簡體   English   中英

將 3D 數組圖像轉換為二維數組

[英]Convert 3D array image into 2D array

我正在嘗試通過from tensorflow.keras.preprocessing import image 。我的圖像是我寫在紙上的手寫數字,然后我通過手機從中拍攝了一張照片,然后將其大小更改為 28*28:

手寫數字 7

我使用了以下代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM