Created
March 11, 2023 22:11
-
-
Save zacps/43f37a979332d9b15079f8ce0e7a4f10 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import cv2 | |
import serial | |
SERIAL_PORT = '/dev/ttyUSB0' | |
CLASSIFIER_YML = 'haarcascade_frontalface_default.xml' | |
def main(graphical=False): | |
# Load the cascade | |
face_cascade = cv2.CascadeClassifier(CLASSIFIER_YML) | |
# To capture video from webcam. | |
cap = cv2.VideoCapture(0) | |
if not graphical: | |
ser = serial.Serial(SERIAL_PORT) | |
while True: | |
try: | |
t0 = time.monotonic() | |
# Read the frame | |
_, img = cap.read() | |
height, width, _channels = img.shape | |
t1 = time.monotonic() | |
# Convert to grayscale | |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
t2 = time.monotonic() | |
# Detect the faces | |
faces = face_cascade.detectMultiScale(gray, 1.1, 5) | |
t3 = time.monotonic() | |
if len(faces) != 0: | |
biggest = max(w*h for x,y,w,h in faces) | |
# Draw the rectangle around each face | |
for i, (x, y, w, h) in enumerate(faces): | |
if graphical: | |
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) | |
center = x + w/2, y + h/2 | |
center_norm = center[0] / width, center[1] / height | |
center_255 = int(center_norm[0] * 180), int(center_norm[1] * 180) | |
if w*h == biggest: | |
print(f'{center_255[0]:03d},{center_255[1]:03d}\n') | |
if not graphical: | |
if w*h == biggest: | |
ser.write(bytes(f'{center_255[0]:03d},{center_255[1]:03d}\n', encoding="utf-8")) | |
t4 = time.monotonic() | |
# Display | |
if graphical: | |
cv2.imshow('img', img) | |
# Stop if escape key is pressed | |
k = cv2.waitKey(30) & 0xff | |
if k==27: | |
break | |
print(f"{t1-t0:.2f}, {t2-t1:.2f}, {t3-t2:.2f}, {t4-t3:.2f}") | |
except Exception as e: | |
print("Failed to determine face", e) | |
# Cleanup | |
cap.release() | |
ser.close() | |
if __name__ == "__main__": | |
main(True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment