Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...