Replace all pixels of a particular color in a C++

2020-07-20 03:49发布

问题:

1) I have a Matrix class

Mat src = imread("/pic.png", 0)

http://i1265.photobucket.com/albums/jj502/anizilla/demo_result.png

I want to replace all the white pixels in the above given image to black.

Is there a way to replace all the pixels with a particular RGB value with another?

2) When I use -

src.col(0).row(0)

I get the proper values. Is there any way to extract value of each RGB channel?

3) When I use -

src.at<Vec2b>(0,0)[0];

I get garbage values (like . and !). I get garbage value if I use <Vec2d>

But. When I use

src.at<Vec2s>(0,0)[0];

I get proper value for channel 0, and,

src.at<Vec2s>(0,0)[1];
src.at<Vec2s>(0,0)[2];

returns garbage numbers

回答1:

This is very simple if you do it right.

  1. Use explicit template instantiation, e.g.

    Mat3b src = imread("/pic.png", 0);
    
  2. Use iterators:

    for (Mat3b::iterator it = src.begin(); it != src.end(); it++) {
        if (*it == Vec3b(255, 255, 255)) {
            *it = Vec3b(0, 0, 0);
        }
    }
    

Sorry, the first proposed solution (src.setTo(newMat, (src == old));) only works with single-channel matrices.



标签: c++ opencv