将图像转换为CNN的数组

Mar*_*aou 4 python neural-network scikit-image conv-neural-network keras

我正在尝试使用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)
Run Code Online (Sandbox Code Playgroud)

我将如何将图像转换为数组?每列都是一张图片?任何帮助都会有所帮助.

Max*_*xim 11

对于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)
Run Code Online (Sandbox Code Playgroud)

不确定如何存储标签,但您还需要制作一系列标签.我叫它y_train.您可以将其转换为热门,如下所示:

y_train = keras.utils.to_categorical(y_train, num_classes)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

可在此处找到完整的MNIST示例.