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
Output
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
.
A general approach:
cv::Mat utilites::resizeKeepAspectRatio(const cv::Mat &input, const cv::Size &dstSize, const cv::Scalar &bgcolor)
{
cv::Mat output;
double h1 = dstSize.width * (input.rows/(double)input.cols);
double w2 = dstSize.height * (input.cols/(double)input.rows);
if( h1 <= dstSize.height) {
cv::resize( input, output, cv::Size(dstSize.width, h1));
} else {
cv::resize( input, output, cv::Size(w2, dstSize.height));
}
int top = (dstSize.height-output.rows) / 2;
int down = (dstSize.height-output.rows+1) / 2;
int left = (dstSize.width - output.cols) / 2;
int right = (dstSize.width - output.cols+1) / 2;
cv::copyMakeBorder(output, output, top, down, left, right, cv::BORDER_CONSTANT, bgcolor );
return output;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With