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

pep*_*epe 21 python opencv numpy image-processing python-imaging-library

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

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

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

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

在视觉上这将是期望的结果:

在此输入图像描述

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

任何使用cv2,PIL或numpy的建议都是受欢迎的.

Ste*_*uch 26

你可以用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
Run Code Online (Sandbox Code Playgroud)

测试代码:

test_image = Image.open('hLarp.png')
new_image = make_square(test_image)
new_image.show()
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

  • 谢谢,这看起来真的很好,所以`.paste`的原点会居中吗? (3认同)
  • 当然-抓住了它,因为我刚用过它。 (2认同)
  • @ me2beats,我添加了一行以显示如何白色填充。 (2认同)

Dir*_*llu 8

这是使用 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()
Run Code Online (Sandbox Code Playgroud)


inf*_*val 8

PIL.ImageOps.pad

from PIL import Image, ImageOps

with Image.open('hLARP.png') as im:
    im = ImageOps.pad(im, (200, 200), color='black')
im.save('result.png')
Run Code Online (Sandbox Code Playgroud)