2

I have an image img. I also have a mask with value 255 at all the places where I want to retain the pixel values of img are 0 at all other places.

I want to use these two images viz. the mask and img such that I create a matrix with original img values at places where the mask is 255, and the value -1 at all places where mask is 0.

So, far, I have written this:

maskedImg = cv2.bitwise_and(img, mask)

but the maskedImg has 0 at all the places where the mask has 0. How can I get the value -1 instead of 0 at all the other places using a fast bitwise operation?

5
  • 1
    swap the mask around (bitwise not) and bitwise or it with the image Commented Dec 17, 2017 at 20:53
  • @MadPhysicist thanks for the comment. If I swap the mask and the or the mask with the image, I will have the value 255 at all the places outside the mask. I want the value -1 at all those other places outside the mask. Commented Dec 17, 2017 at 21:05
  • 2
    not sure why you prefer -1... but OpenCV usually uses uint8 for most of the images, including masks, so probably you have to change the type frist.... for it to be able to have -1 Commented Dec 17, 2017 at 21:48
  • @Londonguy. 255 is -1 to all intents and purposes. Commented Dec 17, 2017 at 22:00
  • Also, as @api55 pointed out, you need to indicate the type of your image and tell us what how far you are willing to go in of conversions. Commented Dec 17, 2017 at 22:04

1 Answer 1

2

I don't know what is your image's dtype. Default is np.uint8, so you cann't set -1 on the result, it underflows to -1 + 256 = 255. That is to say, if the dtype is np.uint8, you cann't set it to negative value.

If you want to set to -1, you should change the dtype.

#masked = cv2.bitwise_and(img, mask).astype(np.int32)
masked = np.int32(img)
masked[mask==0] = -1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.