【问题标题】:Enlarge numpy image and fill extra space with zeros放大 numpy 图像并用零填充额外的空间
【发布时间】:2018-03-15 11:37:19
【问题描述】:

我正在处理图像列表image_listimage_list 中的每个项目都是一个形状为 (X, Y, 3) 的 numpy 数组。 X为高度,Y为宽度,每张图片有3个颜色通道。

我想获取所有图像的最大宽度和高度,并调整每个图像的大小,如果有多余的空间,则底部和右侧都用 0 填充。我可以做第一部分(获得最大高度和最大宽度),但我正在努力处理第二部分(调整大小并用零填充右侧和底部的多余区域)。

max_height = 0
max_width = 0
for image in image_list:
    shape = image.shape
    if shape[0] > max_height:
        max_height = shape[0]
    if shape[1] > max_width:
        max_width = shape[1]

要调整大小,我试过了:

image.resize((max_height, max_width, 3))

但这只是有时有效。其他时候,您会多次重复获得相同的图像。

【问题讨论】:

    标签: python image numpy computer-vision


    【解决方案1】:

    方法#1

    这是一种方法,A 是图像的输入列表 -

    M,N = np.max([i.shape[:2] for i in A],0)
    M_ext = [M-i.shape[0] for i in A]
    N_ext = [N-i.shape[1] for i in A]
    out = [img3D_pad(a,M_ext[i],N_ext[i]) for i,a in enumerate(A)]
    

    辅助函数-

    def img3D_pad(a,m,n):
        return np.pad(a,((0,m),(0,n),(0,0)),'constant')
    

    验证

    1) 形状验证:

    In [108]: A = [np.random.randint(11,99,(4,5,3)), np.random.randint(11,99,(2,6,3))]
    
    In [109]: [i.shape for i in out]
    Out[109]: [(4, 6, 3), (4, 6, 3)]
    

    2) 价值验证:

    In [110]: A[0][...,0]
    Out[110]: 
    array([[53, 64, 41, 13, 85],
           [74, 53, 88, 47, 54],
           [35, 26, 93, 68, 80],
           [38, 68, 50, 83, 77]])
    
    In [111]: out[0][...,0]
    Out[111]: 
    array([[79, 33, 41, 16, 76,  0],
           [11, 49, 54, 56, 40,  0],
           [38, 43, 98, 95, 23,  0],
           [26, 26, 20, 59, 53,  0]])
    
    In [112]: A[1][...,0]
    Out[112]: 
    array([[76, 44, 29, 20, 91, 71],
           [71, 90, 11, 51, 81, 22]])
    
    In [113]: out[1][...,0]
    Out[113]: 
    array([[57, 11, 42, 95, 87, 75],
           [15, 70, 88, 88, 41, 95],
           [ 0,  0,  0,  0,  0,  0],
           [ 0,  0,  0,  0,  0,  0]])
    

    方法 #2

    基于zeros-initialization的简化版-

    M,N = np.max([i.shape[:2] for i in A],0)
    out = [img3D_create(a,M,N) for i,a in enumerate(A)]
    

    辅助函数-

    def img3D_create(a,M,N):
        p,q,r = a.shape
        out = np.zeros((M,N,r),dtype=a.dtype)
        out[:p,:q] = a
        return out
    

    【讨论】:

      猜你喜欢
      • 2019-11-29
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      相关资源
      最近更新 更多