Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple method to highlight the mask?

If I have mask like

And I have a image( the size is same to the mask) like

Mathematica graphics

I want to hightlight the mask in the image. If I'm in other Language,I just

As you can see, the result image have a transparent red show the mask. I hope implement this in OpenCV. So I write this code

#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;
}

But as you see, I use a alpha value in Scalar, but it is not a transparent red.

Maybe this is due to the srcImg just have 3 channels. I have two question about this

  1. How to hightlight the mask with a transparent red(even the image just have 3 channels)?
  2. I have to draw circle pixel by pixel to do this thing?
like image 629
yode Avatar asked Sep 07 '17 19:09

yode


2 Answers

#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

like image 109
sturkmen Avatar answered Sep 28 '22 08:09

sturkmen


I've written this in python but you can easily port it to C++. Assuming that your source and mask images are CV_8UC3 images:

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

like image 25
zindarod Avatar answered Sep 28 '22 08:09

zindarod