简体   繁体   English

OpenCV 和 Python:在图像上覆盖彩色蒙版

[英]OpenCV & Python: Cover a colored mask over a image

I want to cover a image with a transparent solid color overlay in the shape of a black-white mask我想用黑白蒙版形状的透明纯色覆盖覆盖图像

Currently I'm using the following java code to implement this.目前我正在使用以下java代码来实现这一点。

redImg = new Mat(image.size(), image.type(), new Scalar(255, 0, 0));
redImg.copyTo(image, mask);

I'm not familiar with the python api.我不熟悉python api。

So I want to know if there any alternative api in python.所以我想知道python中是否有任何替代api。 Is there any better implementation?有没有更好的实现方式?

image:图片:

源图片

mask:面具:

面具

what i want:我想要的是:

我想要的是

Now after I deal with all this Python, OpenCV, Numpy thing for a while, I find out it's quite simple to implement this with code:现在,在我处理了所有这些 Python、OpenCV、Numpy 的事情一段时间后,我发现用代码实现它非常简单:

image[mask] = (0, 0, 255)

-------------- the original answer -------------- -------------- 原来的答案 --------------

I solved this by the following code:我通过以下代码解决了这个问题:

redImg = np.zeros(image.shape, image.dtype)
redImg[:,:] = (0, 0, 255)
redMask = cv2.bitwise_and(redImg, redImg, mask=mask)
cv2.addWeighted(redMask, 1, image, 1, 0, image)

The idea is to convert the mask to a binary format where pixels are either 0 (black) or 255 (white).这个想法是将掩码转换为像素为0 (黑色)或255 (白色)的二进制格式。 White pixels represent sections that are kept while black sections are thrown away.白色像素代表保留的部分,而黑色部分被丢弃。 Then set all white pixels on the mask to your desired BGR color.然后将蒙版上的所有白色像素设置为所需的BGR颜色。

Input image and mask输入图像和蒙版

Result结果

Code代码

import cv2

image = cv2.imread('1.jpg')
mask = cv2.imread('mask.jpg', 0)
mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
image[mask==255] = (36,255,12)

cv2.imshow('image', image)
cv2.imshow('mask', mask)
cv2.waitKey()

this is what worked for me:这对我有用:

red = np.ones(mask.shape)
red = red*255
img[:,:,0][tmask>0] = red[mask>0]

so I made a 2d array with solid 255 values and replaced it with my image's red band in pixels that my mask is not zero.所以我制作了一个具有 255 个实心值的二维数组,并将其替换为我的图像的红色带(以像素为单位),我的掩码不为零。 redmask红面具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM