我可以为您推荐几个适合口罩识别的公开数据集,并给出相应的数据加载代码示例:
推荐数据集:
- Kaggle - Face Mask Detection Dataset
# Kaggle数据集链接
# https://www.kaggle.com/datasets/andrewmvd/face-mask-detection
- MaskedFace-Net数据集
# 数据集链接
# https://github.com/cabani/MaskedFace-Net
数据加载代码示例(以Kaggle数据集为例):
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET
# 数据集路径
dataset_path = './face-mask-detection/'
def parse_annotation(annotation_path):
tree = ET.parse(annotation_path)
root = tree.getroot()
# 提取标签信息
for obj in root.findall('object'):
label = obj.find('name').text
return label
def load_dataset(dataset_path):
images = []
labels = []
# 遍历数据集
for filename in os.listdir(os.path.join(dataset_path, 'images')):
if filename.endswith('.jpg'):
# 图片路径
img_path = os.path.join(dataset_path, 'images', filename)
# 对应标注文件
xml_path = os.path.join(dataset_path, 'annotations', filename.replace('.jpg', '.xml'))
# 读取图片
image = tf.io.read_file(img_path)
image = tf.io.decode_image(image, channels=3)
image = tf.image.resize(image, [224, 224])
image = tf.cast(image, tf.float32) / 255.0
# 读取标签
label = parse_annotation(xml_path)
# 转换标签
if label == 'with_mask':
label_encoded = [1, 0] # 戴口罩
elif label == 'without_mask':
label_encoded = [0, 1] # 不戴口罩
else:
continue # 跳过不确定的样本
images.append(image)
labels.append(label_encoded)
return np.array(images), np.array(labels)
# 加载数据集
X, y = load_dataset(dataset_path)
# 划分训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建数据集
train_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
test_dataset = tf.data.Dataset.from_tensor_slices((X_test, y_test))
# 配置数据集
BATCH_SIZE = 32
train_dataset = train_dataset.shuffle(1000).batch(BATCH_SIZE)
test_dataset = test_dataset.batch(BATCH_SIZE)
# 构建模型(可以使用之前的AlexNet或更先进的模型)
model = keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(2, activation='softmax')
])
# 编译模型
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# 训练模型
history = model.fit(
train_dataset,
epochs=10,
validation_data=test_dataset
)
# 评估模型
test_loss, test_accuracy = model.evaluate(test_dataset)
print(f"Test accuracy: {test_accuracy}")
# 保存模型
model.save('mask_detection_model.h5')