使用OpenCv Python将掩码应用于图像

时间:2018-04-25 16:49:39

标签: python numpy opencv

我试图在python中使用opencv,我遇到了这个问题:

我有一个图像和二进制掩码(0s和255的单通道图像) 我想迭代掩码的每个像素,并根据掩码像素的值对原始图像执行一些操作。 我如何使用numpy优化来做到这一点?

例如,假设我想创建一个新图像,如果掩码中的值为0,则每个像素保持不变;如果掩码中的像素为255,则设置为(0,0,255),如:< / p>

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

如何使用numpy优化此功能? 非常感谢你

1 个答案:

答案 0 :(得分:2)

我们可以在将掩码扩展到3D之后使用np.where,让它以广播的方式进行选择 -

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

或者更接近原始代码,制作副本然后一次性分配mask -

result = originalImage.copy()
result[mask!=0] = (0,0,255)
相关问题