[英]Apply mask to image with OpenCv Python
i'm trying to use opencv with python and I have this problem: 我正在尝试将opencv与python一起使用,但我遇到了这个问题:
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. 我有一个图像和一个二进制蒙版(具有0和255的单通道图像),我想迭代蒙版的每个像素,并根据蒙版像素的值对原始图像执行一些操作。 How can I use the numpy optimization to do that?
如何使用numpy优化来做到这一点?
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: 例如,假设我要创建一个新图像,如果蒙版中的像素值为0,则每个像素保持不变;如果蒙版中的像素为255,则将像素设置为(0,0,255),例如:
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? 我如何使用numpy对此进行优化? Thank you very much
非常感谢你
We can use np.where
after extending the mask to 3D
that let's it do the choosing in a broadcasted manner - 在将遮罩扩展到
3D
之后,我们可以使用np.where
,让我们以广播的方式进行选择-
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
- 或与原始代码保持更近的距离,进行复制,然后与
mask
一并分配-
result = originalImage.copy()
result[mask!=0] = (0,0,255)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.