Search code examples
c++opencvcrop

Crop an image causes outofbounds error


I am trying to crop an image. Sometimes the calculated cropped image outreach the initial size (since the cropping is calculated by the use of a distance). How is it possible instead of receiving an out of bounds error, to fill the rest with black (the same effect as in wrapAffine rotation).


Solution

  • Well, cropping is by definition reducing the size of an image. So if you want to potentially extend the image at the same time, and fill it with black, you could enlarge it first. Something like the following algorithm:

    1. Take maximal bounding box of the original image and the crop rect
    2. Create an empty (black) image of the new dimensions
    3. Copy the original image into the black image
    4. Crop the resulting image

    You could wrap this up into a class and give it the same interface as the crop filter, then you would have a generic solution.