如何用 RGB 图像训练 CNN

How to train CNN with an RGB Image

我目前正在构建一个 CNN 来区分烂苹果和正常苹果。我觉得如果我能用 rgb 图像给 CNN 提供很大的好处。但是,我到底需要改成下面的网络什么?

 x = tf.placeholder('float', [None, 784])
#y = tf.placeholder(tf.float32, shape=(), name="init")
y = tf.placeholder('int32')

keep_rate = 0.8
keep_prob = tf.placeholder(tf.float32)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')

def maxpool2d(x):
    #                        size of window         movement of window
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')



def convolutional_neural_network(x):
    weights = {'W_conv1':tf.Variable(tf.random_normal([5,5,1,32])),
               'W_conv2':tf.Variable(tf.random_normal([5,5,32,64])),
               'W_fc':tf.Variable(tf.random_normal([7*7*64,1024])),
               'out':tf.Variable(tf.random_normal([1024, n_classes]))}

    biases = {'b_conv1':tf.Variable(tf.random_normal([32])),
               'b_conv2':tf.Variable(tf.random_normal([64])),
               'b_fc':tf.Variable(tf.random_normal([1024])),
               'out':tf.Variable(tf.random_normal([n_classes]))}

    x = tf.reshape(x, shape=[-1, 28, 28, 1])

    print("test")
    print(x)
    conv1 = tf.nn.relu(conv2d(x, weights['W_conv1']) + biases['b_conv1'])
    conv1 = maxpool2d(conv1)

    conv2 = tf.nn.relu(conv2d(conv1, weights['W_conv2']) + biases['b_conv2'])
    conv2 = maxpool2d(conv2)

    fc = tf.reshape(conv2,[-1, 7*7*64])
    fc = tf.nn.relu(tf.matmul(fc, weights['W_fc'])+biases['b_fc'])
    fc = tf.nn.dropout(fc, keep_rate)

    output = tf.matmul(fc, weights['out'])+biases['out']
    return output

我曾尝试更改某些值,但我不断收到一个又一个错误。该网络目前打算拍摄 28 x 28 通道 1 灰度图像。

灰度和 RGB 图像之间的唯一区别是波段数,分别为 1 和 3。

因此,您的 CNN 必须将 3 个波段作为输入,而不是 1 个。其余的将被处理。

在不编写代码 运行 的情况下,您至少需要更改:

weights = {'W_conv1':tf.Variable(tf.random_normal([5,5,3,32]))
x = tf.reshape(x, shape=[-1, 28, 28, 3])