Ask Your Question
1

How to replace information in a mat based on a mask?

asked 2014-10-02 07:00:08 -0600

thdrksdfthmn gravatar image

updated 2015-08-25 18:47:38 -0600

I have an image, and a mask. I want to remove the information in the image in the mask area.

cv::Mat plateMat = imgIn(theRect); // theRect is the roi in the input image
cv::Mat plateMsk = cv::Mat::zeros(imgIn.rows, imgIn.cols, CV_8UC1);
cv::fillPoly(plateMsk, shapeContour, 255); // shape contour is marking the region that I want to remove
int yIdx = 0;
for (int i = plateY; i < plateY + plateH; i++)
{
  int xIdx = 0;
  for (int j = plateX; j < plateX + plateW; j++)
  {
    if (plateMsk.ptr<uchar>(i)[j] == 255)
    { // I am adding green for better visualization
      retImage.ptr<cv::Vec3b>(i)[j][0] = 0;
      retImage.ptr<cv::Vec3b>(i)[j][1] = 255;
      retImage.ptr<cv::Vec3b>(i)[j][2] = 0;
    }
    xIdx++;
  }
  yIdx++;
}

I have done it in for loops, but I think that it is a better way (optimized in OpenCV mode), but right now I have no idea. Can you help me a little?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
3

answered 2014-10-02 10:33:58 -0600

kbarni gravatar image

In this particular case I would suggest to draw the shapeContour directly on the resulting image with 0. Something like:

cv::fillPoly(retImage, shapeContour, 0);

It takes much less time (no need to recopy) and uses less memory (no need for mask image).

Otherwise if you already got the mask image (0=delete, otherwise 255), you could use the per element matrix operations:

Result = Image & Mask;

where Result, Image and Mask are matrices.

To use an alpha channel, use the matrix multiplication with Mask values between 0 and 1:

Result = Image.mul(Mask);

This way you can even combine two images using a mask:

Result = Image1 & Mask + Image2 & ~Mask;
edit flag offensive delete link more

Comments

I do not know why I have not thought of fillPoly, because I use it to create the mask... doh! Thanks :)

thdrksdfthmn gravatar imagethdrksdfthmn ( 2014-10-02 10:42:20 -0600 )edit

Question Tools

Stats

Asked: 2014-10-02 07:00:08 -0600

Seen: 8,590 times

Last updated: Oct 02 '14