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
|
|
|
|
|
|
|
4 |
|
5 |
-
def
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
13 |
|
14 |
if __name__ == "__main__":
|
15 |
-
|
16 |
|
|
|
1 |
+
#create a Streamlit app using info from image_demo.py
|
2 |
+
import cv2
|
3 |
+
import time
|
4 |
+
import argparse
|
5 |
import os
|
6 |
+
import torch
|
7 |
+
import posenet
|
8 |
+
import tempfile
|
9 |
+
from posenet.utils import *
|
10 |
+
import streamlit as st
|
11 |
+
from posenet.decode_multi import *
|
12 |
+
from visualizers import *
|
13 |
+
from ground_truth_dataloop import *
|
14 |
|
15 |
+
import cv2
|
16 |
+
import time
|
17 |
+
import argparse
|
18 |
+
import os
|
19 |
+
import torch
|
20 |
+
import posenet
|
21 |
+
import streamlit as st
|
22 |
+
from posenet.decode_multi import *
|
23 |
+
from visualizers import *
|
24 |
+
from ground_truth_dataloop import *
|
25 |
+
|
26 |
+
st.title('PoseNet Image Analyzer')
|
27 |
+
|
28 |
+
def process_frame(frame, scale_factor, output_stride):
|
29 |
+
input_image, draw_image, output_scale = process_input(frame, scale_factor=scale_factor, output_stride=output_stride)
|
30 |
+
return input_image, draw_image, output_scale
|
31 |
+
|
32 |
+
@st.cache_data()
|
33 |
+
|
34 |
+
def load_model(model):
|
35 |
+
model = posenet.load_model(model)
|
36 |
+
model = model.cuda()
|
37 |
+
return model
|
38 |
+
|
39 |
+
def main():
|
40 |
+
MAX_FILE_SIZE = 20 * 1024 * 1024 # 20 MB
|
41 |
+
|
42 |
+
model_number = st.sidebar.selectbox('Model', [101, 100, 75, 50])
|
43 |
+
scale_factor = 1.0
|
44 |
+
output_stride = st.sidebar.selectbox('Output Stride', [8, 16, 32, 64])
|
45 |
+
min_pose_score = st.sidebar.number_input("Minimum Pose Score", min_value=0.000, max_value=1.000, value=0.10, step=0.001)
|
46 |
+
st.sidebar.markdown(f'<p style="color:grey; font-size: 12px">The current number is {min_pose_score:.3f}</p>', unsafe_allow_html=True)
|
47 |
+
|
48 |
+
min_part_score = st.sidebar.number_input("Minimum Part Score", min_value=0.000, max_value=1.000, value=0.010, step=0.001)
|
49 |
+
st.sidebar.markdown(f'<p style="color:grey; font-size:12px">The current number is {min_part_score:.3f}</p>', unsafe_allow_html=True)
|
50 |
+
|
51 |
+
model = load_model(model_number)
|
52 |
+
output_stride = model.output_stride
|
53 |
+
output_dir = st.sidebar.text_input('Output Directory', './output')
|
54 |
+
|
55 |
+
option = st.selectbox('Choose an option', ['Upload Image', 'Upload Video', 'Try existing image'])
|
56 |
+
|
57 |
+
if option == 'Upload Video':
|
58 |
+
video_display_mode = st.selectbox("Video Display Mode", ['Frame by Frame', 'Entire Video'])
|
59 |
+
uploaded_video = st.file_uploader("Upload a video (mp4, mov, avi)", type=['mp4', 'mov', 'avi'])
|
60 |
+
|
61 |
+
if uploaded_video is not None:
|
62 |
+
tfile = tempfile.NamedTemporaryFile(delete=False)
|
63 |
+
tfile.write(uploaded_video.read())
|
64 |
+
|
65 |
+
vidcap = cv2.VideoCapture(tfile.name)
|
66 |
+
success, image = vidcap.read()
|
67 |
+
frames = []
|
68 |
+
frame_count = 0
|
69 |
+
|
70 |
+
while success:
|
71 |
+
input_image, draw_image, output_scale = process_frame(image, scale_factor, output_stride)
|
72 |
+
pose_scores, keypoint_scores, keypoint_coords = run_model(input_image, model, output_stride, output_scale)
|
73 |
+
|
74 |
+
result_image = posenet.draw_skel_and_kp(
|
75 |
+
draw_image, pose_scores, keypoint_scores, keypoint_coords,
|
76 |
+
min_pose_score=min_pose_score, min_part_score=min_part_score)
|
77 |
+
|
78 |
+
result_image = cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB)
|
79 |
+
# result_image = print_frame(draw_image, pose_scores, keypoint_scores, keypoint_coords, output_dir, min_part_score=min_part_score, min_pose_score=min_pose_score)
|
80 |
+
|
81 |
+
if result_image is not None:
|
82 |
+
frames.append(result_image)
|
83 |
+
success, image = vidcap.read()
|
84 |
+
frame_count += 1
|
85 |
+
|
86 |
+
if video_display_mode == 'Frame by Frame':
|
87 |
+
st.image(result_image, caption=f'Frame {frame_count}', use_column_width=True)
|
88 |
+
|
89 |
+
# Progress bar
|
90 |
+
progress_bar = st.progress(0)
|
91 |
+
|
92 |
+
# Write the output video
|
93 |
+
output_file = 'output.mp4'
|
94 |
+
height, width, layers = frames[0].shape
|
95 |
+
size = (width,height)
|
96 |
+
|
97 |
+
output_file_path = os.path.join(output_dir, output_file)
|
98 |
+
out = cv2.VideoWriter(output_file_path, cv2.VideoWriter_fourcc(*'mp4v'), 15, size)
|
99 |
+
|
100 |
+
for i in range(len(frames)):
|
101 |
+
progress_percentage = i / len(frames)
|
102 |
+
progress_bar.progress(progress_percentage)
|
103 |
+
out.write(cv2.cvtColor(frames[i], cv2.COLOR_RGB2BGR))
|
104 |
+
|
105 |
+
out.release()
|
106 |
+
|
107 |
+
|
108 |
+
# Display the processed video
|
109 |
+
if video_display_mode == 'Entire Video':
|
110 |
+
with open(output_file_path, "rb") as file:
|
111 |
+
bytes_data = file.read()
|
112 |
+
|
113 |
+
st.download_button(
|
114 |
+
label="Download video",
|
115 |
+
data=bytes_data,
|
116 |
+
file_name=output_file,
|
117 |
+
mime="video/mp4",
|
118 |
+
)
|
119 |
+
|
120 |
+
# video_file = open(output_file_path, 'rb')
|
121 |
+
# st.write(f"Output file path: {output_file_path}")
|
122 |
+
# video_bytes = video_file.read()
|
123 |
+
# st.video(video_bytes)
|
124 |
+
|
125 |
+
# try:
|
126 |
+
# st.video(bytes_data, format="video/mp4", start_time=0)
|
127 |
+
# # st.write(f"Output file path: {output_file_path}")
|
128 |
+
# # st.video('./output/output.mp4', format="video/mp4", start_time=0)
|
129 |
+
|
130 |
+
# except Exception as e:
|
131 |
+
# st.write("Error: ", str(e))
|
132 |
+
|
133 |
+
if frames:
|
134 |
+
frame_idx = st.slider('Choose a frame', 0, len(frames) - 1, 0)
|
135 |
+
input_image, draw_image, output_scale = process_frame(frames[frame_idx], scale_factor, output_stride)
|
136 |
+
pose_scores, keypoint_scores, keypoint_coords = run_model(input_image, model, output_stride, output_scale)
|
137 |
+
|
138 |
+
pose_data = {
|
139 |
+
'pose_scores': pose_scores.tolist(),
|
140 |
+
'keypoint_scores': keypoint_scores.tolist(),
|
141 |
+
'keypoint_coords': keypoint_coords.tolist()
|
142 |
+
}
|
143 |
+
|
144 |
+
st.image(draw_image, caption=f'Frame {frame_idx + 1}', use_column_width=True)
|
145 |
+
st.write(pose_data)
|
146 |
+
|
147 |
+
progress_bar.progress(1.0)
|
148 |
+
|
149 |
+
|
150 |
+
elif option == 'Upload Image':
|
151 |
+
image_file = st.file_uploader("Upload Image (Max 10MB)", type=['png', 'jpg', 'jpeg'])
|
152 |
+
|
153 |
+
if image_file is not None:
|
154 |
+
if image_file.size > MAX_FILE_SIZE:
|
155 |
+
st.error("File size exceeds the 10MB limit. Please upload a smaller file.")
|
156 |
+
file_bytes = np.asarray(bytearray(image_file.read()), dtype=np.uint8)
|
157 |
+
input_image = cv2.imdecode(file_bytes, 1)
|
158 |
+
filename = image_file.name
|
159 |
+
# Crop the image here as needed
|
160 |
+
# input_image = input_image[y:y+h, x:x+w]
|
161 |
+
|
162 |
+
input_image, source_image, output_scale = process_input(
|
163 |
+
input_image, scale_factor, output_stride)
|
164 |
+
|
165 |
+
pose_scores, keypoint_scores, keypoint_coords = run_model(input_image, model, output_stride, output_scale)
|
166 |
+
print_frame(source_image, pose_scores, keypoint_scores, keypoint_coords, output_dir, filename=filename, min_part_score=min_part_score, min_pose_score=min_pose_score)
|
167 |
+
else:
|
168 |
+
st.sidebar.warning("Please upload an image.")
|
169 |
+
|
170 |
+
|
171 |
+
|
172 |
+
elif option == 'Try existing image':
|
173 |
+
image_dir = st.sidebar.text_input('Image Directory', './images_train')
|
174 |
+
|
175 |
+
if output_dir:
|
176 |
+
if not os.path.exists(output_dir):
|
177 |
+
os.makedirs(output_dir)
|
178 |
+
|
179 |
+
filenames = [f.path for f in os.scandir(image_dir) if f.is_file() and f.path.endswith(('.png', '.jpg'))]
|
180 |
+
|
181 |
+
if filenames:
|
182 |
+
selected_image = st.sidebar.selectbox('Choose an image', filenames)
|
183 |
+
|
184 |
+
input_image, draw_image, output_scale = posenet.read_imgfile(
|
185 |
+
selected_image, scale_factor=scale_factor, output_stride=output_stride)
|
186 |
+
|
187 |
+
filename = os.path.basename(selected_image)
|
188 |
+
result_image, pose_scores, keypoint_scores, keypoint_coords = run_model(input_image, draw_image, model, output_stride, output_scale)
|
189 |
+
print_frame(result_image, pose_scores, keypoint_scores, keypoint_coords, output_dir, filename=selected_image, min_part_score=min_part_score, min_pose_score=min_pose_score)
|
190 |
+
|
191 |
+
|
192 |
+
else:
|
193 |
+
st.sidebar.warning("No images found in directory.")
|
194 |
+
|
195 |
+
#same as utils.py _process_input
|
196 |
+
def process_input(source_img, scale_factor=1.0, output_stride=16):
|
197 |
+
target_width, target_height = posenet.valid_resolution(
|
198 |
+
source_img.shape[1] * scale_factor, source_img.shape[0] * scale_factor, output_stride=output_stride)
|
199 |
+
scale = np.array([source_img.shape[0] / target_height, source_img.shape[1] / target_width])
|
200 |
+
input_img = cv2.resize(source_img, (target_width, target_height), interpolation=cv2.INTER_LINEAR)
|
201 |
+
input_img = cv2.cvtColor(input_img, cv2.COLOR_BGR2RGB).astype(np.float32)
|
202 |
+
input_img = input_img * (2.0 / 255.0) - 1.0
|
203 |
+
input_img = input_img.transpose((2, 0, 1)).reshape(1, 3, target_height, target_width)
|
204 |
+
return input_img, source_img, scale
|
205 |
+
|
206 |
+
def run_model(input_image, model, output_stride, output_scale):
|
207 |
+
|
208 |
+
with torch.no_grad():
|
209 |
+
input_image = torch.Tensor(input_image).cuda()
|
210 |
+
|
211 |
+
heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = model(input_image)
|
212 |
+
|
213 |
+
# st.text("model heatmaps_result shape: {}".format(heatmaps_result.shape))
|
214 |
+
# st.text("model offsets_result shape: {}".format(offsets_result.shape))
|
215 |
+
|
216 |
+
pose_scores, keypoint_scores, keypoint_coords, pose_offsets = posenet.decode_multi.decode_multiple_poses(
|
217 |
+
heatmaps_result.squeeze(0),
|
218 |
+
offsets_result.squeeze(0),
|
219 |
+
displacement_fwd_result.squeeze(0),
|
220 |
+
displacement_bwd_result.squeeze(0),
|
221 |
+
output_stride=output_stride,
|
222 |
+
max_pose_detections=10,
|
223 |
+
min_pose_score=0.0)
|
224 |
+
|
225 |
+
# st.text("decoded pose_scores shape: {}".format(pose_scores.shape))
|
226 |
+
# st.text("decoded pose_offsets shape: {}".format(pose_offsets.shape))
|
227 |
+
|
228 |
+
keypoint_coords *= output_scale
|
229 |
+
|
230 |
+
# Convert BGR to RGB
|
231 |
+
|
232 |
+
return pose_scores, keypoint_scores, keypoint_coords
|
233 |
|
234 |
+
def print_frame(draw_image, pose_scores, keypoint_scores, keypoint_coords, output_dir, filename=None, min_part_score=0.01, min_pose_score=0.1):
|
235 |
+
if output_dir:
|
236 |
+
|
237 |
+
draw_image = posenet.draw_skel_and_kp(
|
238 |
+
draw_image, pose_scores, keypoint_scores, keypoint_coords,
|
239 |
+
min_pose_score=min_pose_score, min_part_score=min_part_score)
|
240 |
+
|
241 |
+
draw_image = cv2.cvtColor(draw_image, cv2.COLOR_BGR2RGB)
|
242 |
|
243 |
+
if filename:
|
244 |
+
cv2.imwrite(os.path.join(output_dir, filename), draw_image)
|
245 |
+
else:
|
246 |
+
cv2.imwrite(os.path.join(output_dir, "output.png"), draw_image)
|
247 |
+
|
248 |
+
st.image(draw_image, caption='PoseNet Output', use_column_width=True)
|
249 |
+
st.text("Results for image: %s" % filename)
|
250 |
+
st.text("Size of draw_image: {}".format(draw_image.shape))
|
251 |
|
252 |
+
for pi in range(len(pose_scores)):
|
253 |
+
if pose_scores[pi] == 0.:
|
254 |
+
break
|
255 |
+
st.text('Pose #%d, score = %f' % (pi, pose_scores[pi]))
|
256 |
+
for ki, (s, c) in enumerate(zip(keypoint_scores[pi, :], keypoint_coords[pi, :, :])):
|
257 |
+
st.text('Keypoint %s, score = %f, coord = %s' % (posenet.PART_NAMES[ki], s, c))
|
258 |
|
259 |
if __name__ == "__main__":
|
260 |
+
main()
|
261 |
|