0
votes

I know this is very simple but i just cant make it work in Opencv. I have 2 images of same size, one in RGB and other in black and white. The black and white image is obtained after some transformation in Opencv. Now i want to map the black white image to the RGB image and only keep the pixel corresponding to the white pixel in the black and white image. The black is simply discarded.

In C# its easy but since i am using c++ opencv, I want to do it in openCV. How can i do it?

In c# is like this:

for(i = 0; i < image.lenght; i+=4)
{
if(img_bw != 255)
image[i] = 0;image[i+1] = 0;image[i+2] = 0;
}
2
Have a look to the at operator to access Mat elements linkAndrea Riccardi
You could use a library which offers a logical "and" function. I don't know if OpenCV do it, but I know IPP does. Using "and" will save you the for loop. RGB && BW == what_you_want. If you choose to do it this way you will have to be careful with the image formats though.CTZStef

2 Answers

3
votes
cv::Mat blackAndWhiteMask = ...; // You black and white image
cv::Mat image = imread("original_image.jpg"); // Your original image
cv::Mat result;
image.copyTo(result, blackAndWhiteMask);
image = result;
2
votes

Based on http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html

cv::Mat bw = ...;
cv::Mat clr = ...;  // clr.size() == bw.size()

for(int i = 0; i < bw.rows; ++ i)
{
    uchar* bw_r = bw.ptr<uchar>(i);
    cv::Vec3b* clr_r = clr.ptr<Vec3b>(i);
    for(int j = 0; j < bw.cols; ++j)
        if(br_r[j] != 255)
            clr_r[j] = cv::Vec3b(0, 0, 0);
}