Search code examples
opencvroi

Obtain rectangle ROI from object/mask opencv


I aim to obtain a ROI from a Mat. This Mat is expected to have a expected convex silhouette inside it. As example:

enter image description here

Being the red rectangle the ROI I want to obtain, in order to cut this part of the image and work only with it.

I've tried using a mask from this silhouette; create a new Mat, and then copy it using the mask, but this doesn't work since I want to reduce my image size, not only to have the data of this ROI:

enter image description here

It also has the another problem: found another little areas in the mask. This would be avoided if I could have only the ROI I want.

Any ideas about how to do it? I wonder if I can get the ROI from the mask I've used here, and calculate the ROI around the biggest area or something like that, but don't know if that's possible or how to face to code it.

Thank you in advance


Solution

  • I just found out how to do it!

    1º Find contours from my mask.

    2º Take the one with bigger area.

    3º Find his bounding rectangle using boundingrect()

    4º Create a new Mat with this size and copy this ROI to it.

    References:

    boundingRect