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

标签 c++ image opencv image-resizing

有没有一种方法可以调整任何形状或大小的图像,比如 [500x500] 但保持图像的纵横比,让空白区域用白色/黑色填充物填充?

假设图像是 [2000x1000],在调整大小为 [500x500] 后,实际图像本身将是 [500x250] , 125 两边都是白色/黑色填充物。

像这样:

输入

enter image description here

输出

enter image description here

编辑

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

我遇到的唯一一个类似的问题是 this post ,但它在 php 中。

最佳答案

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

EDIT 处理不是 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;
}

关于c++ - 将图像调整为正方形但保持纵横比 c++ opencv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28562401/

相关文章:

python - Python OpenCV-过滤掉不在附近的轮廓

python - Python:solvePnP()没有足够的值可解包?

c++ - std::is_trivially_xxx 其中一个暗示另一个

c++ - 引用结构数组

c++ - 编译器何时以及为什么会在 malloc/free/new/delete 上将内存初始化为 0xCD、0xDD 等?

java - 向文件写入/读取一系列不同的序列化对象

c++ - 未解析的外部符号 cvFindChessboardCorners()

c++ - 如何按第一个元素降序对<int,对<int,int>>对数组进行排序?

Java DataInputStream 到图像文件

Android 使用 OnClick 从 SD 卡中删除图像