xmrt commited on
Commit
face1bf
·
1 Parent(s): a682a1b
Files changed (1) hide show
  1. main_noweb.py +270 -0
main_noweb.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pose inferencing
2
+ import mmpose
3
+ from mmpose.apis import MMPoseInferencer
4
+
5
+ # Ultralytics
6
+ from ultralytics import YOLO
7
+ import torch
8
+
9
+ # Gradio
10
+ import gradio as gr
11
+ import moviepy.editor as moviepy
12
+
13
+
14
+ # System and files
15
+ import os
16
+ import glob
17
+ import uuid
18
+
19
+ # Image manipulation
20
+ import numpy as np
21
+ import cv2
22
+
23
+ print(torch.__version__)
24
+ # Use GPU if available
25
+ if torch.cuda.is_available():
26
+ device = torch.device("cuda")
27
+ else:
28
+ device = torch.device("cpu")
29
+
30
+ os.system("nvidia-smi")
31
+
32
+ print("[INFO]: Imported modules!")
33
+ human = MMPoseInferencer("human")
34
+ hand = MMPoseInferencer("hand")
35
+ human3d = MMPoseInferencer(pose3d="human3d")
36
+ track_model = YOLO('yolov8n.pt') # Load an official Detect model
37
+
38
+
39
+ print("[INFO]: Downloaded models!")
40
+
41
+ def check_extension(video):
42
+ split_tup = os.path.splitext(video)
43
+
44
+ # extract the file name and extension
45
+ file_name = split_tup[0]
46
+ file_extension = split_tup[1]
47
+
48
+ if file_extension != ".mp4":
49
+ print("Converting to mp4")
50
+ clip = moviepy.VideoFileClip(video)
51
+
52
+ video = file_name+".mp4"
53
+ clip.write_videofile(video)
54
+
55
+ return video
56
+
57
+
58
+ def tracking(video, model, boxes=True):
59
+ print("[INFO] Is cuda available? ", torch.cuda.is_available())
60
+ print(device)
61
+
62
+ print("[INFO] Loading model...")
63
+ # Load an official or custom model
64
+
65
+ # Perform tracking with the model
66
+ print("[INFO] Starting tracking!")
67
+ # https://docs.ultralytics.com/modes/predict/
68
+ annotated_frame = model(video, boxes=boxes, device=device)
69
+
70
+ return annotated_frame
71
+
72
+ def show_tracking(video_content):
73
+
74
+ # https://docs.ultralytics.com/datasets/detect/coco/
75
+ video = cv2.VideoCapture(video_content)
76
+
77
+ # Track
78
+ video_track = tracking(video_content, track_model.track)
79
+
80
+ # Prepare to save video
81
+ #out_file = os.path.join(vis_out_dir, "track.mp4")
82
+ out_file = "track.mp4"
83
+ print("[INFO]: TRACK", out_file)
84
+
85
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v") # Codec for MP4 video
86
+ fps = video.get(cv2.CAP_PROP_FPS)
87
+ height, width, _ = video_track[0][0].orig_img.shape
88
+ size = (width,height)
89
+
90
+ out_track = cv2.VideoWriter(out_file, fourcc, fps, size)
91
+
92
+ # Go through frames and write them
93
+ for frame_track in video_track:
94
+ result_track = frame_track[0].plot() # plot a BGR numpy array of predictions
95
+ out_track.write(result_track)
96
+
97
+ print("[INFO] Done with frames")
98
+ #print(type(result_pose)) numpy ndarray
99
+
100
+ out_track.release()
101
+
102
+ video.release()
103
+ cv2.destroyAllWindows() # Closing window
104
+
105
+ return out_file
106
+
107
+
108
+ def pose3d(video):
109
+ video = check_extension(video)
110
+ print(device)
111
+
112
+
113
+ # Define new unique folder
114
+ add_dir = str(uuid.uuid4())
115
+ vis_out_dir = os.path.join("/".join(video.split("/")[:-1]), add_dir)
116
+ os.makedirs(vis_out_dir)
117
+
118
+ result_generator = human3d(video,
119
+ vis_out_dir = vis_out_dir,
120
+ thickness=4,
121
+ radius = 5,
122
+ return_vis=True,
123
+ kpt_thr=0.3,
124
+ rebase_keypoint_height=True,
125
+ device=device)
126
+
127
+ result = [result for result in result_generator] #next(result_generator)
128
+
129
+ out_file = glob.glob(os.path.join(vis_out_dir, "*.mp4")) #+ glob.glob(os.path.join(vis_out_dir, "*.webm"))
130
+
131
+ # Reinitialize
132
+ return "".join(out_file)
133
+
134
+
135
+ def pose2d(video, kpt_threshold):
136
+ video = check_extension(video)
137
+ print(device)
138
+
139
+ # Define new unique folder
140
+ add_dir = str(uuid.uuid4())
141
+ vis_out_dir = os.path.join("/".join(video.split("/")[:-1]), add_dir)
142
+ os.makedirs(vis_out_dir)
143
+
144
+ result_generator = human(video,
145
+ vis_out_dir = vis_out_dir,
146
+ return_vis=True,
147
+ radius = 5,
148
+ thickness=4,
149
+ rebase_keypoint_height=True,
150
+ kpt_thr=kpt_threshold,
151
+ device=device,
152
+ pred_out_dir = vis_out_dir
153
+ )
154
+
155
+ result = [result for result in result_generator] #next(result_generator)
156
+
157
+ out_file = glob.glob(os.path.join(vis_out_dir, "*.mp4")) #+ glob.glob(os.path.join(vis_out_dir, "*.webm"))
158
+ kpoints = glob.glob(os.path.join(vis_out_dir, "*.json"))
159
+
160
+ return "".join(out_file), "".join(kpoints)
161
+
162
+
163
+ def pose2dhand(video, kpt_threshold):
164
+ video = check_extension(video)
165
+ print(device)
166
+ # ultraltics
167
+
168
+ # Define new unique folder
169
+ add_dir = str(uuid.uuid4())
170
+ vis_out_dir = os.path.join("/".join(video.split("/")[:-1]), add_dir)
171
+ os.makedirs(vis_out_dir)
172
+
173
+ result_generator = hand(video,
174
+ vis_out_dir = vis_out_dir,
175
+ return_vis=True,
176
+ thickness = 4,
177
+ radius = 5,
178
+ rebase_keypoint_height=True,
179
+ kpt_thr=kpt_threshold,
180
+ device=device)
181
+
182
+ result = [result for result in result_generator] #next(result_generator)
183
+
184
+ out_file = glob.glob(os.path.join(vis_out_dir, "*.mp4")) #+ glob.glob(os.path.join(vis_out_dir, "*.webm"))
185
+
186
+ return "".join(out_file)
187
+
188
+ block = gr.Blocks()
189
+ with block:
190
+ with gr.Column():
191
+ with gr.Tab("Upload video"):
192
+ with gr.Column():
193
+ with gr.Row():
194
+ with gr.Column():
195
+ video_input = gr.Video(source="upload", type="filepath", height=612)
196
+ # Insert slider with kpt_thr
197
+ file_kpthr = gr.Slider(0, 1, value=0.3, label='Keypoint threshold')
198
+ with gr.Row():
199
+ submit_pose_file = gr.Button("Make 2d pose estimation", variant="primary")
200
+ submit_pose3d_file = gr.Button("Make 3d pose estimation", variant="primary")
201
+ submit_hand_file = gr.Button("Make 2d hand estimation", variant="primary")
202
+ submit_detect_file = gr.Button("Detect and track objects", variant="primary")
203
+
204
+ with gr.Row():
205
+ video_output1 = gr.PlayableVideo(height=512, label = "Estimate human 2d poses", show_label=True)
206
+ video_output2 = gr.PlayableVideo(height=512, label = "Estimate human 3d poses", show_label=True)
207
+ video_output3 = gr.PlayableVideo(height=512, label = "Estimate human hand poses", show_label=True)
208
+ video_output4 = gr.Video(height=512, label = "Detection and tracking", show_label=True, format="mp4")
209
+ jsonoutput = gr.Code()
210
+
211
+
212
+ with gr.Tab("General information"):
213
+ gr.Markdown("""
214
+ \n # Information about the models
215
+
216
+ \n ## Pose models:
217
+
218
+ \n All the pose estimation models come from the library [MMpose](https://github.com/open-mmlab/mmpose). It is a library for human pose estimation that provides pre-trained models for 2D and 3D pose estimation.
219
+
220
+ \n The 2D pose model is used for estimating the 2D coordinates of human body joints from an image or a video frame. The model uses a convolutional neural network (CNN) to predict the joint locations and their confidence scores.
221
+
222
+ \n The 2D hand model is a specialized version of the 2D pose model that is designed for hand pose estimation. It uses a similar CNN architecture to the 2D pose model but is trained specifically for detecting the joints in the hand.
223
+
224
+ \n The 3D pose model is used for estimating the 3D coordinates of human body joints from an image or a video frame. The model uses a combination of 2D pose estimation and depth estimation to infer the 3D joint locations.
225
+
226
+ \n
227
+
228
+ \n ## Detection and tracking:
229
+
230
+ \n The tracking method in the Ultralight's YOLOv8 model is used for object tracking in videos. It takes a video file or a camera stream as input and returns the tracked objects in each frame. The method uses the COCO dataset classes for object detection and tracking.
231
+
232
+ \n The COCO dataset contains 80 classes of objects such as person, car, bicycle, etc. See https://docs.ultralytics.com/datasets/detect/coco/ for all available classes. The tracking method uses the COCO classes to detect and track the objects in the video frames. The tracked objects are represented as bounding boxes with labels indicating the class of the object.""")
233
+ gr.Markdown("You can load the keypoints in python in the following way: ")
234
+ gr.Code(
235
+ value="""def hello_world():
236
+ return "Hello, world!"
237
+
238
+ print(hello_world())""",
239
+ language="python",
240
+ interactive=True,
241
+ show_label=False,
242
+ )
243
+
244
+
245
+ # From file
246
+ submit_pose_file.click(fn=pose2d,
247
+ inputs= [video_input, file_kpthr],
248
+ outputs = [video_output1, jsonoutput],
249
+ queue=False)
250
+
251
+ submit_pose3d_file.click(fn=pose3d,
252
+ inputs= video_input,
253
+ outputs = video_output2,
254
+ queue=False)
255
+
256
+ submit_hand_file.click(fn=pose2dhand,
257
+ inputs= [video_input, file_kpthr],
258
+ outputs = video_output3,
259
+ queue=False)
260
+
261
+ submit_detect_file.click(fn=show_tracking,
262
+ inputs= video_input,
263
+ outputs = video_output4,
264
+ queue=False)
265
+
266
+ if __name__ == "__main__":
267
+ block.queue()
268
+ block.launch(server_name="0.0.0.0", server_port=7860)
269
+
270
+