이제 파이썬과 아두이노 코딩을 해야한다.
처음에는 https://projecthub.arduino.cc/Little_french_kev/face-tracking-camera-f391e1 여기 있는 코드를 사용했었으나 쓰다보니 아두이노-PC간 통신 문제가 발생하였는데 해결하지 못하여 다른 사람의 코드를 가져다가 쓰기로했다.
https://www.hackster.io/shubhamsantosh99/face-tracker-using-opencv-and-arduino-55412e
Face Tracker Using OpenCV and Arduino
Track your face using OpenCV's facial recognition. By Shubham Santosh.
www.hackster.io
결국 이 분의 코드를 사용
아두이노의 경우 maximum 각도 제한이 필요하여 약간의 변경을 거쳤다.
#include<Servo.h>
Servo x, y;
int width = 640, height = 480; // total resolution of the video
int xpos = 90, ypos = 90; // initial positions of both Servos
int min_angle = 30, max_angle = 150; // 제한된 각도 범위
const int angle = 2; // degree of increment or decrement
void setup() {
Serial.begin(9600);
x.attach(9);
y.attach(10);
x.write(xpos);
y.write(ypos);
}
void loop() {
if (Serial.available() > 0) {
int x_mid, y_mid;
if (Serial.read() == 'X') {
x_mid = Serial.parseInt(); // read center x-coordinate
if (Serial.read() == 'Y')
y_mid = Serial.parseInt(); // read center y-coordinate
}
// adjust the servo within the squared region if the coordinates are outside it
if (x_mid > width / 2 + 30)
xpos += angle;
if (x_mid < width / 2 - 30)
xpos -= angle;
if (y_mid < height / 2 + 30)
ypos -= angle;
if (y_mid > height / 2 - 30)
ypos += angle;
// Apply the angle limits to the servo positions (30° ~ 150°)
if (xpos > max_angle) xpos = max_angle;
if (xpos < min_angle) xpos = min_angle;
if (ypos > max_angle) ypos = max_angle;
if (ypos < min_angle) ypos = min_angle;
// Move the servos
x.write(xpos);
y.write(ypos);
// used for testing
//Serial.print("\t");
//Serial.print(x_mid);
//Serial.print("\t");
//Serial.println(y_mid);
}
}
중요한 부분은 python 코드에서 사전학습된 얼굴 탐지 모델을 사용하는 것이다. haarcascade xml 파일을 사용하는데, 이미 고양이 얼굴 등 다양한 모델들이 있어서 필요에 따라서 구해다가 쓰면 된다.
코드는 간단하긴하지만 몇가지 개선의 여지가 보여서 차후 시도해볼 계획.
잘 작동하는 것으로 보인다. 웹캠이 약간 아래를 향하고 있다보니 이 부분은 뼈대를 잡을 때 손봐야할 듯 하다.
'Project Log > [Toy Project]Tiger-Bot' 카테고리의 다른 글
[Toy Project]Tiger-Bot 만들기 - Face Recognition (0) | 2025.03.22 |
---|---|
[Toy Project]Tiger-Bot 만들기 - Talking [1] (0) | 2025.02.25 |
[Toy Project]Tiger-Bot 만들기 - 몸체 (0) | 2025.02.24 |
[Toy Project]Tiger-Bot 만들기 - 케이블링 (0) | 2025.02.24 |
[Toy Project] Tiger-Bot 만들기 - 구상 (0) | 2025.02.24 |