Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding borders to an image using python

I have a large number of images of a fixed size (say 500*500). I want to write a python script which will resize them to a fixed size (say 800*800) but will keep the original image at the center and fill the excess area with a fixed color (say black).

I am using PIL. I can resize the image using the resize function now, but that changes the aspect ratio. Is there any way to do this?

like image 266
Nihar Sarangi Avatar asked Jun 21 '12 16:06

Nihar Sarangi


People also ask

Can you add a border to an image?

Simply click on the “Edit a photo” button from the homepage to get started. Then upload the photo you want to edit. Once the photo is uploaded, click on “Frames“ located on the left of the panel, and you'll see a ton of photo borders and frames. You can add colored borders, patterned borders, and even outline borders.

How do I add a border to an image in OpenCV?

To add borders to the images OpenCV has a package copyMakeBorder which helps to make a border around the image. Parameters of copyMakeBorder: inputImage. topBorderWidth.


1 Answers

You can create a new image with the desired new size, and paste the old image in the center, then saving it. If you want, you can overwrite the original image (are you sure? ;o)

import Image  old_im = Image.open('someimage.jpg') old_size = old_im.size  new_size = (800, 800) new_im = Image.new("RGB", new_size)   ## luckily, this is already black! new_im.paste(old_im, ((new_size[0]-old_size[0])//2,                       (new_size[1]-old_size[1])//2))  new_im.show() # new_im.save('someimage.jpg') 
like image 69
heltonbiker Avatar answered Sep 22 '22 22:09

heltonbiker