피지컬컴퓨팅/아두이노
#인공지능 AI 활용 - 얼굴인식 트랙킹
오즈랩
2025. 5. 14. 12:34
반응형
1) 라이브러리 설치 : openCV활용 얼굴 인식
- pip install opencv-python
- pip install numpy
- pip install pyFirmata
2) 서보모터 팬틸트 활용
- 파이썬 코드
import cv2
from cvzone.FaceDetectionModule import FaceDetector
import pyfirmata
import numpy as np
import time
cap = cv2.VideoCapture(0)
ws, hs = 1280, 720
cap.set(3, ws)
cap.set(4, hs)
if not cap.isOpened():
print("Camera couldn't Access!!!")
exit()
port = "COM6"
board = pyfirmata.Arduino(port)
servo_pinX = board.get_pin('d:9:s') #pin 9 Arduino
servo_pinY = board.get_pin('d:10:s') #pin 10 Arduino
time.sleep(1) # 초기화 대기
detector = FaceDetector()
servoPos = [90, 90] # initial servo position
while True:
success, img = cap.read()
img, bboxs = detector.findFaces(img, draw=False)
if bboxs:
#get the coordinate
fx, fy = bboxs[0]["center"][0], bboxs[0]["center"][1]
pos = [fx, fy]
#convert coordinat to servo degree
servoX = np.interp(fx, [0, ws], [0, 180])
servoY = np.interp(fy, [0, hs], [0, 180])
if servoX < 0:
servoX = 0
elif servoX > 180:
servoX = 180
if servoY < 0:
servoY = 0
elif servoY > 180:
servoY = 180
servoPos[0] = servoX
servoPos[1] = servoY
print(servoPos[0], servoPos[1])
cv2.circle(img, (fx, fy), 80, (0, 0, 255), 2)
cv2.putText(img, str(pos), (fx+15, fy-15), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 0), 2 )
cv2.line(img, (0, fy), (ws, fy), (0, 0, 0), 2) # x line
cv2.line(img, (fx, hs), (fx, 0), (0, 0, 0), 2) # y line
cv2.circle(img, (fx, fy), 15, (0, 0, 255), cv2.FILLED)
cv2.putText(img, "TARGET LOCKED", (850, 50), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 3 )
else:
cv2.putText(img, "NO TARGET", (880, 50), cv2.FONT_HERSHEY_PLAIN, 3, (0, 0, 255), 3)
cv2.circle(img, (640, 360), 80, (0, 0, 255), 2)
cv2.circle(img, (640, 360), 15, (0, 0, 255), cv2.FILLED)
cv2.line(img, (0, 360), (ws, 360), (0, 0, 0), 2) # x line
cv2.line(img, (640, hs), (640, 0), (0, 0, 0), 2) # y line
cv2.putText(img, f'Servo X: {int(servoPos[0])} deg', (50, 50), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 0), 2)
cv2.putText(img, f'Servo Y: {int(servoPos[1])} deg', (50, 100), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 0), 2)
servo_pinX.write(servoPos[0])
servo_pinY.write(servoPos[1])
time.sleep(0.1)
cv2.imshow("Image", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
tombolQditekan = True
break
- 아두이노 코드
파일->예제->Firmata->StandartFirmata
반응형