MLMLTL MLMLTL - 1 year ago 491
C++ Question

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

but have the image's aspect ratio be maintained, levaing the empty space be filled with white/black filler?

So say the image is
, after getting resized to
making the actual image itself would be
, with
either side being white/black filler.

Something like this:


enter image description here


enter image description here


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

Answer Source

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;
        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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download