简体   繁体   English

numpy 将数组宽度调整为零

[英]numpy resize array width by zeros

I'm a typical user of R, but in python I'm stuck.我是 R 的典型用户,但在 python 中我被卡住了。

I have a lot of images saved as NumPy array I need to resize the pad of array/images to 4k resolution from different widths which oscillated between 1620 to 2800 , the height is constant: 2160 .我有很多图像保存为 NumPy 数组我需要将数组/图像的填充调整为 4k 分辨率,从在16202800之间振荡的不同宽度,高度是恒定的: 2160

I need to resize the pad of each array/image to 3840*2160 , ie.我需要将每个数组/图像的焊盘大小调整为3840*2160 ,即。 add a black border on right and left side, so that the array/image itself remains unchanged.在左右两侧添加黑色边框,使数组/图像本身保持不变。

For resizing I try this, but the code adds black edges to all sides.为了调整大小,我尝试了这个,但代码在所有边都添加了黑色边缘。

arr = np.array([[1,1,1],[1,1,1],[1,1,1],[1,1,1]])
FinalWidth = 20 

def pad_with(vector, pad_width, iaxis, kwargs):
    pad_value = kwargs.get('padder', 0)
    vector[:pad_width[0]] = pad_value

arr2 = np.pad(arr,FinalWidth/2,pad_with)

I think you just need hstack , assuming you want half the width to go on either side:我认为你只需要hstack ,假设你想要一半宽度到 go 两侧:

def pad_with(vector, pad_width):
    temp = np.hstack((np.zeros((vector.shape[0], pad_width//2)), vector))
    return np.hstack((temp, np.zeros((vector.shape[0], pad_width//2))))
arr2 = pad_with(arr,FinalWidth)
arr2 
>>> array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0.]])
arr2.shape
>>> (4, 23)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM