OpenCV Operations on Images
Arithmetic Operations
Brightness
# Create a matrix with constant intensity.
matrix = np.ones(img.shape, dtype = 'uint8') * 30
# Create brighter and darker images.
img_brighter = cv2.add(img, matrix)
img_darker = cv2.subtract(img, matrix)
# Display the images
plt.figure(figsize = [18,5])
plt.subplot(131); plt.imshow(img_darker[:, :, ::-1]); plt.title('Darker')
plt.subplot(132); plt.imshow(img[:, :, ::-1]); plt.title('Original')
plt.subplot(133); plt.imshow(img_brighter[:, :, ::-1]); plt.title('Brighter');
Contrast
# Create matrices with a constant scale factor.
matrix_ones = np.ones(img.shape, dtype = 'float64')
# Create lower and higher contrast images.
img_lower = np.uint8(cv2.multiply(np.float64(img), matrix_ones, scale = 0.8))
img_higher = np.uint8(np.clip(cv2.multiply(np.float64(img), matrix_ones, scale = 1.2) , 0, 255))
# Display the images.
plt.figure(figsize = [18,5])
plt.subplot(131); plt.imshow(img_lower[:, :, ::-1]); plt.title('Lower Contrast')
plt.subplot(132); plt.imshow(img[:, :, ::-1]); plt.title('Original')
plt.subplot(133); plt.imshow(img_higher[:, :, ::-1]); plt.title('Higher Contrast');
Bitwise Operations
img_rec = cv2.imread('rectangle.jpg', cv2.IMREAD_GRAYSCALE)
img_cir = cv2.imread('circle.jpg', cv2.IMREAD_GRAYSCALE)
plt.figure(figsize = [20,5])
plt.subplot(121); plt.imshow(img_rec);
plt.subplot(122); plt.imshow(img_cir);
print(img_rec.shape)
result = cv2.bitwise_and(img_rec, img_cir, mask = None)
plt.imshow(result);
result = cv2.bitwise_or(img_rec, img_cir, mask = None)
plt.imshow(result);
result = cv2.bitwise_xor(img_rec, img_cir, mask = None)
plt.imshow(result);
References