有没有一种方法可以调整任何形状或大小的图像,比如 [500x500]
但保持图像的纵横比,让空白区域用白色/黑色填充物填充?
假设图像是 [2000x1000]
,在调整大小为 [500x500]
后,实际图像本身将是 [500x250]
, 125
两边都是白色/黑色填充物。
像这样:
输入
输出
编辑
我不希望简单地在方形窗口中显示图像,而是将图像更改为该状态,然后保存到文件中,以创建具有尽可能小的图像失真的相同大小图像的集合。
我遇到的唯一一个类似的问题是 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/