Search code examples
pythonnumpyopencvimage-processingpadding

How can I make the image centered while padding in python


I am working on image processing. Since the input images have different sizes, I will crop them to a fixed size of 700x700. However, some images are slightly smaller than 700x700, so I want to apply padding to center the image and fill the surrounding area with black pixels. How can I achieve this?

#Cropping image
if np.shape(c_contour)[0] >= 700 and np.shape(c_contour)[1] >= 700: 
    crop_img = center_contour[center_y - 350:center_y + 350, center_x - 350 :center_x + 350]
else:
    padded_img = np.zeros((700, 700, 3), dtype=np.uint8)
    if np.shape(c_contour)[0] < 700:
        crop_img = center_contour[:, center_x - 350 :center_x + 350]
    else:
        crop_img = center_contour[center_y - 350:center_y + 350, :]
    #####Make the photo center while padding
    #####.....

I tried using cv2.resize(center_contour, (700, 700), interpolation=cv2.INTER_NEAREST). Although the image size becomes 700×700, distortion occurs. I want to maintain the object's original size while ensuring the overall image size is 700×700.


Solution

  • If you know how much to pad before/after the height/width, you can just use np.pad.

    def get_pad(curr_size: int, target_size: int):
        d = target_size - curr_size
        
        if d <= 0: return (0, 0) # no need to pad
    
        p1 = d // 2
        p2 = d - p1
        return (p1, p2)
    
    H, W = 600, 650 # make dummy image    
    image = np.random.randint(0, 255, (H, W, 3), np.uint8)
    
    
    DH, DW = 700, 700 # desired height / width
    padding = (get_pad(H, DH), get_pad(W, DW), (0, 0))
    image_padded = np.pad(image, padding, constant_values=0)