将矩形图像调整为正方形,保持比例并用黑色填充背景

新手上路,请多包涵

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

我的意图是缩小图像。

调整大小必须输出方形 (1:1) 图像,其中:

  • 调整大小的图像垂直居中
  • 纵横比保持不变
  • 剩余像素呈现黑色

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

在此处输入图像描述

我尝试创建一个具有目标大小(例如 200 x 200)的 numpy 零点矩阵,但无法将调整大小的图像粘贴到其垂直中心。

欢迎使用 cv2、PIL 或 numpy 提出任何建议。

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

阅读 1k
2 个回答

您可以使用 Pillow 来实现:

代码:

 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, (int((size - x) / 2), int((size - y) / 2)))
    return new_im

测试代码:

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

对于白色背景,您可以执行以下操作:

 new_image = make_square(test_image, fill_color=(255, 255, 255, 0))

结果:

在此处输入图像描述

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

这是使用 OPENCV 模块解决您的问题的代码(也使用 NUMPY 模块)

 #Importing modules opencv + numpy
import cv2
import numpy as np

#Reading an image (you can use PNG or JPG)
img = cv2.imread("image.png")

#Getting the bigger side of the image
s = max(img.shape[0:2])

#Creating a dark square with NUMPY
f = np.zeros((s,s,3),np.uint8)

#Getting the centering position
ax,ay = (s - img.shape[1])//2,(s - img.shape[0])//2

#Pasting the 'image' in a centering position
f[ay:img.shape[0]+ay,ax:ax+img.shape[1]] = img

#Showing results (just in case)
cv2.imshow("IMG",f)
#A pause, waiting for any press in keyboard
cv2.waitKey(0)

#Saving the image
cv2.imwrite("img2square.png",f)
cv2.destroyAllWindows()

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

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