pycharm实现猫狗图像分类识别的代码
时间: 2023-12-11 21:08:03 浏览: 183
基于Python实现猫狗图像分类(CNN-DNN-RNN)【100011892】
5星 · 资源好评率100%
以下是使用PyCharm实现猫狗图像分类识别的代码:
```python
import os
import cv2
import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator
# 设置路径
train_dir = 'train/'
test_dir = 'test/'
train_cats_dir = os.path.join(train_dir, 'cats')
train_dogs_dir = os.path.join(train_dir, 'dogs')
test_cats_dir = os.path.join(test_dir, 'cats')
test_dogs_dir = os.path.join(test_dir, 'dogs')
# 定义模型
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(512, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
# 数据预处理
train_data_gen = ImageDataGenerator(rescale=1./255)
test_data_gen = ImageDataGenerator(rescale=1./255)
train_generator = train_data_gen.flow_from_directory(train_dir, target_size=(150, 150), batch_size=20, class_mode='binary')
test_generator = test_data_gen.flow_from_directory(test_dir, target_size=(150, 150), batch_size=20, class_mode='binary')
# 训练模型
history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=30, validation_data=test_generator, validation_steps=50)
# 测试模型
img = cv2.imread('test/cat.1.jpg')
img = cv2.resize(img, (150, 150))
img = np.reshape(img, [1, 150, 150, 3])
classes = model.predict_classes(img)
print(classes)
```
这段代码会训练一个卷积神经网络模型,用于猫狗图像分类识别。训练数据和测试数据存储在`train/`和`test/`文件夹中,每个文件夹分别有`cats/`和`dogs/`两个子文件夹,存储着不同类别的图像。模型训练完成后,可以使用`cv2.imread()`读取一张图像,将其转换为模型需要的格式,然后使用`model.predict_classes()`方法预测其类别。
阅读全文