snipplets.dev/snipplets/code/Python/opencv/face-detect-realtime.py

35 lines
804 B
Python
Raw Normal View History

2023-09-03 12:44:02 +03:00
#!/usr/bin/env python3
import cv2
2023-09-03 13:09:03 +03:00
def face_detect(capture):
gray_image = cv2.cvtColor(capture, cv2.COLOR_BGR2GRAY)
faces = face_classifier.detectMultiScale(
gray_image, scaleFactor=1.1, minNeighbors=5, minSize=(40, 40)
)
for x, y, w, h in faces:
cv2.rectangle(capture, (x, y), (x + w, y + h), (0, 255, 0), 2)
2023-09-03 12:44:02 +03:00
2023-09-03 13:09:03 +03:00
return faces
2023-09-03 12:44:02 +03:00
2023-09-03 13:09:03 +03:00
if __name__ == '__main__':
camera = cv2.VideoCapture(2)
2023-09-03 12:44:02 +03:00
face_classifier = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)
2023-09-03 13:09:03 +03:00
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
2023-09-03 12:44:02 +03:00
2023-09-03 13:09:03 +03:00
result, image = camera.read()
2023-09-03 12:44:02 +03:00
2023-09-03 13:09:03 +03:00
faces = face_detect(image)
cv2.imshow('Face Realtime Detector', image)
2023-09-03 12:44:02 +03:00
2023-09-03 13:09:03 +03:00
camera.release()
cv2.destroyAllWindows()