Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply mask to image with OpenCv Python

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

like image 545
Federico Taschin Avatar asked Apr 25 '18 16:04

Federico Taschin


1 Answers

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)
like image 108
Divakar Avatar answered Sep 18 '22 04:09

Divakar