简体   繁体   中英

How can I apply mask to a 16bit image?

apply mask like this to an image

How can I apply mask to a 16bit image? It works fine with a 8bit image with this code:

image = misc.imread('test.jpg')
gray = cv2.cvtColor(image, cv2.Color(image, cv2.COLOR_BGR2GRAY)
x = 610
y = 220
w = h = 150
mask = np.zeros(gray.shape[:2], np.uint8)
mask[y:y+h,x:x+w] = 255
res = cv2.bitwise_and(gray, gray, mask = mask)
cv2.imshow("res", res)
cv2.waitKey(0)

But when I try to do it with a 16 bit.png picture it doesn't work. I tried this code:

mask = np.zeros(gray.shape[:2], np.uint16)
mask[y:y+h, x:x+w] = 6535
res = cv2.bitwise_and(gray, gray, mask = mask)

I get the error:

res = cv2.bitwise_and(gray, gray, mask = mask) cv2.error: /home/... : error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function binary_op

Does anybody know how I can apply a mask to my 16 bit image?

According to the OpenCV documentation , mask needs to be 8-bit:

– optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed. –可选的操作掩码,8位单通道数组,用于指定要更改的输出数组的元素。

The error message seems to reflect that,

res = cv2.bitwise_and(gray, gray, mask = mask) cv2.error: /home/... : error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function binary_op

since it tells you that the date type of your mask needs to be either 8-bit unsigned or 8-bit signed (integer).

So the definition of your mask needs to be

mask = np.zeros(gray.shape[:2], np.uint8)
mask[y:y+h,x:x+w] = 255

like before.

Try

mask = np.zeros(gray.shape[:2], np.uint16)
mask[y:y+h, x:x+w] = 1
res = gray * mask

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM