Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

OpenCV: Masking Operation Does not Function Properly

I have an image which I want to crop, for this I am using masking operation with copyTo() function. Here is the code block that does the operation:

// ROI by creating mask for the trapezoid
Mat mask = Mat(frame.rows, frame.cols, CV_8UC1, Scalar(0));

// Create Polygon from vertices
approxPolyDP(pointsForTrapezoid, roiPolygonized, 1.0, true);

// Fill polygon white
fillConvexPoly(mask, &roiPolygonized[0], roiPolygonized.size(), 255, 8, 0);

// Create new image for result storage
Mat maskedImage = Mat(frame.rows, frame.cols, CV_8UC3);
frame.copyTo(maskedImage, mask);
return maskedImage;

However, there is something really weird with this. I get different outputs from each run. Sometimes it works and sometimes it does not. Let me explain with snapshots:

This is the correct mask which I generate:

enter image description here

This is the correctly applied mask, after the operation:

enter image description here

And these are the ridiculously applied masks, after the operations:

enter image description here enter image description here enter image description here

As you can see, sometimes the masking operation works, and sometimes it does not. I don't know what the hell is wrong with OpenCV, but this shouldn't happen. Same code with same input should not create different output on each run. I suspect that copyTo() function is messed up.

Any thoughts?

OpenCV: Masking Operation Does not Function Properly

I have an image which I want to crop, for this I am using masking operation with copyTo() function. Here is the code block that does the operation:

// ROI by creating mask for the trapezoid
Mat mask = Mat(frame.rows, frame.cols, CV_8UC1, Scalar(0));

// Create Polygon from vertices
approxPolyDP(pointsForTrapezoid, roiPolygonized, 1.0, true);

// Fill polygon white
fillConvexPoly(mask, &roiPolygonized[0], roiPolygonized.size(), 255, 8, 0);

// Create new image for result storage
Mat maskedImage = Mat(frame.rows, frame.cols, CV_8UC3);
frame.copyTo(maskedImage, mask);
return maskedImage;

However, there is something really weird with this. I get different outputs from each run. Sometimes it works and sometimes it does not. Let me explain with snapshots:

This is the correct mask which I generate:

enter image description here

This is the correctly applied mask, after the operation:

enter image description here

And these are the ridiculously applied masks, after the operations:

enter image description here enter image description here enter image description here

As you can see, sometimes the masking operation works, and sometimes it does not. I don't know what the hell is wrong with OpenCV, but this shouldn't happen. Same code with same input should not create different output on each run. I suspect that copyTo() function is messed up.

Any thoughts?