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

时间:2017-05-28 19:29:44

标签: python opencv numpy image-processing python-imaging-library

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

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

调整大小时必须输出一个方形(1:1)图像,其中包含:

  • 调整后的图像垂直居中
  • 维持宽高比
  • 剩余像素呈现黑色

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

enter image description here

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

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

4 个答案:

答案 0 :(得分:19)

您可以使用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))

结果:

enter image description here

答案 1 :(得分:3)

PIL具有缩放方法,可以保持纵横比。从那里你只需要将它粘贴在你的黑色背景矩形中心。

from PIL import Image

def black_background_thumbnail(path_to_image, thumbnail_size=(200,200)):
    background = Image.new('RGBA', thumbnail_size, "black")    
    source_image = Image.open(path_to_image).convert("RGBA")
    source_image.thumbnail(thumbnail_size)
    (w, h) = source_image.size
    background.paste(source_image, ((thumbnail_size[0] - w) / 2, (thumbnail_size[1] - h) / 2 ))
    return background

if __name__ == '__main__':
    img = black_background_thumbnail('hLARP.png')
    img.save('tmp.jpg')
    img.show()

答案 2 :(得分:0)

from PIL import Image

def reshape(image):
    '''
    Reshapes the non-square image by pasting
    it to the centre of a black canvas of size
    n*n where n is the biggest dimension of
    the non-square image. 
    '''
    old_size = image.size
    max_dimension, min_dimension = max(old_size), min(old_size)
    desired_size = (max_dimension, max_dimension)
    position = int(max_dimension/2) - int(min_dimension/2) 
    blank_image = Image.new("RGB", desired_size, color='black')
    if image.height<image.width:
        blank_image.paste(image, (0, position))
    else:
        blank_image.paste(image, (position, 0))
    return blank_image

答案 3 :(得分: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()