Anton Mulder
Anton Mulder

Reputation: 215

C++ | Change color in cv::mat with setTo

I have a cv::Mat file with vec3b values. These values are colours from an image. I'd like to change some colours in that image.

I know the setTo() function for normal matrix manipulation, but how do I use it for my Mat file?

I tried something like this:

 image = image.setto(Vec3b(0,0,0), image == Vec3b(255,0,0))

Thx!

Upvotes: 5

Views: 13464

Answers (1)

Alexey
Alexey

Reputation: 5978

Given an image image, we want to find all the pixels in image that are equal to Scalar(255,0,0) and then set these pixels to Scalar(0,0,0).

  • First we need to obtain mask, such that a location in mask is set to 255 if the corresponding location in image equals Scalar(255,0,0), otherwise it is set to 0. This can be achieved with inRange() function.

    Mat mask;
    inRange(image, Scalar(255,0,0), Scalar(255,0,0), mask);
    
  • Now apply setTo() function to image.

    image.setTo(Scalar(0,0,0), mask);
    

Upvotes: 8

Related Questions