-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
154 lines (126 loc) · 4.37 KB
/
Copy pathmain.py
File metadata and controls
154 lines (126 loc) · 4.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
from __future__ import annotations
import argparse
from dataclasses import dataclass
import cv2
import mediapipe as mp
@dataclass(frozen=True)
class LandmarkGroup:
name: str
indices: tuple[int, ...]
color: tuple[int, int, int]
FACE_FEATURES: tuple[LandmarkGroup, ...] = (
LandmarkGroup("left_eye", (33, 133, 159, 145), (0, 255, 0)),
LandmarkGroup("right_eye", (362, 263, 386, 374), (0, 255, 0)),
LandmarkGroup("nose", (1, 4, 6, 94, 195), (255, 0, 0)),
LandmarkGroup("mouth", (61, 291, 13, 14, 78, 308), (0, 0, 255)),
LandmarkGroup("jaw", (152, 172, 136, 365, 397), (0, 255, 255)),
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Real-time face landmark detection using MediaPipe Face Mesh."
)
parser.add_argument(
"--camera-index",
type=int,
default=0,
help="Camera index to open. Default is 0.",
)
parser.add_argument(
"--max-faces",
type=int,
default=1,
help="Maximum number of faces to track at once.",
)
parser.add_argument(
"--min-detection-confidence",
type=float,
default=0.5,
help="Minimum confidence for initial face detection.",
)
parser.add_argument(
"--min-tracking-confidence",
type=float,
default=0.5,
help="Minimum confidence for face tracking.",
)
return parser.parse_args()
def to_pixel(landmark, frame_width: int, frame_height: int) -> tuple[int, int]:
return int(landmark.x * frame_width), int(landmark.y * frame_height)
def draw_feature_points(
frame,
face_landmarks,
frame_width: int,
frame_height: int,
) -> None:
for group in FACE_FEATURES:
points = []
for idx in group.indices:
landmark = face_landmarks.landmark[idx]
x, y = to_pixel(landmark, frame_width, frame_height)
points.append((x, y))
cv2.circle(frame, (x, y), 3, group.color, -1)
label_x = min(point[0] for point in points)
label_y = min(point[1] for point in points) - 10
cv2.putText(
frame,
group.name,
(label_x, max(20, label_y)),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
group.color,
1,
cv2.LINE_AA,
)
def main() -> None:
args = parse_args()
print(f"Opening camera {args.camera_index}...")
cap = cv2.VideoCapture(args.camera_index, cv2.CAP_DSHOW)
if not cap.isOpened():
# Fall back to OpenCV default backend in case DirectShow is unavailable.
cap = cv2.VideoCapture(args.camera_index)
if not cap.isOpened():
raise RuntimeError(
f"Unable to open camera {args.camera_index}. Try a different camera index."
)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cv2.namedWindow("Face Feature Points", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Face Feature Points", 960, 720)
print("Camera opened successfully. Video window should appear now.")
mp_face_mesh = mp.solutions.face_mesh
with mp_face_mesh.FaceMesh(
static_image_mode=False,
max_num_faces=args.max_faces,
refine_landmarks=True,
min_detection_confidence=args.min_detection_confidence,
min_tracking_confidence=args.min_tracking_confidence,
) as face_mesh:
while True:
ok, frame = cap.read()
if not ok:
print("Failed to read frame from camera.")
break
frame = cv2.flip(frame, 1)
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = face_mesh.process(rgb_frame)
if results.multi_face_landmarks:
for face_landmarks in results.multi_face_landmarks:
height, width = frame.shape[:2]
draw_feature_points(frame, face_landmarks, width, height)
cv2.putText(
frame,
"Press Q to quit",
(10, 30),
cv2.FONT_HERSHEY_SIMPLEX,
0.8,
(255, 255, 255),
2,
cv2.LINE_AA,
)
cv2.imshow("Face Feature Points", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()