Sandeep Sreenivasan
Sandeep Sreenivasan

Reputation: 21

How to pad images to a specific size like 720*576 with a pixel value/border value?

I have images of various sizes like 122*98, 98*65, 320*256, 620*540. How to make all images to a fixed size say 720*576 by padding them with border/some pixel value? Is there a generic way to do it which works for input images of any size? I tried some methods using PIL module, but didn't get a generic solution.

Upvotes: 1

Views: 464

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207485

I am assuming you are pretty tool-agnostic since you have tagged with OpenCV, PIL/Pillow and skimage, so I would suggest just using ImageMagick on the command line:

So, starting with these images as 1.png, 2.png and 3.png:

enter image description here

enter image description here

enter image description here

You can make an output directory and put them all in the North-West corner of a magenta background:

mkdir output
magick mogrify -path output -background magenta -extent 720x576 [123].png

enter image description here

Or, put them all in the centre of a yellow background:

magick mogrify -path output -gravity center -background yellow  -extent 720x576 [123].png

enter image description here

Omit the -path output if you want the files overwritten in place.

Omit the word magick if running v6 or older.


If you specifically want to do it in Python, one way is to make a solid canvas of the correct size and padding colour that you want as an output image and then paste your image onto that canvas, either at top-left or centred using some simple maths.

Another option is PIL/Pillow's ImageOps.expand() like here.

Upvotes: 2

Shawn Mathew
Shawn Mathew

Reputation: 2337

You're looking for the cv2.remap() function. This function has a parameter that let's you define a constant border value. The Opencv tutorial at https://docs.opencv.org/3.4/d1/da0/tutorial_remap.html should give you enough info to start. The if-block ind == 0: in the tutorial resizes the image by 50%. You should be able to use this to get the fixed size of 720x576.

Upvotes: 0

Related Questions