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

后端 未结 4 512
一向
一向 2021-02-08 05:50

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 whi

4条回答
  •  孤城傲影
    2021-02-08 06:22

    Alireza's answer is good, however I modified the code slightly so that I don't add the vertical borders when the image fits vertically and I don't add horizontal borders when the image fits horizontally (this is closer to the original request):

    cv::Mat utilites::resizeKeepAspectRatio(const cv::Mat &input, const cv::Size &dstSize, const cv::Scalar &bgcolor)
    {
        cv::Mat output;
    
        // initially no borders
        int top = 0;
        int down = 0;
        int left = 0;
        int right = 0;
        if( h1 <= dstSize.height) 
        {
            // only vertical borders
            top = (dstSize.height - h1) / 2;
            down = top;
            cv::resize( input, output, cv::Size(dstSize.width, h1));
        } 
        else 
        {
            // only horizontal borders
            left = (dstSize.width - w2) / 2;
            right = left;
            cv::resize( input, output, cv::Size(w2, dstSize.height));
        }
    
        return output;
    }
    

提交回复
热议问题