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

后端 未结 4 511
一向
一向 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:32

    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;
    }
    

提交回复
热议问题