是否有一种简单的方法来突出面具?

时间:2017-09-07 19:25:10

标签: c++ opencv image-processing

如果我有面具

我有一个图像(大小与面具相同),如

Mathematica graphics

我想高亮显示图像中的蒙版。如果我使用其他语言,我只是

如您所见,结果图像有一个透明红色显示蒙版。我希望在OpenCV中实现它。所以我写了这段代码

#include <opencv.hpp>

using namespace cv;
using namespace std;

int main() {
    Mat srcImg = imread("image.jpg");
    Mat mask = imread("mask.jpg", IMREAD_GRAYSCALE)>200;

    for(int i=0;i<srcImg.rows;i++)
        for(int j=0;j<srcImg.cols;j++)
            if(mask.at<uchar>(i, j)==255)
                circle(srcImg, Point(j,i), 3, Scalar(0, 0, 128,128));
    imshow("image",srcImg);

    waitKey();
    return 0;
}

但是如您所见,我在Scalar中使用了alpha值,但它不是透明红色

也许这是因为srcImg只有3个频道。我对此有两个问题

  1. 如何使用透明红色高亮显示遮罩(即使图像只有3个通道)?
  2. 我必须逐像素地绘制circle来做这件事吗?

2 个答案:

答案 0 :(得分:2)

#include<opencv2/core.hpp>
#include<opencv2/imgproc.hpp>
#include<opencv2/highgui.hpp>

using namespace cv;

int main(int argc, char** argv)
{
    Mat srcImg = imread("image.png");
    Mat mask = imread("mask.png", IMREAD_GRAYSCALE) > 200;

    Mat red;
    cvtColor(mask, red, COLOR_GRAY2BGR);
    red = (red - Scalar(0, 0, 255)) / 2;
    srcImg = srcImg - red;

    imshow("image", srcImg);

    waitKey();
    return 0;
}

enter image description here

答案 1 :(得分:1)

我已经在python中编写了这个,但你可以很容易地将它移植到C ++。假设您的sourcemask图片为CV_8UC3图片:

src = cv2.imread("source.png", -1)
mask = cv2.imread("mask.png", -1)

# convert mask to gray and then threshold it to convert it to binary
gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 40, 255, cv2.THRESH_BINARY)

# find contours of two major blobs present in the mask
im2,contours,hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

# draw the found contours on to source image
for contour in contours:
    cv2.drawContours(src, contour, -1, (255,0,0), thickness = 1)

# split source to B,G,R channels
b,g,r = cv2.split(src)

# add a constant to R channel to highlight the selected area in reed
r = cv2.add(b, 30, dst = b, mask = binary, dtype = cv2.CV_8U)

# merge the channels back together
cv2.merge((b,g,r), src)

result