Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,174 +1,181 @@
|
|
1 |
-
import os
|
2 |
-
import sys
|
3 |
-
import traceback
|
4 |
-
import gradio as gr
|
5 |
-
import cv2 as cv
|
6 |
-
import numpy as np
|
7 |
-
import mediapipe as mp
|
8 |
-
from utils import blinkRatio
|
9 |
-
|
10 |
-
def custom_excepthook(type, value, tb):
|
11 |
-
traceback.print_exception(type, value, tb)
|
12 |
-
sys.__excepthook__(type, value, tb)
|
13 |
-
|
14 |
-
sys.excepthook = custom_excepthook
|
15 |
-
|
16 |
-
def list_overlay_images(directory):
|
17 |
-
return [f for f in os.listdir(directory) if f.endswith('.png')]
|
18 |
-
|
19 |
-
def process_frame(frame, overlay, LEFT_EYE, RIGHT_EYE, LEFT_IRIS, RIGHT_IRIS,
|
20 |
-
min_detection_confidence, min_tracking_confidence, alpha):
|
21 |
-
try:
|
22 |
-
mp_face_mesh = mp.solutions.face_mesh
|
23 |
-
with mp_face_mesh.FaceMesh(
|
24 |
-
max_num_faces=1,
|
25 |
-
refine_landmarks=True,
|
26 |
-
min_detection_confidence=min_detection_confidence,
|
27 |
-
min_tracking_confidence=min_tracking_confidence
|
28 |
-
) as face_mesh:
|
29 |
-
rgb_frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
|
30 |
-
rgba_frame = cv.cvtColor(frame, cv.COLOR_BGR2RGBA)
|
31 |
-
height, width = rgba_frame.shape[:2]
|
32 |
-
results = face_mesh.process(rgb_frame)
|
33 |
-
if results.multi_face_landmarks:
|
34 |
-
zero_overlay = np.zeros_like(rgba_frame)
|
35 |
-
mesh_points = np.array([np.multiply([p.x, p.y],
|
36 |
-
[width, height]).astype(int) for p in results.multi_face_landmarks[0].landmark])
|
37 |
-
iris_mask_left = np.zeros(rgba_frame.shape, dtype=np.uint8)
|
38 |
-
iris_mask_right = np.zeros(rgba_frame.shape, dtype=np.uint8)
|
39 |
-
_, re_ratio, le_ratio = blinkRatio(rgb_frame, mesh_points, RIGHT_EYE, LEFT_EYE)
|
40 |
-
(l_cx, l_cy), l_radius = cv.minEnclosingCircle(mesh_points[LEFT_IRIS])
|
41 |
-
(r_cx, r_cy), r_radius = cv.minEnclosingCircle(mesh_points[RIGHT_IRIS])
|
42 |
-
center_left = (int(l_cx), int(l_cy))
|
43 |
-
center_right = (int(r_cx), int(r_cy))
|
44 |
-
cv.circle(iris_mask_left, center_left, int(l_radius), (255, 0, 0, 255), -1, cv.LINE_AA)
|
45 |
-
cv.circle(iris_mask_right, center_right, int(r_radius), (255, 0, 0, 255), -1, cv.LINE_AA)
|
46 |
-
bbx_size_l = int((l_radius * 2) / 2)
|
47 |
-
bbx_size_r = int((r_radius * 2) / 2)
|
48 |
-
resized_overlay_l = cv.resize(overlay, (bbx_size_l * 2, bbx_size_l * 2), interpolation=cv.INTER_CUBIC)
|
49 |
-
resized_overlay_r = cv.resize(overlay, (bbx_size_r * 2, bbx_size_r * 2), interpolation=cv.INTER_CUBIC)
|
50 |
-
y1_r = center_right[1] - bbx_size_r
|
51 |
-
y2_r = center_right[1] + bbx_size_r
|
52 |
-
x1_r = center_right[0] - bbx_size_r
|
53 |
-
x2_r = center_right[0] + bbx_size_r
|
54 |
-
y1_l = center_left[1] - bbx_size_l
|
55 |
-
y2_l = center_left[1] + bbx_size_l
|
56 |
-
x1_l = center_left[0] - bbx_size_l
|
57 |
-
x2_l = center_left[0] + bbx_size_l
|
58 |
-
if (resized_overlay_l.shape == zero_overlay[y1_l:y2_l, x1_l:x2_l].shape) & (le_ratio < 5.0) & (le_ratio > 2.0):
|
59 |
-
zero_overlay[y1_l:y2_l, x1_l:x2_l] = resized_overlay_l
|
60 |
-
if (resized_overlay_r.shape == zero_overlay[y1_r:y2_r, x1_r:x2_r].shape) & (re_ratio < 5.0) & (re_ratio > 2.0):
|
61 |
-
zero_overlay[y1_r:y2_r, x1_r:x2_r] = resized_overlay_r
|
62 |
-
eye_mask_left = np.zeros(rgba_frame.shape, dtype=np.uint8)
|
63 |
-
eye_mask_right = np.zeros(rgba_frame.shape, dtype=np.uint8)
|
64 |
-
cv.fillPoly(eye_mask_left, [mesh_points[LEFT_EYE]], (255, 0, 0, 255))
|
65 |
-
cv.fillPoly(eye_mask_right, [mesh_points[RIGHT_EYE]], (255, 0, 0, 255))
|
66 |
-
zero_overlay[np.where((iris_mask_left[:, :, 3] > 0) & (eye_mask_left[:, :, 3] == 0))] = 0
|
67 |
-
zero_overlay[np.where((iris_mask_right[:, :, 3] > 0) & (eye_mask_right[:, :, 3] == 0))] = 0
|
68 |
-
rgba_frame = cv.addWeighted(rgba_frame, 1, zero_overlay, alpha, 0)
|
69 |
-
return rgba_frame
|
70 |
-
except Exception as e:
|
71 |
-
print(f"Error in process_frame: {e}")
|
72 |
-
traceback.print_exc()
|
73 |
-
|
74 |
-
def process_image(input_image, overlay_file, alpha=0.3, min_detection_confidence=0.5, min_tracking_confidence=0.5):
|
75 |
-
overlay_file = overlay_file + '.png'
|
76 |
-
overlay_path = os.path.join(os.getcwd(),'overlays', overlay_file)
|
77 |
-
overlay = cv.imread(overlay_path, cv.IMREAD_UNCHANGED)
|
78 |
-
frame = np.array(input_image)
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
min_detection_confidence
|
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 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import traceback
|
4 |
+
import gradio as gr
|
5 |
+
import cv2 as cv
|
6 |
+
import numpy as np
|
7 |
+
import mediapipe as mp
|
8 |
+
from utils import blinkRatio
|
9 |
+
|
10 |
+
def custom_excepthook(type, value, tb):
|
11 |
+
traceback.print_exception(type, value, tb)
|
12 |
+
sys.__excepthook__(type, value, tb)
|
13 |
+
|
14 |
+
sys.excepthook = custom_excepthook
|
15 |
+
|
16 |
+
def list_overlay_images(directory):
|
17 |
+
return [f for f in os.listdir(directory) if f.endswith('.png')]
|
18 |
+
|
19 |
+
def process_frame(frame, overlay, LEFT_EYE, RIGHT_EYE, LEFT_IRIS, RIGHT_IRIS,
|
20 |
+
min_detection_confidence, min_tracking_confidence, alpha):
|
21 |
+
try:
|
22 |
+
mp_face_mesh = mp.solutions.face_mesh
|
23 |
+
with mp_face_mesh.FaceMesh(
|
24 |
+
max_num_faces=1,
|
25 |
+
refine_landmarks=True,
|
26 |
+
min_detection_confidence=min_detection_confidence,
|
27 |
+
min_tracking_confidence=min_tracking_confidence
|
28 |
+
) as face_mesh:
|
29 |
+
rgb_frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
|
30 |
+
rgba_frame = cv.cvtColor(frame, cv.COLOR_BGR2RGBA)
|
31 |
+
height, width = rgba_frame.shape[:2]
|
32 |
+
results = face_mesh.process(rgb_frame)
|
33 |
+
if results.multi_face_landmarks:
|
34 |
+
zero_overlay = np.zeros_like(rgba_frame)
|
35 |
+
mesh_points = np.array([np.multiply([p.x, p.y],
|
36 |
+
[width, height]).astype(int) for p in results.multi_face_landmarks[0].landmark])
|
37 |
+
iris_mask_left = np.zeros(rgba_frame.shape, dtype=np.uint8)
|
38 |
+
iris_mask_right = np.zeros(rgba_frame.shape, dtype=np.uint8)
|
39 |
+
_, re_ratio, le_ratio = blinkRatio(rgb_frame, mesh_points, RIGHT_EYE, LEFT_EYE)
|
40 |
+
(l_cx, l_cy), l_radius = cv.minEnclosingCircle(mesh_points[LEFT_IRIS])
|
41 |
+
(r_cx, r_cy), r_radius = cv.minEnclosingCircle(mesh_points[RIGHT_IRIS])
|
42 |
+
center_left = (int(l_cx), int(l_cy))
|
43 |
+
center_right = (int(r_cx), int(r_cy))
|
44 |
+
cv.circle(iris_mask_left, center_left, int(l_radius), (255, 0, 0, 255), -1, cv.LINE_AA)
|
45 |
+
cv.circle(iris_mask_right, center_right, int(r_radius), (255, 0, 0, 255), -1, cv.LINE_AA)
|
46 |
+
bbx_size_l = int((l_radius * 2) / 2)
|
47 |
+
bbx_size_r = int((r_radius * 2) / 2)
|
48 |
+
resized_overlay_l = cv.resize(overlay, (bbx_size_l * 2, bbx_size_l * 2), interpolation=cv.INTER_CUBIC)
|
49 |
+
resized_overlay_r = cv.resize(overlay, (bbx_size_r * 2, bbx_size_r * 2), interpolation=cv.INTER_CUBIC)
|
50 |
+
y1_r = center_right[1] - bbx_size_r
|
51 |
+
y2_r = center_right[1] + bbx_size_r
|
52 |
+
x1_r = center_right[0] - bbx_size_r
|
53 |
+
x2_r = center_right[0] + bbx_size_r
|
54 |
+
y1_l = center_left[1] - bbx_size_l
|
55 |
+
y2_l = center_left[1] + bbx_size_l
|
56 |
+
x1_l = center_left[0] - bbx_size_l
|
57 |
+
x2_l = center_left[0] + bbx_size_l
|
58 |
+
if (resized_overlay_l.shape == zero_overlay[y1_l:y2_l, x1_l:x2_l].shape) & (le_ratio < 5.0) & (le_ratio > 2.0):
|
59 |
+
zero_overlay[y1_l:y2_l, x1_l:x2_l] = resized_overlay_l
|
60 |
+
if (resized_overlay_r.shape == zero_overlay[y1_r:y2_r, x1_r:x2_r].shape) & (re_ratio < 5.0) & (re_ratio > 2.0):
|
61 |
+
zero_overlay[y1_r:y2_r, x1_r:x2_r] = resized_overlay_r
|
62 |
+
eye_mask_left = np.zeros(rgba_frame.shape, dtype=np.uint8)
|
63 |
+
eye_mask_right = np.zeros(rgba_frame.shape, dtype=np.uint8)
|
64 |
+
cv.fillPoly(eye_mask_left, [mesh_points[LEFT_EYE]], (255, 0, 0, 255))
|
65 |
+
cv.fillPoly(eye_mask_right, [mesh_points[RIGHT_EYE]], (255, 0, 0, 255))
|
66 |
+
zero_overlay[np.where((iris_mask_left[:, :, 3] > 0) & (eye_mask_left[:, :, 3] == 0))] = 0
|
67 |
+
zero_overlay[np.where((iris_mask_right[:, :, 3] > 0) & (eye_mask_right[:, :, 3] == 0))] = 0
|
68 |
+
rgba_frame = cv.addWeighted(rgba_frame, 1, zero_overlay, alpha, 0)
|
69 |
+
return rgba_frame
|
70 |
+
except Exception as e:
|
71 |
+
print(f"Error in process_frame: {e}")
|
72 |
+
traceback.print_exc()
|
73 |
+
|
74 |
+
def process_image(input_image, overlay_file, alpha=0.3, min_detection_confidence=0.5, min_tracking_confidence=0.5):
|
75 |
+
overlay_file = overlay_file + '.png'
|
76 |
+
overlay_path = os.path.join(os.getcwd(),'overlays', overlay_file)
|
77 |
+
overlay = cv.imread(overlay_path, cv.IMREAD_UNCHANGED)
|
78 |
+
frame = np.array(input_image)
|
79 |
+
w,h,_ = frame.shape
|
80 |
+
new_h = 500
|
81 |
+
new_w = int((w/h)*new_h)
|
82 |
+
frame = cv.resize(frame, (new_h,new_w), interpolation=cv.INTER_CUBIC)
|
83 |
+
processed_frame = process_frame(frame, overlay, LEFT_EYE, RIGHT_EYE, LEFT_IRIS, RIGHT_IRIS,
|
84 |
+
min_detection_confidence, min_tracking_confidence, alpha)
|
85 |
+
return cv.cvtColor(processed_frame, cv.COLOR_BGR2RGB)
|
86 |
+
|
87 |
+
def process_video(input_video, overlay_file, alpha=0.3, output_format='mp4', output_frame_rate=30,
|
88 |
+
min_detection_confidence=0.5, min_tracking_confidence=0.5):
|
89 |
+
overlay_file = overlay_file + '.png'
|
90 |
+
overlay_path = os.path.join(os.getcwd(),'overlays', overlay_file)
|
91 |
+
overlay = cv.imread(overlay_path, cv.IMREAD_UNCHANGED)
|
92 |
+
cap = cv.VideoCapture(input_video)
|
93 |
+
output_path = os.path.join(os.getcwd(),f'video_processed.{output_format}')
|
94 |
+
# Define the codec and create a VideoWriter object to save the processed video
|
95 |
+
if (not isinstance(overlay,type(None))) & (not isinstance(cap,type(None))):
|
96 |
+
# Get the dimensions of the frame, fps
|
97 |
+
fps=int(output_frame_rate)
|
98 |
+
if fps==0:
|
99 |
+
fps = cap.get(5)
|
100 |
+
ret, frame = cap.read()
|
101 |
+
h,w,_ = frame.shape
|
102 |
+
new_h = 500
|
103 |
+
new_w = int((w/h)*new_h)
|
104 |
+
fourcc = cv.VideoWriter_fourcc(*'mp4v' if output_format == 'mp4' else 'MJPG')
|
105 |
+
out = cv.VideoWriter(output_path, fourcc, fps, (new_w,new_h))
|
106 |
+
while(cap.isOpened()):
|
107 |
+
ret, frame = cap.read()
|
108 |
+
if ret == True:
|
109 |
+
frame = cv.resize(frame, (new_w,new_h), interpolation=cv.INTER_NEAREST)
|
110 |
+
processed_frame = process_frame(frame,overlay,LEFT_EYE, RIGHT_EYE, LEFT_IRIS, RIGHT_IRIS,
|
111 |
+
float(min_detection_confidence),
|
112 |
+
float(min_tracking_confidence), float(alpha)) # Assuming process_frame is a function that processes a single frame
|
113 |
+
processed_frame = cv.cvtColor(processed_frame, cv.COLOR_RGBA2BGR)
|
114 |
+
out.write(processed_frame)
|
115 |
+
else:
|
116 |
+
break
|
117 |
+
cap.release()
|
118 |
+
out.release()
|
119 |
+
return output_path
|
120 |
+
|
121 |
+
|
122 |
+
def process_webcam(frame, overlay_file, alpha=0.3, min_detection_confidence=0.5, min_tracking_confidence=0.5):
|
123 |
+
overlay_file = overlay_file + '.png'
|
124 |
+
overlay_path = os.path.join(os.getcwd(), overlay_file)
|
125 |
+
overlay = cv.imread(overlay_path, cv.IMREAD_UNCHANGED)
|
126 |
+
processed_frame = process_frame(frame, overlay, LEFT_EYE, RIGHT_EYE, LEFT_IRIS, RIGHT_IRIS,
|
127 |
+
min_detection_confidence, min_tracking_confidence, alpha)
|
128 |
+
yield processed_frame
|
129 |
+
|
130 |
+
LEFT_EYE = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466, 388, 387, 386, 385, 384, 398]
|
131 |
+
RIGHT_EYE = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246]
|
132 |
+
LEFT_IRIS = [474, 475, 476, 477]
|
133 |
+
RIGHT_IRIS = [469, 470, 471, 472]
|
134 |
+
|
135 |
+
overlay_dir = os.path.join(os.getcwd(),'overlays')
|
136 |
+
overlay_files = list_overlay_images(overlay_dir)
|
137 |
+
overlay_choices = [x.split('.png')[0] for x in overlay_files]
|
138 |
+
with gr.Blocks() as demo:
|
139 |
+
with gr.Tab("Image"):
|
140 |
+
with gr.Row():
|
141 |
+
overlay_file = gr.Dropdown(choices=overlay_choices, value='Blue', label="Select a color")
|
142 |
+
# min_detection_confidence = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, label="Min Detection Confidence")
|
143 |
+
# min_tracking_confidence = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, label="Min Tracking Confidence")
|
144 |
+
# alpha = gr.Slider(minimum=0.0, maximum=1.0, value=0.3, label="Overlay Transparency")
|
145 |
+
with gr.Row():
|
146 |
+
input_image = gr.Image(height=500,width=400,label="Upload Image")
|
147 |
+
output_image = gr.Image(label="Processed Image")
|
148 |
+
process_image_btn = gr.Button("Process Image")
|
149 |
+
process_image_btn.click(process_image,
|
150 |
+
inputs=[input_image, overlay_file,],
|
151 |
+
outputs=output_image)
|
152 |
+
|
153 |
+
with gr.Tab("Video"):
|
154 |
+
with gr.Row():
|
155 |
+
overlay_file = gr.Dropdown(choices=overlay_choices, value='Blue', label="Select a color")
|
156 |
+
# min_detection_confidence = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, label="Min Detection Confidence")
|
157 |
+
# min_tracking_confidence = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, label="Min Tracking Confidence")
|
158 |
+
# alpha = gr.Slider(minimum=0.0, maximum=1.0, value=0.3, label="Overlay Transparency")
|
159 |
+
with gr.Row():
|
160 |
+
input_video = gr.Video(height=500,width=400,label="Upload Video")
|
161 |
+
output_video = gr.Video(height=500,label="Processed Video")
|
162 |
+
process_video_btn = gr.Button("Process Video")
|
163 |
+
process_video_btn.click(process_video,
|
164 |
+
inputs=[input_video, overlay_file,],
|
165 |
+
outputs=output_video)
|
166 |
+
|
167 |
+
with gr.Tab("Webcam"):
|
168 |
+
with gr.Row():
|
169 |
+
overlay_file = gr.Dropdown(choices=overlay_choices, value='Blue', label="Select a color")
|
170 |
+
# min_detection_confidence = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, label="Min Detection Confidence")
|
171 |
+
# min_tracking_confidence = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, label="Min Tracking Confidence")
|
172 |
+
# alpha = gr.Slider(minimum=0.0, maximum=1.0, value=0.3, label="Overlay Transparency")
|
173 |
+
with gr.Row():
|
174 |
+
# input_webcam = gr.Video(sources="webcam", label="Webcam")
|
175 |
+
webcam = gr.Image(sources="webcam",label="Processed Webcam",streaming=True)
|
176 |
+
process_webcam_btn = gr.Button("Process Webcam")
|
177 |
+
process_webcam_btn.click(process_webcam,
|
178 |
+
inputs=[webcam, overlay_file,],
|
179 |
+
outputs=webcam)
|
180 |
+
|
181 |
+
demo.launch()
|