Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize rectangular image to square, keeping ratio and fill background with black

I'm trying to resize a batch of grayscale images that are 256 x N pixels (N varies, but is always ≤256).

My intention is to downscale the images.

The resize would have to output a square (1:1) image, with:

  • resized image centered vertically
  • aspect ratio maintained
  • remaining pixels rendered black

Visually this would be the desired result:

enter image description here

I have tried creating a numpy zeroes matrix with the target size (e.g. 200 x 200) but have not been able to paste the resized image into its vertical center.

Any suggestions using cv2, PIL or numpy are welcome.

like image 476
pepe Avatar asked May 28 '17 19:05

pepe


2 Answers

You can use Pillow to accomplish that:

Code:

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 Code:

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

For a white background you can do:

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

Result:

enter image description here

like image 59
Stephen Rauch Avatar answered Sep 27 '22 01:09

Stephen Rauch


Here is a code that solve your question with OPENCV module (using NUMPY module too)

#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() 
like image 37
Diroallu Avatar answered Sep 27 '22 01:09

Diroallu