Search code examples
c++imageopencvimage-resizing

Resize an image to a square but keep aspect ratio c++ opencv


Is there a way of resizing images of any shape or size to say [500x500] but have the image's aspect ratio be maintained, levaing the empty space be filled with white/black filler?

So say the image is [2000x1000], after getting resized to [500x500] making the actual image itself would be [500x250], with 125 either side being white/black filler.

Something like this:

Input

enter image description here

Output

enter image description here

EDIT

I don't wish to simply display the image in a square window, rather have the image changed to that state and then saved to file creating a collection of same size images with as little image distortion as possible.

The only thing I came across asking a similar question was this post, but its in php.


Solution

  • Not fully optimized, but you can try this:

    EDIT handle target size that is not 500x500 pixels and wrapping it up as a function.

    cv::Mat GetSquareImage( const cv::Mat& img, int target_width = 500 )
    {
        int width = img.cols,
           height = img.rows;
    
        cv::Mat square = cv::Mat::zeros( target_width, target_width, img.type() );
    
        int max_dim = ( width >= height ) ? width : height;
        float scale = ( ( float ) target_width ) / max_dim;
        cv::Rect roi;
        if ( width >= height )
        {
            roi.width = target_width;
            roi.x = 0;
            roi.height = height * scale;
            roi.y = ( target_width - roi.height ) / 2;
        }
        else
        {
            roi.y = 0;
            roi.height = target_width;
            roi.width = width * scale;
            roi.x = ( target_width - roi.width ) / 2;
        }
    
        cv::resize( img, square( roi ), roi.size() );
    
        return square;
    }