Add padding to images to get them into the same shape

前端 未结 6 1768
野趣味
野趣味 2020-12-31 04:21

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 leng

6条回答
  •  抹茶落季
    2020-12-31 04:38

    Here is another way to do that in Python/OpenCV/Numpy. It uses numpy slicing to copy the input image into a new image of the desired output size and a given offset. Here I compute the offset to do center padding. I think this is easier to do using width, height, xoffset, yoffset, rather than how much to pad on each side.

    Input:

    import cv2
    import numpy as np
    
    # read image
    img = cv2.imread('lena.jpg')
    ht, wd, cc= img.shape
    
    # create new image of desired size and color (blue) for padding
    ww = 300
    hh = 300
    color = (255,0,0)
    result = np.full((hh,ww,cc), color, dtype=np.uint8)
    
    # compute center offset
    xx = (ww - wd) // 2
    yy = (hh - ht) // 2
    
    # copy img image into center of result image
    result[yy:yy+ht, xx:xx+wd] = img
    
    # view result
    cv2.imshow("result", result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    # save result
    cv2.imwrite("lena_centered.jpg", result)
    


提交回复
热议问题