import numpy as np
import cv2
import serial
port = "COM8" # Replace with the appropriate COM port name
baudrate = 9600
# Open the COM port
arduino = serial.Serial(port, baudrate=baudrate)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
capture = cv2.VideoCapture(0,cv2.CAP_DSHOW)
capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1024)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
Tim=0
xi = int(capture.get(3))
cxi = int(xi/2)
yi = int(capture.get(4))
cyi = int(yi/2)
while True:
ret, frame = capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
eyes = eye_cascade.detectMultiScale(gray, 1.3, 5)
cv2.line(frame, (cxi,0),(cxi,yi),(120,120,120),1)
cv2.line(frame, (0,cyi),(xi,cyi),(120,120,120),1)
ct = ''
current_time0 = time.time()
for (x, y, w, h) in faces:
frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 255), 2)
cx=int(x+w/2)
cy=int(y+h/2)
dx=int(90+cxi-cx)
dy=int(90+cyi-cy)
ct=str(dx)+':'+str(dy) # Send to COM port
cv2.circle(frame, (cx,cy), 5, (0, 0, 255) , -1) #-1
cv2.line(frame, (cxi,cyi), (cx,cy),(0, 0, 255), 3)
cv2.putText(frame, ct, (0, 20), cv2.FONT_HERSHEY_DUPLEX, 0.9, (0, 0, 250), 1)
# Send commands to the Arduino
#print(current_time0)
#if (time.time()-current_time0)>2.0:
# ser.write(f"{angle}n".encode())
print(ct)
command = ct
arduino.write(command.encode())
arduino.flush()
time.sleep(1.2)
#current_time0 = time.time()
cv2.imshow('From Camera', frame)
k = cv2.waitKey(30) & 0xFF
if k == 27:
if arduino.is_open:
command = '0:0'
arduino.write(command.encode())
arduino.close()
print("Serial connection closed.")
break
capture.release()
cv2.destroyAllWindows()