【问题标题】:Is there a way to preserve pixel values of an image after padding?有没有办法在填充后保留图像的像素值?
【发布时间】:2021-10-05 06:12:09
【问题描述】:

我正在处理两个图像 im0im1,它们分别具有不同的形状 (512, 512,3)(217, 317, 3) .我想在较小的图像上添加填充,以使其大小与另一张相同,但在使用后

im1 = cv2.copyMakeBorder( im1, top = 200, bottom = 95, left = 100, right = 95, borderType=cv2.BORDER_CONSTANT)

我在图像数组中得到 0 个值

print(im1)

  [[[0 0 0]
  [0 0 0]
  [0 0 0]
  ...
  [0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]...

我期望得到现有值加上一些 0,因为填充像

    [[ 34  58  36]
  [ 39  63  41]
  [ 40  64  42]
  ...
  [ 47  81 116]
  [ 47  81 118]
  [ 47  81 118]]

 [[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  ...
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]]

有谁知道解决这个问题,以便我可以同时拥有现有值和填充值?

【问题讨论】:

    标签: python numpy padding


    【解决方案1】:

    您可以为此使用np.pad

    示例

    import numpy as np
    
    img = np.arange(25).reshape((5,5))
    desired_height = 7
    desired_width = 8
    pad_value = 0
    
    height, width = img.shape
    
    print(img)
    
    if height % desired_height != 0:
        padding = ((0, desired_height - (height % desired_height)), (0, 0))
        img = np.pad(img, padding, mode="constant", constant_values=pad_value)
    
    if width % desired_width != 0:
        padding = ((0, 0), (0, desired_width - (width % desired_width)))
        img = np.pad(img, padding, mode="constant", constant_values=pad_value)
    
    print(img)
    

    输出:

    [[ 0  1  2  3  4]
     [ 5  6  7  8  9]
     [10 11 12 13 14]
     [15 16 17 18 19]
     [20 21 22 23 24]]
    
    [[ 0  1  2  3  4  0  0  0]
     [ 5  6  7  8  9  0  0  0]
     [10 11 12 13 14  0  0  0]
     [15 16 17 18 19  0  0  0]
     [20 21 22 23 24  0  0  0]
     [ 0  0  0  0  0  0  0  0]
     [ 0  0  0  0  0  0  0  0]]
    

    【讨论】:

    • 谢谢,成功了!但是为了获得高度和宽度的填充,我只使用了一个 if 语句,并且这样做 if height % desired_height != 0 and width % desired_width != 0:
    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2021-08-03
    • 2021-09-07
    • 2020-12-14
    相关资源
    最近更新 更多