Resize a rectangular image per square, save the ratio and fill the background with black

I am trying to resize a series of images in grayscale that are 256 x N pixels in size (N changes, but always ≤256).

My intention is to reduce the images.

When resizing, you should get a square image (1: 1) with:

  • vertical centered image
  • aspect ratio is maintained
  • remaining pixels are displayed in black

Visually, this will be the desired result:

enter image description here

I tried to create a matrix with zero zeros with a target size (for example, 200 x 200), but could not insert the resized image into its vertical center.

Any suggestions using cv2, PIL or numpy are welcome.

+13
3

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

+17

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
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
0

Source: https://habr.com/ru/post/1678077/


All Articles