# Revision history [back]

### 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);


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?

 2 retagged sturkmen 6547 ●3 ●44 ●75 https://github.com/stu...

### 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);

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.