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:
This is the correctly applied mask, after the operation:
And these are the ridiculously applied masks, after the operations:
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?
I suppose it is normal: you are copying a 4 channel Mat to a 3 channel Mat. Be sure your frame has 3 channels:
if (frame.channel() != 3) { std::cout << "not 3 channel" << std::endl; return cv::Mat; }
looks like leftover memory to me. again, it does not copy, where the mask is 0
try to put zeros into your maskedImage before
Mat::zero() is a static function, that returns a new image. (so, that had no effect)
try :
Mat maskedImage = Mat(frame.rows, frame.cols, CV_8UC3, Scalar::all());
(easier to read/understand)