aboutsummaryrefslogtreecommitdiff
path: root/util.py
blob: e50d342af04c5a674b84506a5933da688b786b95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 10 17:39:12 2019

@author: franklin
"""

import numpy as np
import cv2

def clipAndConvert(img):
  img = np.clip(img, 0, 255)
  img = img.astype('uint8')
  return img

def normalizeAndConvert(img):
  return cv2.normalize(img, None, alpha = 0, beta = 255, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_8U)

def showResized(window, img):
  if img is not None:
    scaled = cv2.resize(clipAndConvert(img), (512, 512))
    cv2.imshow(window, scaled)

# scale colors of an image so lights are lighter and darks are darker
def increaseContrast(img, s = 1.1):
  img = img.astype('float32')
  img = ((img - 128) * s + 128)
  #print(img)
  return img

def averageColorOfRegion(im, x1, x2, y1, y2):
  # Find the average color of a rectangular region
  region = im[y1:y2,x1:x2]
  return np.average(np.average(region, axis=0), axis = 0)

# OpenCV stores colors as BGR
RED_COMP = 2
GREEN_COMP = 1
BLUE_COMP = 0

# Color space mapping information
# 
# These variables describe how the camera and projector colors map to
# each other.
#
# More specifically, we have six variables which describe the mapping:
#
# camera_Rmin, camera_Rmax
# camera_Gmin, camera_Gmax
# camera_Bmin, camera_Bmax
#
# R_min, G_min, and B_min are obtained by projecting a black image
# (R,G,B=0). The three maximums are obtained by projecting pure red,
# green, and blue. X_min and X_max describe the camera's color
# response when shown a zero X component or a 255 R component,
# respectively.
#
# We can then model the projector -> camera mapping as
#
# camera_R = camera_Rmin + (R_max - R_min) / 255 * projector_R
#
# The reverse mapping is
#
# projector_R = (camera_R - camera_Rmin) / (camera_Rmax - camera_Rmin) * 255

# image is a 3D numpy array [y, x, color]
# black is the minimum B, G, R components
# maxColors is the maximum B, G, R components

# this will return an unnormalized float32 matrix
# map camera colors to projector color space
def cameraToProjectorColor(image, black, maxColors):
  return (image - black).astype('float32') * 255 / (maxColors - black)
  #print (maxColors - black)
  #return image

# inverse of the above
# projector color to camera color
def projectorToCameraColor(image, black, maxColors):
  return black + (maxColors - black) / 255 * image.astype('float32')