将矩形图像调整为正方形,保持比例并用黑色填充背景 [英] Resize rectangular image to square, keeping ratio and fill background with black

查看:1960
本文介绍了将矩形图像调整为正方形,保持比例并用黑色填充背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调整一组256 x N像素的灰度图像(N变化,但始终≤256)。

I'm trying to resize a batch of grayscale images that are 256 x N pixels (N varies, but is always ≤256).

我的目的是缩小图像尺寸。

My intention is to downscale the images.

调整尺寸必须输出一个正方形(1:1) )图像,带:

The resize would have to output a square (1:1) image, with:


  • 垂直居中的图像调整大小

  • 保持纵横比

  • 剩余像素呈现黑色

视觉上这将是理想的结果:

Visually this would be the desired result:

我尝试使用目标尺寸创建一个numpy零点矩阵(例如200 x 200)但是无法将调整后的图像粘贴到垂直中心。

I have tried creating a numpy zeroes matrix with the target size (e.g. 200 x 200) but have not been able to paste the resized image into its vertical center.

欢迎任何使用cv2,PIL或numpy的建议。

Any suggestions using cv2, PIL or numpy are welcome.

推荐答案

您可以使用 PIL

from PIL import Image

def make_square(im, min_size=256, fill_color=(0, 0, 0, 0)):
    x, y = im.size
    size = max(min_size, x, y)
    new_im = Image.new('RGBA', (size, size), fill_color)
    new_im.paste(im, ((size - x) / 2, (size - y) / 2))
    return new_im



测试代码:



Test Code:

test_image = Image.open(hLarp.png')
new_image = make_square(test_image)
new_image.show()



< h3>结果:

Result:

这篇关于将矩形图像调整为正方形,保持比例并用黑色填充背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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