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

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

    You can create another image of the square size you wish, then put your image in the middle of the square image. Something like this:

    #include 
    #include 
    #include "opencv2/imgproc/imgproc.hpp"
    
    int main(int argc, char *argv[])
    {
        // read an image
        cv::Mat image1= cv::imread("/home/hdang/Desktop/colorCode.png");
    
        //resize it
        cv::Size newSize = cv::Size(image1.cols/2,image1.rows/2);
        cv::resize(image1, image1, newSize, 0, 0, cv::INTER_LINEAR);
    
        //create the square container
        int dstWidth = 500;
        int dstHeight = 500;
        cv::Mat dst = cv::Mat(dstHeight, dstWidth, CV_8UC3, cv::Scalar(0,0,0));
    
        //Put the image into the container, roi is the new position
        cv::Rect roi(cv::Rect(0,dst.rows*0.25,image1.cols,image1.rows));
        cv::Mat targetROI = dst(roi);
        image1.copyTo(targetROI);
    
        //View the result
        cv::namedWindow("OpenCV Window");
        cv::imshow("OpenCV Window", dst);
    
        // wait key for 5000 ms
        cv::waitKey(5000);
    
        return 0;
    }
    

提交回复
热议问题