用python和opencv写一个基于卷积神经网络的疲劳驾驶识别检测+数据集
时间: 2024-02-17 10:03:58 浏览: 161
下面是一个基于卷积神经网络的疲劳驾驶识别检测的Python代码,包括数据集的生成和模型的训练和测试:
```
import cv2
import os
import numpy as np
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.utils import to_categorical
# 生成数据集
def load_dataset(dataset_path, img_size):
# 读取数据集
images = []
labels = []
for foldername in os.listdir(dataset_path):
label = int(foldername)
folderpath = os.path.join(dataset_path, foldername)
for filename in os.listdir(folderpath):
imagepath = os.path.join(folderpath, filename)
image = cv2.imread(imagepath)
image = cv2.resize(image, (img_size, img_size))
images.append(image)
labels.append(label)
images = np.array(images, dtype=np.float32) / 255.0
labels = np.array(labels, dtype=np.int32)
return images, labels
# 划分数据集
def split_dataset(images, labels, test_size):
x_train, x_test, y_train, y_test = train_test_split(images, labels, test_size=test_size, random_state=42)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
return x_train, x_test, y_train, y_test
# 定义模型
def create_model(img_size, num_classes):
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(img_size, img_size, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# 训练模型
def train_model(x_train, y_train, x_test, y_test, batch_size, epochs):
model = create_model(x_train.shape[1], y_train.shape[1])
model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=epochs, batch_size=batch_size)
return model
# 测试模型
def test_model(model, images, labels):
loss, acc = model.evaluate(images, labels, verbose=0)
return acc
# 主函数
if __name__ == '__main__':
dataset_path = 'dataset'
img_size = 32
test_size = 0.2
batch_size = 32
epochs = 10
num_classes = 2
images, labels = load_dataset(dataset_path, img_size)
x_train, x_test, y_train, y_test = split_dataset(images, labels, test_size)
model = train_model(x_train, y_train, x_test, y_test, batch_size, epochs)
acc = test_model(model, x_test, y_test)
print('Test accuracy:', acc)
```
在这个代码中,我们首先使用`load_dataset`函数读取数据集,然后使用`split_dataset`函数划分数据集,接着使用`create_model`函数定义模型,使用`train_model`函数训练模型,最后使用`test_model`函数测试模型。其中,`num_classes`表示数据集中的类别数,本例中为2(疲劳和非疲劳),可以根据实际情况进行修改。
需要注意的是,在运行代码之前,需要先准备好数据集,将疲劳和非疲劳的图像分别放在两个不同的文件夹中,并将这两个文件夹放在一个名为`dataset`的文件夹下。
希望对你有所帮助!
阅读全文