Anja
Anja

Reputation: 345

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?

Upvotes: 0

Views: 2066

Answers (2)

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

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

mask – optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.

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.

Upvotes: 2

Aleksey Petrov
Aleksey Petrov

Reputation: 370

Try

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

Upvotes: 1

Related Questions