Selection and Masking
# From Selection and Masking Lecture
import numpy as np
import cv2
import scipy.linalg as la
import matplotlib.pyplot as plt
import sys
import tqdm
img_raw = cv2.imread("/work/2x2Rubiks_1.png")
print(img_raw.shape, img_raw.dtype)
img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
img_selected = img_rgb[850:1600, 100:750, :]
img_masking = np.logical_and(np.logical_and(img_rgb[:, :, 0] > 200, img_rgb[:, :, 2] < 100), img_rgb[:, :, 1] < 100)
plt.imshow(img_selected)
plt.figure()
plt.imshow(img_masking)
plt.figure()
img_new = img_rgb.copy()
img_new[img_masking, :] = (0, 0, 0)
plt.imshow(img_new)
plt.figure()
img_selected[:,:,0] = 0
plt.imshow(img_rgb)
# dtypes
# uint8: 0 - 255 total of 256 = 2^8
# float32: 0 - 1, fraction values, can store negative
# bool: 0 or 1, indicates false or true
Background Subtraction
threshold
233 / 255
import numpy as np
import cv2
import scipy.linalg as la
import matplotlib.pyplot as plt
import sys
import tqdm
img_bg = cv2.cvtColor(cv2.imread("/work/2x2Rubiks_BG.png"), cv2.COLOR_BGR2RGB)
plt.figure()
plt.imshow(img_bg)
img_fg = cv2.cvtColor(cv2.imread("/work/2x2Rubiks_2.png"), cv2.COLOR_BGR2RGB)
plt.figure()
plt.imshow(img_fg)
img_sub = np.sqrt(np.sum((img_fg.astype(np.float32) - img_bg.astype(np.float32))**2, -1))
plt.figure()
plt.imshow(img_sub)
img_new = img_fg.copy()
img_new[img_sub < threshold, :] = (0, 0, 0)
plt.figure(figsize=(30,15))
plt.imshow(img_new)