[英]Convert 3D array image into 2D array
我正在尝试通过from tensorflow.keras.preprocessing import image
。我的图像是我写在纸上的手写数字,然后我通过手机从中拍摄了一张照片,然后将其大小更改为 28*28:
我使用了以下代码:
img_width, img_height = 28, 28
img = image.load_img('rgb_seven.jpeg', target_size=(img_width, img_height))
img_tensor = image.img_to_array(img)
img_tensor.shape
形状结果是:
(28, 28, 3)
似乎图像被加载为3D 数组。 我需要一个2D array ,所以我这样做:
x_image = img_tensor.reshape(len(img_tensor),-1)
x_image.shape
结果是:
(28, 84)
为什么是84 ? 我需要 28,因为我想将其展平以作为输入层插入。
什么是问题?
您应该使用color_mode='grayscale'
加载图像
img = image.load_img('rgb_seven.jpeg', color_mode='grayscale', target_size=(img_width, img_height))
它会给你形状(28, 28, 1)
然后使用x_image = img_tensor.reshape(28, 28)
会给你形状(28, 28)
你得到形状(28, 84)
的原因是因为reshape()
不会删除维度,所以如果你想使用img_tensor.reshape(28,-1)
用(28, 28, 3)
重塑数组它会返回一个数组作为最后两个维度的组合,因此你得到形状(28, 28 * 3)
您应该使用tf.squeeze
而不是reshape
。 Tensorflow 专门制作了一个 function 来删除指定的尺寸,因此我认为最好使用这个。
img = image.load_img('rgb_seven.jpeg',
color_mode='grayscale',
target_size=(img_width, img_height))
img_tensor = image.img_to_array(img)
img_tensor = tf.squeeze(img_tensor, axis=-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.