This article describes an example implementation of the python edge expansion method as follows:
import cv2 # big_pad=True: edge padding when target image height and width are both larger than the original image # big_pad=False: scale to the smallest scale of the target size before edge filling # borderType=cv2.BORDER_CONSTANT: indicates constant fill, borderValue is fill constant 0~255 (black~white) # borderType=cv2.BORDER_REPLICATE: Border Replication Fill # borderType=cv2.BORDER_REFLECT: Border Reflection Fill # borderType=cv2.BORDER_WRAP: Border Wrap Fill def image_padding(image, target_shape, big_pad=True, borderType=cv2.BORDER_REFLECT, borderValue=(0, 0, 0)): # Target size size ph, pw = target_shape # Original image size h, w, _ = if big_pad and ph > h and pw > w: # Edge fill centered on the original image top = bottom = (ph - h) // 2 # Get the top and bottom fill sizes top += (ph - h) % 2 # To ensure target size, +1 if not divisible left = right = (pw - w) // 2 left += (pw - w) % 2 # To ensure target size, ditto upper left + 1 image_padded = (image, top, bottom, left, right, borderType=borderType, value=borderValue) else: # Minimum scaled fills (large sizes: larger changes in height/width ratios will be filled, small sizes vice versa) # Calculate image size after scaling scale = min(pw/w, ph/h) # Get the minimum ratio of height/width changes nw, nh = int(scale * w), int(scale * h) # Scale the original image to the smallest percentage of the target size img_resized = (image, (nw, nh)) top = bottom = (ph - nh) // 2 # Get the top and bottom fill sizes top += (ph - nh) % 2 # To ensure target size, +1 if not divisible left = right = (pw - nw) // 2 left += (pw - nw) % 2 # To ensure target size, ditto upper left + 1 image_padded = (img_resized, top, bottom, left, right, borderType=borderType, value=borderValue) return image_padded if __name__ == "__main__": path = './2_2.png' img = (path) img_pad = image_padding(img, (640,640)) ('./1_BORDER_WRAP.png',img_pad) # ('./1_.png',img_pad[64:576,64:576])
original figure
BORDER_WRAP
REFLECT
to this article on the python edge expansion way to achieve the example of the article is introduced to this, more related python edge expansion content please search my previous articles or continue to browse the following related articles I hope you will support me more in the future!