将图像大小调整为正方形但保持纵横比 c opencv

新手上路,请多包涵

有没有办法调整任何形状或大小的图像,比如 [500x500] 但是保持图像的纵横比,用白色/黑色填充物填充空白空间?

So say the image is [2000x1000] , after getting resized to [500x500] making the actual image itself would be [500x250] , with 125 either side being白色/黑色填充物。

像这样的东西:

输入

在此处输入图像描述

输出

在此处输入图像描述

编辑

我不希望简单地在方形窗口中显示图像,而是将图像更改为该状态,然后保存到文件中,创建相同大小的图像集合,同时尽可能减少图像失真。

我遇到的唯一一个类似问题是 这篇文章,但它在 php 中。

原文由 MLMLTL 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 748
1 个回答

没有完全优化,但你可以试试这个:

编辑 处理目标大小不是 500x500 像素并将其包装为函数。

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

原文由 Rosa Gronchi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题