(nb_samples, rows, columns, channels)
。其中 nb_samples
表示圖像(或者樣本)的總數,rows
, columns
, 和 channels
分別表示圖像的行數、列數和通道數。path_to_tensor
函數實現以下將彩色圖像的字符串型的文件路徑做爲輸入,返回一個4維張量,做爲 Keras CNN 輸入。由於咱們的輸入圖像是彩色圖像,所以它們具備三個通道( channels
爲 3
)。
(1, 224, 224, 3)
。paths_to_tensor
函數將圖像路徑的字符串組成的 numpy 數組做爲輸入,並返回一個4維張量,各維度尺寸爲 (nb_samples, 224, 224, 3)
。 在這裏,nb_samples
是提供的圖像路徑的數據中的樣本數量或圖像數量。你也能夠將 nb_samples
理解爲數據集中3維張量的個數(每一個3維張量表示一個不一樣的圖像。
from keras.preprocessing import image from tqdm import tqdm def path_to_tensor(img_path): # 用PIL加載RGB圖像爲PIL.Image.Image類型 img = image.load_img(img_path, target_size=(224, 224)) # 將PIL.Image.Image類型轉化爲格式爲(224, 224, 3)的3維張量 x = image.img_to_array(img) # 將3維張量轉化爲格式爲(1, 224, 224, 3)的4維張量並返回 return np.expand_dims(x, axis=0)
#img_paths是個可迭代的量
def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)] return np.vstack(list_of_tensors)