将图像大小调整为正方形,但保持纵横比c ++ opencv [英] Resize an image to a square but keep aspect ratio c++ opencv

查看:1771
本文介绍了将图像大小调整为正方形,但保持纵横比c ++ opencv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 white/black filler?

所以说图像是 [2000x1000] ,在调整大小到 [500x500] 使实际图像本身为 [500x250] 125 任何一面都是白色/黑色填充物。

So say the image is [2000x1000], after getting resized to [500x500] making the actual image itself would be [500x250], with 125 either side being white/black filler.

这样的事情:

输入

输出

编辑

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

I don't wish to simply display the image in a square window, rather have the image changed to that state and then saved to file creating a collection of same size images with as little image distortion as possible.

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

The only thing I came across asking a similar question was this post, but its in php.

推荐答案

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

Not fully optimized, but you can try this:

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

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

这篇关于将图像大小调整为正方形,但保持纵横比c ++ opencv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆