猫狗识别实战项目代码:使用卷积神经网络进行图像分类
以下是一个猫狗识别实战项目的代码框架,包括数据集准备、数据预处理、模型搭建与训练、训练结果可视化、模型预测和展示等步骤。
## 2.1 项目数据集
# 导入必要的库
import os
import cv2
import numpy as np
# 设置数据集路径
data_dir = 'path_to_dataset'
# 定义猫狗类别
categories = ['cat', 'dog']
# 创建数据集
dataset = []
# 遍历数据集文件夹
for category in categories:
path = os.path.join(data_dir, category)
class_num = categories.index(category)
for img in os.listdir(path):
try:
img_array = cv2.imread(os.path.join(path, img))
img_resized = cv2.resize(img_array, (100, 100))
dataset.append([img_resized, class_num])
except Exception as e:
pass
# 随机打乱数据集
np.random.shuffle(dataset)
# 分割数据集为训练集和测试集
train_data = dataset[:8000]
test_data = dataset[8000:]
## 2.2 数据预处理
# 提取特征和标签
x_train = []
y_train = []
for features, label in train_data:
x_train.append(features)
y_train.append(label)
x_test = []
y_test = []
for features, label in test_data:
x_test.append(features)
y_test.append(label)
# 数据归一化
x_train = np.array(x_train) / 255.0
x_test = np.array(x_test) / 255.0
# 数据重塑
x_train = x_train.reshape(-1, 100, 100, 3)
y_train = np.array(y_train)
x_test = x_test.reshape(-1, 100, 100, 3)
y_test = np.array(y_test)
## 3.1 卷积神经网络模型
# 导入必要的库
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
# 创建卷积神经网络模型
model = Sequential()
# 添加卷积层和池化层
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# 添加全连接层
model.add(Flatten())
model.add(Dense(units=128, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
## 3.2 模型搭建
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
## 3.3 模型训练
# 训练模型
model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
## 4.1 训练集和测试集的损失率变化
import matplotlib.pyplot as plt
# 获取训练集和测试集的损失率
train_loss = model.history.history['loss']
test_loss = model.history.history['val_loss']
# 可视化损失率变化
plt.plot(train_loss, label='Training Loss')
plt.plot(test_loss, label='Test Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
## 4.2 训练集和测试集的准确率变化
# 获取训练集和测试集的准确率
train_acc = model.history.history['accuracy']
test_acc = model.history.history['val_accuracy']
# 可视化准确率变化
plt.plot(train_acc, label='Training Accuracy')
plt.plot(test_acc, label='Test Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
## 5.1 模型预测
# 随机选择一张测试集图片进行预测
import random
index = random.randint(0, len(x_test) - 1)
image = x_test[index]
label = y_test[index]
prediction = model.predict(np.expand_dims(image, axis=0))
if prediction[0][0] <= 0.5:
predicted_label = 'cat'
else:
predicted_label = 'dog'
## 5.2 预测展示
# 显示预测结果
plt.imshow(image)
plt.title(f'Label: {categories[label]}, Predicted: {predicted_label}')
plt.axis('off')
plt.show()
## 6.1 图片预测
# 读取图片并进行预处理
img = cv2.imread('path_to_image')
img_resized = cv2.resize(img, (100, 100))
img_normalized = img_resized / 255.0
img_reshaped = np.expand_dims(img_normalized, axis=0)
# 进行预测
prediction = model.predict(img_reshaped)
if prediction[0][0] <= 0.5:
predicted_label = 'cat'
else:
predicted_label = 'dog'
## 6.2 图片识别网页
# 使用Flask构建一个简单的网页应用,用于上传图片并展示预测结果
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def upload_file():
file = request.files['file']
img = cv2.imdecode(np.fromstring(file.read(), np.uint8), cv2.IMREAD_COLOR)
img_resized = cv2.resize(img, (100, 100))
img_normalized = img_resized / 255.0
img_reshaped = np.expand_dims(img_normalized, axis=0)
prediction = model.predict(img_reshaped)
if prediction[0][0] <= 0.5:
predicted_label = 'cat'
else:
predicted_label = 'dog'
return render_template('index.html', prediction=predicted_label)
if __name__ == '__main__':
app.run(debug=True)
请注意,上述代码框架中的路径和参数需要根据实际情况进行修改和调整。此外,还需要安装相关的库和框架,如OpenCV、NumPy、TensorFlow和Flask等。
原文地址: https://www.cveoy.top/t/topic/o9ot 著作权归作者所有。请勿转载和采集!