【问题标题】:Training my simple model for colored images instead of grayscale为彩色图像而不是灰度图像训练我的简单模型
【发布时间】:2020-03-21 08:40:46
【问题描述】:

我是 Python 和 Keras 深度学习的新手。通过一些关于猫与非猫分类的在线教程,我能够为我的分类编译这个简单的训练代码。但是,我的目标应用程序是火灾检测,所以我认为我需要使用彩色图像而不是这个灰度版本(+ 会有帮助吗?!)。换句话说,摆脱img = img.convert('L') 并使用颜色进行训练。

当我尝试将频道数量增加到3 时,我遇到了这个错误:

training_images = np.array([i[0] for i in training_data]).reshape(-1, IMAGE_SIZE, IMAGE_SIZE, 3)
ValueError: could not broadcast input array from shape (300,300,3) into shape (300,300)

我该如何解决这个错误?

这是我原来的训练代码:

from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from PIL import Image
from random import shuffle, choice
import numpy as np
import os

IMAGE_SIZE = 256
IMAGE_DIRECTORY = './data/test_set'

def label_img(name):
  if name == 'cats': return np.array([1, 0])
  elif name == 'notcats' : return np.array([0, 1])

def load_data():
  print("Loading images...")
  train_data = []
  directories = next(os.walk(IMAGE_DIRECTORY))[1]

  for dirname in directories:
    print("Loading {0}".format(dirname))
    file_names = next(os.walk(os.path.join(IMAGE_DIRECTORY, dirname)))[2]

    for i in range(200):
      image_name = choice(file_names)
      image_path = os.path.join(IMAGE_DIRECTORY, dirname, image_name)
      label = label_img(dirname)
      if "DS_Store" not in image_path:
        img = Image.open(image_path)
        img = img.convert('L')
        img = img.resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS)
        train_data.append([np.array(img), label])

  return train_data

def create_model():
  model = Sequential()
  model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', 
                   input_shape=(IMAGE_SIZE, IMAGE_SIZE, 1)))
  model.add(MaxPooling2D(pool_size=(2,2)))
  model.add(BatchNormalization())
  model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
  model.add(MaxPooling2D(pool_size=(2,2)))
  model.add(BatchNormalization())
  model.add(Conv2D(128, kernel_size=(3,3), activation='relu'))
  model.add(MaxPooling2D(pool_size=(2,2)))
  model.add(BatchNormalization())
  model.add(Conv2D(128, kernel_size=(3,3), activation='relu'))
  model.add(MaxPooling2D(pool_size=(2,2)))
  model.add(BatchNormalization())
  model.add(Conv2D(64, kernel_size=(3,3), activation='relu'))
  model.add(MaxPooling2D(pool_size=(2,2)))
  model.add(BatchNormalization())
  model.add(Dropout(0.2))
  model.add(Flatten())
  model.add(Dense(256, activation='relu'))
  model.add(Dropout(0.2))
  model.add(Dense(64, activation='relu'))
  model.add(Dense(2, activation = 'softmax'))

  return model

training_data = load_data()
training_images = np.array([i[0] for i in training_data]).reshape(-1, IMAGE_SIZE, IMAGE_SIZE, 1)
training_labels = np.array([i[1] for i in training_data])

print('creating model')
model = create_model()
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print('training model')
model.fit(training_images, training_labels, batch_size=50, epochs=10, verbose=1)
model.save("model.h5")

【问题讨论】:

  • 如果你的图片已经是彩色的(RGB),只需 cmets #img = img.convert('L') # img = img.resize((IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS)跨度>
  • 我猜没那么简单。 input_shape=(IMAGE_SIZE, IMAGE_SIZE, 1) 和其他人怎么样?
  • 我认为你需要对图像进行预处理以适应网络,否则你会得到不匹配的形状

标签: python tensorflow keras deep-learning classification


【解决方案1】:

为了转换图像,您必须复制单个图像的通道。请注意,您只需要“复制通道后的转换图像。 您可以编写一个执行以下操作的函数并将其传递给理解列表

>>> img = np.random.randint(low=0,high=255, size=(330,330))
>>> converted=np.empty([330,330,3], dtype=int)
>>> red = img.copy()
>>> blue = img.copy()
>>> green = img.copy()
>>> converted[:,:,0]= red
>>> converted[:,:,1]= blue
>>> converted[:,:,2]= green
>>> from PIL import Image
>>> s = Image.fromarray(converted,'RGB')
>>> s.save("rand_image.png")
>>> s.show()

【讨论】:

  • 好吧,我的图片已经上色了。我的意思是如何更改代码以接受颜色。现在,如果您看到,它会将它们转换为灰度。
  • 对不起,我的错...你希望它们是灰度的吗?
  • 您想将 training_data 样本从 300,300 更改为 300,300,3 形状吗?
  • 是的,没错。摆脱img = img.convert('L') 并使用颜色进行训练。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2015-11-20
  • 2013-07-28
  • 2011-12-28
  • 1970-01-01
  • 2014-09-11
相关资源
最近更新 更多