Haar cascade is an algorithm that can detect objects in images, irrespective of their scale in image and location.
This algorithm is not so complex and can run in real-time. We can train a haar-cascade detector to detect various objects like cars, bikes, buildings, fruits, etc.
Haar cascade uses the cascading window, and it tries to compute features in every window and classify whether it could be an object. Sample haar features traverse in window-sized across the picture to compute and match features.
it works as a classifier. It classifies positive data points → that are part of our detected object and negative data points → that don’t contain our object.
- Human face detection
- Eye detection
- Nose / Mouth detection
- Vehicle detection
Haar cascades are XML files that can be used in OpenCV to detect specified objects.
If you find your target object haar-cascade available in the pre-trained repository provided by OpenCV, you need to download the pre-trained XML file.
!pip install opencv-python
#---OR ---
!pip install opencv-contrib-python
face_detector=cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
eye_dectector = cv2.CascadeClassifier(‘haarcascade_eye.xml’)
results = face_detector.detectMultiScale(gray_img, scaleFactor=1.05,minNeighbors=5,minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
We will be using OpenCV video cam feed input to take images in real-time (video)
import cv2
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_dectector = cv2.CascadeClassifier('haarcascade_eye.xml')
# reading the input image now
cap = cv2.VideoCapture(0)
while cap.isOpened():
_, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray,1.1, 4 )
for (x,y, w, h) in faces:
cv2.rectangle(frame, pt1 = (x,y),pt2 = (x+w, y+h), color = (255,0,0),thickness = 3)
roi_gray = gray[y:y+h,x:x+w]
roi_color = frame[y:y+h, x:x+w]
eyes = eye_dectector.detectMultiScale(roi_gray)
for (ex,ey, ew, eh) in eyes:
cv2.rectangle(roi_color, (ex,ey), (ex+ew, ey+eh), (0,255,0), 5)
cv2.imshow("window", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
frame.release()