Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Yes, a binary mask with the shape of the trapezoid (or quadrilateral) filled in is the way to go. Please refer to this question for details.

Firstly, create a single-channel matrix filled with black. Then, use fillPoly or fillConvexPoly to paint the trapezoid area white. Finally, use this matrix as the mask for OpenCV methods that support mask matrix, or use bitwise operations to preprocess or post-process images for OpenCV methods that do not support mask matrix. The details are described in the link mentioned above.

The reason why irregular masking cannot be handled the same way as rectangular ROI is due to the low-level algorithm coding.

Please read: Array slicing (computer programming) - article on Wikipedia

When a rectangular sub-region of a matrix is processed by an algorithm, it can be implemented a two-level for-loop over its rows and columns. The choice of the rectangular sub-region affects the lower and upper limits of the two level for-loops. Aside from that, the code needed for processing the rectangular region can be surprisingly similar to the code needed for processing the whole matrix.

For irregularly-shaped regions, it would not be sufficient just to control the lower and upper limits of the two-level for-loop. Instead, each pixel has to be checked for its region membership - whether it is inside the region or outside. An algorithm that performs this check is equivalent to an algorithm that relies on a user-provided mask matrix to define the irregularly-shaped region.

If you would like to rectify a trapezoid-shaped object, you can use OpenCV geometrical transforms so that the trapezoid-shaped object will be flattened out to a rectangle.

Thanks to StevenPuttemans, thdrksdfthmn and kbarni for providing the details for this answer.