Face Mask Detection is a popular computer vision application that identifies whether a person is wearing a mask or not. Using a pre-trained deep learning model with OpenCV, we can perform real-time detection on images and webcam feeds. This is widely used in public safety, surveillance, and healthcare monitoring.
We will use a pre-trained Deep Learning CNN model for mask detection (for example, Keras/TensorFlow model loaded with OpenCV’s DNN module).
import cv2
import tensorflow as tf
from tensorflow.keras.models import load_model
import numpy as np
# Load Haar cascade for face detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# Load pre-trained mask detection model
model = load_model("mask_detector_model.h5")
Detect faces using Haar cascades, then pass the face ROI to the mask detection model.
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
face = frame[y:y+h, x:x+w]
face_resized = cv2.resize(face, (128, 128)) / 255.0
face_input = np.expand_dims(face_resized, axis=0)
# Predict mask/no mask
prediction = model.predict(face_input)
label = "Mask" if prediction[0][0] > 0.5 else "No Mask"
color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
cv2.rectangle(frame, (x, y), (x+w, y+h), color, 2)
cv2.putText(frame, label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
cv2.imshow("Face Mask Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
✅ In this lesson, you built a Face Mask Detection system using OpenCV and a pre-trained deep learning model.
The system can classify people as “Mask” or “No Mask” in real-time.
👉 Next, we’ll move on to Quiz 5 to test your knowledge on advanced OpenCV applications.
