andro-flock commited on
Commit
0d66750
·
verified ·
1 Parent(s): 05d7a3f

Upload folder using huggingface_hub

Browse files
app.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from face_detection import detect_faces
3
+ from heatmap import get_heatmap
4
+ from pose import detect_pose, draw_pose
5
+
6
+ def prepare_image(img_path):
7
+ # detect face
8
+ annotated_image, face_bboxes = detect_faces(img_path)
9
+ # detect pose + bounding_box
10
+ pose_results = detect_pose(img_path)
11
+ pose_result = pose_results[0]
12
+ body_bboxes, body_keypoints = pose_result.boxes, pose_result.keypoints
13
+ # generate heatmap
14
+ heatmap = get_heatmap(img_path)
15
+ heatmap_pil = Image.fromarray(heatmap)
16
+ # pose on heatmap
17
+ heatmap_n_pose = draw_pose(heatmap_pil,body_keypoints) #PIL.Image
18
+
19
+ # area in bounding_box below head (rectangular)
20
+ face_y1, face_w = face_bboxes[0][1] #xywh
21
+ face_center_y = (face_w - face_y1) // 2
22
+ body_box = body_bboxes.numpy().xywh[0]
23
+ body_box[1] = face_center_y
24
+
25
+ # Calculate the coordinates for cropping
26
+ x, y, w, h = map(int, body_box)
27
+ cropped_region = heatmap_n_pose.crop((x, y, x + w, y + h))
28
+ original_image = Image.open(img_path)
29
+ original_image.paste(cropped_region, (x, y))
30
+
31
+ # Return the modified image
32
+ return original_image
face_detection.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YuNet-face-detection
2
+ import cv2
3
+ from yunet2 import YuNet2
4
+
5
+ MODEL_PATH = "./yunet-ckpts/yunet_2023mar.onnx"
6
+ yunet_model = YuNet2(modelPath=MODEL_PATH)
7
+
8
+ def detect_faces(src_img):
9
+ cv2_img = cv2.imread(src_img)
10
+ annotated_image, bboxes = yunet_model.detect(cv2_img)
11
+ return annotated_image, bboxes
heatmap.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # intel-isl/MiDaS
2
+ import cv2
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ model_type = "DPT_Large" # MiDaS v3 - Large (highest accuracy, slowest inference speed)
7
+ # model_type = "DPT_Hybrid" # MiDaS v3 - Hybrid (medium accuracy, medium inference speed)
8
+ # model_type = "MiDaS_small" # MiDaS v2.1 - Small (lowest accuracy, highest inference speed)
9
+
10
+ midas = torch.hub.load("intel-isl/MiDaS", model_type)
11
+ midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
12
+
13
+ if model_type == "DPT_Large" or model_type == "DPT_Hybrid":
14
+ transform = midas_transforms.dpt_transform
15
+ else:
16
+ transform = midas_transforms.small_transform
17
+
18
+ def get_heatmap(src_img):
19
+ cv2image = cv2.imread(src_img)
20
+ img = cv2.cvtColor(cv2image, cv2.COLOR_BGR2RGB)
21
+ input_batch = transform(img)
22
+ with torch.inference_mode():
23
+ prediction = midas(input_batch)
24
+
25
+ prediction = F.interpolate(
26
+ prediction.unsqueeze(1),
27
+ size=img.shape[:2],
28
+ mode="bicubic",
29
+ align_corners=False,
30
+ ).squeeze()
31
+ output = prediction.cpu().numpy()
32
+ return output
pose.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLO
2
+ import cv2
3
+ import torch
4
+ import numpy as np
5
+ from ultralytics import YOLO
6
+ from PIL import Image, ImageDraw
7
+
8
+ model_name = 'yolo11s-pose.pt'
9
+ model = YOLO(model_name)
10
+
11
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
12
+ half = device=='cuda'
13
+
14
+ connection_color_map = {
15
+ (0, 1): 'lightgreen', # Nose to Left Eye
16
+ (0, 2): 'lightgreen', # Nose to Right Eye
17
+ (1, 3): 'lightgreen', # Left Eye to Left Ear
18
+ (2, 4): 'lightgreen', # Right Eye to Right Ear
19
+ (0, 5): 'lightblue', # Nose to Left Shoulder
20
+ (0, 6): 'lightblue', # Nose to Right Shoulder
21
+ (5, 7): 'blue', # Left Shoulder to Left Elbow
22
+ (7, 9): 'blue', # Left Elbow to Left Wrist
23
+ (6, 8): 'red', # Right Shoulder to Right Elbow
24
+ (8, 10): 'red', # Right Elbow to Right Wrist
25
+ (5, 11): 'purple', # Left Shoulder to Left Hip
26
+ (6, 12): 'purple', # Right Shoulder to Right Hip
27
+ (11, 13): 'purple', # Left Hip to Left Knee
28
+ (13, 15): 'purple', # Left Knee to Left Ankle
29
+ (12, 14): 'purple', # Right Hip to Right Knee
30
+ (14, 16): 'purple', # Right Knee to Right Ankle
31
+ (11, 12): 'orange' # Left Hip to Right Hip
32
+ }
33
+
34
+
35
+ def detect_pose(src_img):
36
+ results = model.predict(
37
+ source=src_img,
38
+ # conf=conf_threshold,
39
+ # iou=iou_threshold,
40
+ max_det=1,
41
+ show_labels=True,
42
+ show_conf=True,
43
+ imgsz=32*5,
44
+ classes=[0],
45
+ # line_width=3,
46
+ half=half,
47
+ device=device,
48
+ )
49
+ return results
50
+
51
+ def draw_pose(skeleton_image:Image.Image, keypoints, threshold=0.7, line_width = 3,circle_radius = 6):
52
+ coords = keypoints.numpy().xy[0]
53
+ scores = keypoints.data.squeeze()[:,2].numpy()
54
+ # Create a blank image with the same size as the input image
55
+ # skeleton_image = Image.new("RGB", im.size, "black") # White background
56
+ draw = ImageDraw.Draw(skeleton_image)
57
+
58
+ # Draw lines connecting the keypoints
59
+ for connection, color in connection_color_map.items():
60
+ try:
61
+ start_point = coords[connection[0]]
62
+ end_point = coords[connection[1]]
63
+ if scores[connection[0]] > threshold and scores[connection[1]] > threshold:
64
+ draw.line([tuple(start_point), tuple(end_point)], fill=color, width=line_width)
65
+ draw.ellipse(
66
+ (start_point[0] - circle_radius, start_point[1] - circle_radius,
67
+ start_point[0] + circle_radius, start_point[1] + circle_radius),
68
+ fill=color
69
+ )
70
+ draw.ellipse(
71
+ (end_point[0] - circle_radius, end_point[1] - circle_radius,
72
+ end_point[0] + circle_radius, end_point[1] + circle_radius),
73
+ fill=color
74
+ )
75
+
76
+ except IndexError:
77
+ pass # Handle cases where keypoints might be missing
78
+
79
+ # Save the skeleton image
80
+ return skeleton_image
yunet-ckpts/yunet_2023mar.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4
3
+ size 232589
yunet-ckpts/yunet_2023mar_int8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:321aa5a6afabf7ecc46a3d06bfab2b579dc96eb5c3be7edd365fa04502ad9294
3
+ size 100416
yunet.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of OpenCV Zoo project.
2
+ # It is subject to the license terms in the LICENSE file found in the same directory.
3
+ #
4
+ # Copyright (C) 2021, Shenzhen Institute of Artificial Intelligence and Robotics for Society, all rights reserved.
5
+ # Third party copyrights are property of their respective owners.
6
+
7
+ from itertools import product
8
+
9
+ import numpy as np
10
+ import cv2 as cv
11
+
12
+ class YuNet:
13
+ def __init__(self, modelPath, inputSize=[320, 320], confThreshold=0.6, nmsThreshold=0.3, topK=5000, backendId=0, targetId=0):
14
+ self._modelPath = modelPath
15
+ self._inputSize = tuple(inputSize) # [w, h]
16
+ self._confThreshold = confThreshold
17
+ self._nmsThreshold = nmsThreshold
18
+ self._topK = topK
19
+ self._backendId = backendId
20
+ self._targetId = targetId
21
+
22
+ self._model = cv.FaceDetectorYN.create(
23
+ model=self._modelPath,
24
+ config="",
25
+ input_size=self._inputSize,
26
+ score_threshold=self._confThreshold,
27
+ nms_threshold=self._nmsThreshold,
28
+ top_k=self._topK,
29
+ backend_id=self._backendId,
30
+ target_id=self._targetId)
31
+
32
+ @property
33
+ def name(self):
34
+ return self.__class__.__name__
35
+
36
+ def setBackendAndTarget(self, backendId, targetId):
37
+ self._backendId = backendId
38
+ self._targetId = targetId
39
+ self._model = cv.FaceDetectorYN.create(
40
+ model=self._modelPath,
41
+ config="",
42
+ input_size=self._inputSize,
43
+ score_threshold=self._confThreshold,
44
+ nms_threshold=self._nmsThreshold,
45
+ top_k=self._topK,
46
+ backend_id=self._backendId,
47
+ target_id=self._targetId)
48
+
49
+ def setInputSize(self, input_size):
50
+ self._model.setInputSize(tuple(input_size))
51
+
52
+ def infer(self, image):
53
+ # Forward
54
+ faces = self._model.detect(image)
55
+ return np.array([]) if faces[1] is None else faces[1]
yunet2.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import cv2 as cv
3
+ import numpy as np
4
+ from yunet import YuNet
5
+
6
+
7
+ # Valid combinations of backends and targets
8
+ backend_target_pairs = [
9
+ [cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_TARGET_CPU],
10
+ [cv.dnn.DNN_BACKEND_CUDA, cv.dnn.DNN_TARGET_CUDA],
11
+ [cv.dnn.DNN_BACKEND_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16],
12
+ [cv.dnn.DNN_BACKEND_TIMVX, cv.dnn.DNN_TARGET_NPU],
13
+ [cv.dnn.DNN_BACKEND_CANN, cv.dnn.DNN_TARGET_NPU],
14
+ ]
15
+
16
+
17
+ class YuNet2:
18
+ def __init__(
19
+ self,
20
+ modelPath,
21
+ input_size=(320, 320),
22
+ conf_threshold=0.6,
23
+ nms_threshold=0.3,
24
+ top_k=5000,
25
+ backend_id=0,
26
+ target_id=0,
27
+ ):
28
+ self.model = YuNet(
29
+ modelPath=modelPath,
30
+ inputSize=input_size,
31
+ confThreshold=conf_threshold,
32
+ nmsThreshold=nms_threshold,
33
+ topK=top_k,
34
+ backendId=backend_id,
35
+ targetId=target_id,
36
+ )
37
+
38
+ def detect(self, image, num_faces=None):
39
+ # If input is an image
40
+ if image is not None:
41
+ h, w, _ = image.shape
42
+
43
+ # Inference
44
+ self.model.setInputSize([w, h])
45
+ results = self.model.infer(image)
46
+
47
+ faces = results[:num_faces] if num_faces else results
48
+
49
+ bboxes = []
50
+
51
+ for face in faces:
52
+ bbox = face[0:4].astype(np.int32) # x,y,w,h
53
+ bboxes.append(bbox)
54
+ x, y, w, h = bbox
55
+ # draw
56
+ cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
57
+
58
+ return image, bboxes
59
+
60
+ def resize(self, image, target_size=512, above_head_ratio=0.5):
61
+ height, width, _c = image.shape
62
+ ar = width / height
63
+ # downscale the image
64
+ if not target_size:
65
+ target_size = 512
66
+ if ar > 1:
67
+ # Landscape
68
+ new_height = target_size
69
+ new_width = int(target_size * ar)
70
+ elif ar < 1:
71
+ # Portrait
72
+ new_width = target_size
73
+ new_height = int(target_size / ar)
74
+ else:
75
+ # Square
76
+ new_width = target_size
77
+ new_height = target_size
78
+
79
+ resized = cv2.resize(
80
+ image, (new_width, new_height), interpolation=cv2.INTER_AREA
81
+ )
82
+
83
+ # Perform object detection on the resized image
84
+ dt_image, bboxes = self.detect(resized.copy())
85
+
86
+ # crop around face
87
+ if len(bboxes) >= 1:
88
+ x, y, w, h = bboxes[0]
89
+ else:
90
+ x, y, w, h = 0, 0, target_size, target_size
91
+ # 20% of image height
92
+ above_head_max = int(target_size * above_head_ratio)
93
+ x_center = int((x + (x + w)) / 2)
94
+ y_center = int((y + (y + h)) / 2)
95
+ # Calculate cropping box
96
+ top = int(max(0, y_center - above_head_max))
97
+ bottom = int(min(top + target_size, resized.shape[0]))
98
+
99
+ left = int(max(0, x_center - target_size // 2))
100
+ right = int(min(x_center + target_size // 2, resized.shape[1]))
101
+
102
+ # adjust width if necessory
103
+ _w = right - left
104
+ if _w != target_size:
105
+ dx = (
106
+ target_size - _w
107
+ ) # difference between the target size and the current width
108
+ nl = max(0, left - dx)
109
+ dr = dx - nl # remaining adjustment needed for the right coordinate
110
+ left = nl
111
+ right += dr
112
+
113
+ cropped_image = resized[top:bottom, left:right]
114
+ return dt_image, cropped_image