[英]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.