猫狗识别python代码
时间: 2023-08-09 12:05:33 浏览: 180
基于小样本学习和迁移学习实现猫狗品种识别分类python源码(课程设计).zip
好的,以下是一个简单的猫狗识别的Python代码,供您参考:
```python
import tensorflow as tf
import os
import numpy as np
import cv2
import random
# 数据集路径
train_dir = 'train'
test_dir = 'test'
# 图像大小
img_size = 50
# 读取数据集
def read_data(dataset_dir):
images = []
labels = []
# 读取猫的图像
cat_dir = os.path.join(dataset_dir, 'cat')
for img_file in os.listdir(cat_dir):
img_path = os.path.join(cat_dir, img_file)
img = cv2.imread(img_path)
img = cv2.resize(img, (img_size, img_size))
images.append(img)
labels.append(0)
# 读取狗的图像
dog_dir = os.path.join(dataset_dir, 'dog')
for img_file in os.listdir(dog_dir):
img_path = os.path.join(dog_dir, img_file)
img = cv2.imread(img_path)
img = cv2.resize(img, (img_size, img_size))
images.append(img)
labels.append(1)
# 打乱数据集
data = list(zip(images, labels))
random.shuffle(data)
images, labels = zip(*data)
# 转换为numpy数组
images = np.array(images)
labels = np.array(labels)
return images, labels
# 构建卷积神经网络模型
def build_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(img_size, img_size, 3)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
return model
# 训练模型
def train_model(train_images, train_labels, model):
model.fit(train_images, train_labels, epochs=10, batch_size=32)
# 测试模型
def test_model(test_images, test_labels, model):
loss, accuracy = model.evaluate(test_images, test_labels)
print('loss:', loss)
print('accuracy:', accuracy)
# 主函数
def main():
# 读取训练集和测试集
train_images, train_labels = read_data(train_dir)
test_images, test_labels = read_data(test_dir)
# 归一化
train_images = train_images / 255.0
test_images = test_images / 255.0
# 构建模型
model = build_model()
# 训练模型
train_model(train_images, train_labels, model)
# 测试模型
test_model(test_images, test_labels, model)
if __name__ == '__main__':
main()
```
以上代码使用了卷积神经网络(CNN)算法,构建了一个简单的猫狗识别模型,并在训练集和测试集上进行了训练和测试。
阅读全文