5

i'm trying to use opencv with python and I have this problem:

I have an image and a binary mask (single channel image with 0s and 255) I want to iterate each pixel of the mask and perform some operations on the original image based on the value of the masks pixel. How can I use the numpy optimization to do that?

For example, suppose I want to create a new image where each pixel remains the same if its value in the mask is 0, or its set to (0,0,255) if the pixel in the mask is 255, like:

def inpaint(originalImage, mask):
    [rows, columns, channels] = originalImage.shape
    result = np.zeros((rows,columns,channels))
    for row in range(rows):
        for column in range(columns):
            if(mask[row,column]==0):
                result[row,column] = originalImage[row,column]
            else:
                result[row,column] = (0,0,255)
    return result

How can I optimize this using numpy? Thank you very much

1 Answer 1

7

We can use np.where after extending the mask to 3D that let's it do the choosing in a broadcasted manner -

np.where(mask[...,None]==0, originalImage,[0,0,255])

Or staying closer to the original code, make a copy and then assign in one go with the mask -

result = originalImage.copy()
result[mask!=0] = (0,0,255)
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very mutch, it seems to work but if I try to use imshow it shows a black image, and if I use resize() I get this error: cv2.error: OpenCV(3.4.1) C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\imgproc\src\resize.cpp:3922: error: (-215) func != 0 in function cv::hal::resize
@FedericoTaschin I think you need to convert to uint8 type with result.astype(np.uint8)
Howevr, the second way works! Thank you very much! I have another question: what if I wanted to perform a more complex operation on each pixel, that involves more than a simple assignment, for example calling a function?
@FedericoTaschin Have you figured out how to perfom the more complex operation on each pixel by calling a function? Mind sharing it here?
No, I switched to Java opencv because of some of the operations that were too complex to be done in python without built-in functions

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.