|
| 1 | +import cv2 |
| 2 | + |
| 3 | +# pre-trained Haar cascade for face detection |
| 4 | +face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') |
| 5 | + |
| 6 | +cap = cv2.VideoCapture(0) |
| 7 | + |
| 8 | +prev_frame = None |
| 9 | + |
| 10 | +while True: |
| 11 | + #frame-by-frame capturing |
| 12 | + ret, frame = cap.read() |
| 13 | + |
| 14 | + |
| 15 | + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) |
| 16 | + |
| 17 | + # face detection |
| 18 | + faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) |
| 19 | + |
| 20 | + # draw rectangles around the faces |
| 21 | + for (x, y, w, h) in faces: |
| 22 | + cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) |
| 23 | + |
| 24 | + |
| 25 | + if prev_frame is not None: |
| 26 | + |
| 27 | + frame_diff = cv2.absdiff(prev_frame, gray) |
| 28 | + |
| 29 | + |
| 30 | + _, frame_diff_thresh = cv2.threshold(frame_diff, 30, 255, cv2.THRESH_BINARY) |
| 31 | + |
| 32 | + |
| 33 | + contours, _ = cv2.findContours(frame_diff_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
| 34 | + |
| 35 | + |
| 36 | + for contour in contours: |
| 37 | + if cv2.contourArea(contour) > 50: |
| 38 | + x, y, w, h = cv2.boundingRect(contour) |
| 39 | + cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) |
| 40 | + |
| 41 | + cv2.imshow('Video', frame) |
| 42 | + |
| 43 | + # frame store for next iteration |
| 44 | + prev_frame = gray |
| 45 | + |
| 46 | + # exit with 'q' |
| 47 | + if cv2.waitKey(1) & 0xFF == ord('q'): |
| 48 | + break |
| 49 | + |
| 50 | +#release |
| 51 | +cap.release() |
| 52 | +cv2.destroyAllWindows() |
0 commit comments