如何重塑3D numpy数组? [英] How to reshape a 3D numpy array?

查看:97
本文介绍了如何重塑3D numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组的列表,这些数组实际上是我的CNN的输入图像。但是,我的每个图像的大小都不一致,并且我的CNN仅拍摄尺寸为224X224的图像。如何将每个图像重塑为给定尺寸?
print(train_images [key] .reshape(224,224,3))

I have a list of numpy arrays which are actually input images to my CNN. However size of each of my image is not cosistent, and my CNN takes only images which are of dimension 224X224. How do I reshape each of my image into the given dimension? print(train_images[key].reshape(224, 224,3))

给我输出

ValueError:新数组的总大小必须保持不变

我会

推荐答案

在重塑时,新数组应该具有相同数量的值。您需要的是裁剪图片(如果图片大于224x224)和填充(如果图片小于224x224)或在两种情况下都调整大小。

New array should have the same amount of values when you are reshaping. What you need is cropping the picture (if it is bigger than 224x224) and padding (if it is smaller than 224x224) or resizing on both occasions.

裁剪只是在切片正确的索引:

Cropping is simply slicing with correct indexes:

def crop(np_img, size):
    v_start = round((np_img.shape[0] - size[0]) / 2)
    h_start = round((np_img.shape[1] - size[1]) / 2)
    return np_img[v_start:v_start+size[1], h_start:h_start+size[0],:]

填充稍微复杂一点,这将创建一个零形状的数组,并插入其中的图像值:

Padding is slightly more complex, this will create a zeros array in desired shape and plug in the values of image inside:

def pad_image(np_img, size):
    v_start = round((size[0] - np_img.shape[0]) / 2)
    h_start = round((size[1] - np_img.shape[1]) / 2)

    result = np.zeros(size)
    result[v_start:v_start+np_img.shape[1], h_start:h_start+np_img.shape[0], :] = np_img

    return result

您也可以使用 np.pad 函数:

def pad_image(np_img, size):
    v_dif = size[0] - np_img.shape[0]
    h_dif = size[1] - np_img.shape[1]
    return np.lib.pad(np_img, ((v_dif, 0), (h_dif, 0), (0, 0)), 'constant', constant_values=(0))

您可能意识到填充在两个函数中有些不同,我不想使问题复杂化,仅在第二个函数的顶部和左侧填充。

You may realize padding is a bit different in two functions, I didn't want to over complicate the problem and just padded top and left on the second function. Did the both sides in first one since it was easier to calculate.

最后要进行大小调整,最好使用另一个库。您可以使用 scipy.misc.imresize ,非常简单。应该这样做:

And finally for resizing, you better use another library. You can use scipy.misc.imresize, its pretty straightforward. This should do it:

imresize(np_img, size)

这篇关于如何重塑3D numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆