My question is about python and Open CV. Here is my code:
import cv2
import numpy as np
# read image
img = cv2.imread(r"C:\Users\asus\Desktop\20230104200344_6edae.thumb.1000_0.jpg")
# Create a mask the same size as the image
mask = np.zeros(img.shape[:2], dtype=np.uint8)
# Create a circular mask with a radius of 100 and the center at the center of the image.
mask = cv2.circle(mask, (img.shape[1]//2, img.shape[0]//2), 100, 100, -1)
# Perform bitwise operations on the image and mask
masked_img = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow('image', img)
cv2.imshow('mask', mask)
cv2.imshow('masked_image', masked_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
I want to ask about this line particularly:
mask = cv2.circle(mask, (img.shape[1]//2, img.shape[0]//2), 100, 100, -1)
It creates a grey circle on a black background. What if I change it to
mask = cv2.circle(mask, (img.shape[1]//2, img.shape[0]//2), 100, 255, -1)
so it creates a white circle.
When performing bitwise and, I can see why a white color (R=255, G=255, B=255) can be translated to (11111111, 11111111, 11111111) so it can be used to preserve the orginal color. However, if it is grey, (R=100, G=100, B=100), namely (1100100, 1100100, 1100100), I can't really see why it preserves the color. What am I misunderstanding?
You're confused about what a mask is. It's a boolean matrix, as defined here.
The function
cv::bitwise_and
calculates the per-element bit-wise logical conjunction ...dst(I) = src1(I) ∧ src2(I) if mask(I) ≠ 0
The call site is cv2.bitwise_and(img, img, mask=mask)
,
so dst(I)
will simply be src1(I)
(that is, img(I)
)
where mask
is non-zero.
Any non-zero mask value will be treated like
any other non-zero mask value.
Only zero is special.
The mask is boolean, on or off, there is no in-between.