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

后端 未结 4 510
一向
一向 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

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

提交回复
热议问题