-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfaces.py
More file actions
54 lines (50 loc) · 2.23 KB
/
faces.py
File metadata and controls
54 lines (50 loc) · 2.23 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
# Face Detection
import cv2
import mediapipe as mp
class InlineFaceDetector:
def __init__(self, min_detection_confidence=0.5, bounding_box_color=(0, 255, 0), max_faces=None):
self.detector = mp.solutions.face_detection.FaceDetection(min_detection_confidence=min_detection_confidence)
self.color = bounding_box_color
self.max_faces = max_faces
self._results = None
self._boxes = []
def find_faces(self, img_bgr):
# Convert BGR -> RGB
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
self._results = self.detector.process(img_rgb)
boxes = []
if self._results and self._results.detections:
detections = self._results.detections
if self.max_faces is not None:
detections = detections[: self.max_faces]
ih, iw = img_bgr.shape[0], img_bgr.shape[1]
for det in detections:
box = det.location_data.relative_bounding_box
bw = int(box.width * iw)
bh = int(box.height * ih)
x1 = int(box.xmin * iw)
y1 = int(box.ymin * ih)
x2 = x1 + bw
y2 = y1 + bh
cx = (x1 + x2) // 2
cy = (y1 + y2) // 2
boxes.append((x1, y1, x2, y2, bw, bh, cx, cy))
self._boxes = boxes
def draw_detection(self, img_bgr, draw_text=True):
# Overlay rectangles (and % score) onto the given BGR frame
if not self._results or not self._results.detections:
return img_bgr
detections = self._results.detections
if self.max_faces is not None:
detections = detections[: self.max_faces]
for i, det in enumerate(detections):
if i >= len(self._boxes):
break
x1, y1, x2, y2, _, _, _, _ = self._boxes[i]
cv2.rectangle(img_bgr, (x1, y1), (x2, y2), self.color, 2)
if draw_text and det.score:
pct = int(det.score[0] * 100)
cv2.putText(img_bgr, f"{pct}%", (x1, y1 - 10), cv2.FONT_HERSHEY_PLAIN, 1.5, self.color, 2)
return img_bgr
def get_boxes(self): # Return last parsed face boxes (x1, y1, x2, y2, w, h, cx, cy)
return self._boxes