簡體   English   中英

將圖像轉換為 CNN 的數組

[英]Convert image to array for CNN

我正在嘗試使用 CNN 對狗的繁殖識別進行分類。 我已將圖像轉換為灰度並重新縮放它們以縮小尺寸。 所以現在我試圖將它們添加到 numpy 數組中並進行培訓。 此外,我將使用 Relu 激活函數,因為它在多層和分類交叉熵下對不同類別的狗繁殖表現良好。

下面是灰度和重新縮放的代碼:

def RescaleGrayscaleImg():

    # iterate through the names of contents of the folder
    for image_path in os.listdir(path):

        # create the full input path and read the file
        input_path = os.path.join(path, image_path)

        # make image grayscale
        img = io.imread(input_path)
        img_scaled = rescale(img, 2.0 / 4.0)
        GrayImg = color.rgb2gray(img_scaled)

        # create full output path, 'example.jpg' 
        # becomes 'grayscaled_example.jpg', save the file to disk
        fullpath = os.path.join(outPath, 'grayscaled_'+image_path)
        misc.imsave(fullpath, GrayImg)

我將如何將圖像轉換為數組? 每列都是一個圖像嗎?

對於 CNN,您的輸入必須是 4-D 張量[batch_size, width, height, channels] ,因此每個圖像都是 3-D 子張量。 由於您的圖像是灰度的,所以channels=1 同樣對於訓練,所有圖像必須具有相同的大小 - WIDTHHEIGHT

skimage.io.imread返回一個ndarray ,這對 keras 非常有效。 所以你可以像這樣讀取數據:

all_images = []
for image_path in os.listdir(path):
  img = io.imread(image_path , as_grey=True)
  img = img.reshape([WIDTH, HEIGHT, 1])
  all_images.append(img)
x_train = np.array(all_images)

不確定如何存儲標簽,但您還需要制作一系列標簽。 我稱之為y_train 您可以像這樣將其轉換為 one-hot:

y_train = keras.utils.to_categorical(y_train, num_classes)

keras 中的模型非常簡單,這是最簡單的模型(使用 relu 和 x-entropy):

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', 
                 input_shape=[WIDTH, HEIGHT, 1]))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=100, epochs=10, verbose=1)

可以在此處找到完整的 MNIST 示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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