Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add padding to images to get them into the same shape

l have a set of images of different sizes (45,50,3), (69,34,3), (34,98,3). l want to add padding to these images as follows:

Take the max width and length of the whole images then put the image in that size

import os import glob import cv2  input_path="/home/images" os.chdir(indput_path) images=glob.glob("*.png") Length=[] Width=[] for img in images:     img=cv2.imread(img)     width,length=img.shape[0:2]     Length.append(length)     Width.append(width) W=max(Width) L=max(Length) 

How can l add padding in opencv so that all the images will have the same size? In the example l gave the images will get the shape of (69,98,3)

like image 435
vincent Avatar asked Apr 13 '17 11:04

vincent


People also ask

How do I resize an image using padding in Python?

If you want to resize an image but do not want to change the aspect ratio or trim it, you can adjust the size by adding padding to the top, bottom, left, and right of the image. You can pad an image by using new() and paste() of the Python image processing library Pillow (PIL).

What is IMG shape in Python?

img.shape returns (Height, Width, Number of Channels) where. Height represents the number of pixel rows in the image or the number of pixels in each column of the image array. Width represents the number of pixel columns in the image or the number of pixels in each row of the image array.


1 Answers

You can use:

image = cv2.copyMakeBorder(src, top, bottom, left, right, borderType) 

Where src is your source image and top, bottom, left, right are the padding around the image.

You can use max(sizes) - size value of the image in a while loop to add the padding to each image. The bordertype can be one of these:

  • cv2.BORDER_CONSTANT
  • cv2.BORDER_REFLECT
  • cv2.BORDER_REFLECT_101
  • cv2.BORDER_DEFAULT
  • cv2.BORDER_REPLICATE
  • cv2.BORDER_WRAP

cv2.copyMakeBorder tutorial

like image 69
Azade Farshad Avatar answered Oct 08 '22 11:10

Azade Farshad