写一个基于卷积神经网络实现口罩识别的程序
时间: 2023-11-27 18:02:51 浏览: 52
卷积神经网络CNN口罩识别检测(tensorflow和python)
5星 · 资源好评率100%
好的,以下是一个基于卷积神经网络实现口罩识别的程序的示例代码:
```
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# 设置训练集和验证集的文件路径
train_dir = 'path/to/training/directory'
validation_dir = 'path/to/validation/directory'
# 设置输入图像的大小和通道数
img_width, img_height = 224, 224
channels = 3
# 设置训练集和验证集的批次大小
batch_size = 32
# 构建数据生成器
train_datagen = ImageDataGenerator(rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(validation_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
# 构建卷积神经网络模型
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(img_width, img_height, channels)),
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.Conv2D(128, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# 编译模型
model.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.RMSprop(lr=1e-4),
metrics=['acc'])
# 训练模型
history = model.fit(train_generator,
steps_per_epoch=train_generator.n//batch_size,
epochs=50,
validation_data=validation_generator,
validation_steps=validation_generator.n//batch_size)
# 保存模型
model.save('mask_detection_model.h5')
```
这段代码使用了 TensorFlow 和 Keras 框架,通过构建卷积神经网络模型和数据生成器,实现了口罩识别的训练和验证,并最终保存了训练好的模型。当然,这只是一个简单的示例,实际情况下还需要根据具体的数据集进行调整和优化。
阅读全文