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)
这是使用 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)
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)