Update DWPose visualization styles

#2
Files changed (1) hide show
  1. utils/draw_dw_lib.py +204 -31
utils/draw_dw_lib.py CHANGED
@@ -14,12 +14,114 @@ from typing import List, Dict, Any, Optional, Tuple
14
 
15
  eps = 0.01
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def alpha_blend_color(color, alpha):
18
  """blend color according to point conf
19
  """
20
  return [int(c * alpha) for c in color]
21
 
22
- def draw_bodypose(canvas, candidate, subset, score, transparent=False):
23
  """Draw body pose on canvas
24
  Args:
25
  canvas: numpy array canvas to draw on
@@ -34,7 +136,7 @@ def draw_bodypose(canvas, candidate, subset, score, transparent=False):
34
  candidate = np.array(candidate)
35
  subset = np.array(subset)
36
 
37
- stickwidth = 4
38
 
39
  limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10],
40
  [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17],
@@ -82,11 +184,11 @@ def draw_bodypose(canvas, candidate, subset, score, transparent=False):
82
  color = colors[i][:-1] + [int(255 * conf)] # Adjust alpha based on confidence
83
  else:
84
  color = colors[i]
85
- cv2.circle(canvas, (int(x), int(y)), 4, color, thickness=-1)
86
 
87
  return canvas
88
 
89
- def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False):
90
  """Draw hand pose on canvas"""
91
  H, W, C = canvas.shape
92
 
@@ -105,10 +207,10 @@ def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False):
105
  if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
106
  color = matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0])
107
  if transparent:
108
- color = np.append(color, score) # Add alpha channel
109
  else:
110
- color = color * score
111
- cv2.line(canvas, (x1, y1), (x2, y2), color * 255, thickness=2)
112
 
113
  for i, keypoint in enumerate(peaks):
114
  x, y = keypoint
@@ -116,13 +218,13 @@ def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False):
116
  y = int(y * H)
117
  if x > eps and y > eps:
118
  if transparent:
119
- color = (0, 0, 0, scores[i]) # Black with alpha
120
  else:
121
- color = (0, 0, int(scores[i] * 255)) # Original color
122
- cv2.circle(canvas, (x, y), 4, color, thickness=-1)
123
  return canvas
124
 
125
- def draw_facepose(canvas, all_lmks, all_scores, transparent=False):
126
  """Draw face pose on canvas"""
127
  H, W, C = canvas.shape
128
  for lmks, scores in zip(all_lmks, all_scores):
@@ -136,10 +238,21 @@ def draw_facepose(canvas, all_lmks, all_scores, transparent=False):
136
  else:
137
  conf = int(score * 255)
138
  color = (conf, conf, conf) # Original grayscale
139
- cv2.circle(canvas, (x, y), 3, color, thickness=-1)
140
  return canvas
141
 
142
- def draw_pose(pose, H, W, include_body=True, include_hand=True, include_face=True, ref_w=2160, transparent=False):
 
 
 
 
 
 
 
 
 
 
 
143
  """vis dwpose outputs with optional transparent background
144
 
145
  Args:
@@ -175,31 +288,74 @@ def draw_pose(pose, H, W, include_body=True, include_hand=True, include_face=Tru
175
  subset = bodies['subset']
176
 
177
  if include_body:
178
- canvas = draw_bodypose(canvas, candidate, subset, score=bodies['score'], transparent=transparent)
 
 
 
 
 
 
 
 
179
 
180
  if include_hand:
181
- canvas = draw_handpose(canvas, hands, processed_data['hands_score'], transparent=transparent)
 
 
 
 
 
 
 
182
 
183
  if include_face:
184
- canvas = draw_facepose(canvas, faces, processed_data['faces_score'], transparent=transparent)
 
 
 
 
 
 
185
 
186
  else:
187
  # 兼容旧的数据格式 - 作为备选方案
188
  try:
189
- bodies = pose['bodies']
190
- faces = pose['faces']
191
- hands = pose['hands']
 
192
  candidate = bodies['candidate']
193
  subset = bodies['subset']
194
 
195
  if include_body:
196
- canvas = draw_bodypose(canvas, candidate, subset, score=bodies['score'], transparent=transparent)
 
 
 
 
 
 
 
 
197
 
198
  if include_hand:
199
- canvas = draw_handpose(canvas, hands, pose['hands_score'], transparent=transparent)
 
 
 
 
 
 
 
200
 
201
  if include_face:
202
- canvas = draw_facepose(canvas, faces, pose['faces_score'], transparent=transparent)
 
 
 
 
 
 
203
  except Exception as e:
204
  print(f"绘制旧格式数据失败: {str(e)}")
205
  # 返回空画布
@@ -270,14 +426,31 @@ def process_pose_data(pose_data: Dict[str, Any], height: int, width: int) -> Dic
270
  face_scores = np.array(all_face_scores) if all_face_scores else np.array([])
271
 
272
  else:
273
- # 兼容性处理 - 如果不是新格式,返回空数据
274
- bodies = np.array([])
275
- subset = np.array([[]])
276
- scores = np.array([[]])
277
- hands = np.array([])
278
- hand_scores = np.array([])
279
- faces = np.array([])
280
- face_scores = np.array([])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
  processed_data['bodies'] = {
283
  'candidate': bodies,
@@ -291,4 +464,4 @@ def process_pose_data(pose_data: Dict[str, Any], height: int, width: int) -> Dic
291
  processed_data['faces'] = faces
292
  processed_data['faces_score'] = face_scores
293
 
294
- return processed_data
 
14
 
15
  eps = 0.01
16
 
17
+ RENDER_STYLES = {
18
+ "bold": {"line_scale": 3.0, "point_scale": 2.0},
19
+ "thin": {"line_scale": 1.0, "point_scale": 1.0},
20
+ }
21
+
22
+
23
+ def get_render_style(style: str = "bold") -> Dict[str, float]:
24
+ """Return named DWPose rendering style parameters."""
25
+ if style not in RENDER_STYLES:
26
+ raise ValueError(f"Unknown render style '{style}'. Choose from: {sorted(RENDER_STYLES)}")
27
+ return RENDER_STYLES[style]
28
+
29
+
30
+ def filter_pose_by_confidence(
31
+ pose_data: Dict[str, Any],
32
+ conf_threshold: float = 0.6,
33
+ ) -> Dict[str, Any]:
34
+ """Filter low-confidence joints before rendering."""
35
+ filtered = {}
36
+ for key, value in pose_data.items():
37
+ if isinstance(value, np.ndarray):
38
+ filtered[key] = value.copy()
39
+ else:
40
+ filtered[key] = value
41
+
42
+ bodies = filtered.get("bodies")
43
+ body_scores = filtered.get("body_scores")
44
+ if bodies is not None:
45
+ bodies = np.array(bodies, copy=True)
46
+ min_valid = 1e-6
47
+ coord_mask = (bodies[:, 0] > min_valid) & (bodies[:, 1] > min_valid)
48
+
49
+ conf_mask = None
50
+ if body_scores is not None:
51
+ score_vec = np.asarray(body_scores).reshape(-1).astype(float)
52
+ conf_mask = score_vec < conf_threshold
53
+ if conf_mask.shape[0] < bodies.shape[0]:
54
+ conf_mask = np.pad(
55
+ conf_mask,
56
+ (0, bodies.shape[0] - conf_mask.shape[0]),
57
+ constant_values=False,
58
+ )
59
+ elif conf_mask.shape[0] > bodies.shape[0]:
60
+ conf_mask = conf_mask[: bodies.shape[0]]
61
+
62
+ valid_mask = coord_mask if conf_mask is None else coord_mask & (~conf_mask)
63
+ bodies[~valid_mask, :] = 0
64
+ filtered["bodies"] = bodies
65
+
66
+ if body_scores is not None:
67
+ subset = np.array(body_scores, copy=True)
68
+ if subset.ndim == 1:
69
+ subset = subset.reshape(1, -1)
70
+ else:
71
+ subset = np.arange(bodies.shape[0], dtype=float).reshape(1, -1)
72
+
73
+ if subset.shape[1] < bodies.shape[0]:
74
+ subset = np.pad(
75
+ subset,
76
+ ((0, 0), (0, bodies.shape[0] - subset.shape[1])),
77
+ constant_values=-1,
78
+ )
79
+ elif subset.shape[1] > bodies.shape[0]:
80
+ subset = subset[:, : bodies.shape[0]]
81
+
82
+ subset[:, ~valid_mask] = -1
83
+ filtered["body_scores"] = subset
84
+
85
+ hands = filtered.get("hands")
86
+ hand_scores = filtered.get("hands_scores")
87
+ if hands is not None and hand_scores is not None:
88
+ hands = np.array(hands, copy=True)
89
+ scores = np.array(hand_scores)
90
+ if hands.ndim == 3 and scores.ndim in (2, 3):
91
+ for h in range(hands.shape[0]):
92
+ cur_scores = scores[h] if scores.ndim == 2 else scores[h]
93
+ mask = (cur_scores < conf_threshold) | (cur_scores <= 0)
94
+ hands[h][mask, :] = 0
95
+ elif hands.ndim == 2 and scores.ndim in (1, 2):
96
+ cur_scores = scores if scores.ndim == 1 else scores.reshape(-1)
97
+ mask = (cur_scores < conf_threshold) | (cur_scores <= 0)
98
+ hands[mask, :] = 0
99
+ filtered["hands"] = hands
100
+
101
+ faces = filtered.get("faces")
102
+ face_scores = filtered.get("faces_scores")
103
+ if faces is not None and face_scores is not None:
104
+ faces = np.array(faces, copy=True)
105
+ scores = np.array(face_scores)
106
+ if faces.ndim == 3 and scores.ndim in (2, 3):
107
+ for f in range(faces.shape[0]):
108
+ cur_scores = scores[f] if scores.ndim == 2 else scores[f]
109
+ mask = (cur_scores < conf_threshold) | (cur_scores <= 0)
110
+ faces[f][mask, :] = 0
111
+ elif faces.ndim == 2 and scores.ndim in (1, 2):
112
+ cur_scores = scores if scores.ndim == 1 else scores.reshape(-1)
113
+ mask = (cur_scores < conf_threshold) | (cur_scores <= 0)
114
+ faces[mask, :] = 0
115
+ filtered["faces"] = faces
116
+
117
+ return filtered
118
+
119
  def alpha_blend_color(color, alpha):
120
  """blend color according to point conf
121
  """
122
  return [int(c * alpha) for c in color]
123
 
124
+ def draw_bodypose(canvas, candidate, subset, score, transparent=False, line_scale=1.0, point_scale=1.0):
125
  """Draw body pose on canvas
126
  Args:
127
  canvas: numpy array canvas to draw on
 
136
  candidate = np.array(candidate)
137
  subset = np.array(subset)
138
 
139
+ stickwidth = max(1, int(round(4 * line_scale)))
140
 
141
  limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10],
142
  [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17],
 
184
  color = colors[i][:-1] + [int(255 * conf)] # Adjust alpha based on confidence
185
  else:
186
  color = colors[i]
187
+ cv2.circle(canvas, (int(x), int(y)), max(1, int(round(4 * point_scale))), color, thickness=-1)
188
 
189
  return canvas
190
 
191
+ def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False, line_scale=1.0, point_scale=1.0):
192
  """Draw hand pose on canvas"""
193
  H, W, C = canvas.shape
194
 
 
207
  if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
208
  color = matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0])
209
  if transparent:
210
+ color = tuple(int(c * 255) for c in color) + (int(score * 255),)
211
  else:
212
+ color = tuple(int(c * score * 255) for c in color)
213
+ cv2.line(canvas, (x1, y1), (x2, y2), color, thickness=max(1, int(round(2 * line_scale))))
214
 
215
  for i, keypoint in enumerate(peaks):
216
  x, y = keypoint
 
218
  y = int(y * H)
219
  if x > eps and y > eps:
220
  if transparent:
221
+ color = (0, 0, 0, int(scores[i] * 255))
222
  else:
223
+ color = (0, 0, int(scores[i] * 255))
224
+ cv2.circle(canvas, (x, y), max(1, int(round(4 * point_scale))), color, thickness=-1)
225
  return canvas
226
 
227
+ def draw_facepose(canvas, all_lmks, all_scores, transparent=False, point_scale=1.0):
228
  """Draw face pose on canvas"""
229
  H, W, C = canvas.shape
230
  for lmks, scores in zip(all_lmks, all_scores):
 
238
  else:
239
  conf = int(score * 255)
240
  color = (conf, conf, conf) # Original grayscale
241
+ cv2.circle(canvas, (x, y), max(1, int(round(3 * point_scale))), color, thickness=-1)
242
  return canvas
243
 
244
+ def draw_pose(
245
+ pose,
246
+ H,
247
+ W,
248
+ include_body=True,
249
+ include_hand=True,
250
+ include_face=True,
251
+ ref_w=2160,
252
+ transparent=False,
253
+ line_scale=1.0,
254
+ point_scale=1.0,
255
+ ):
256
  """vis dwpose outputs with optional transparent background
257
 
258
  Args:
 
288
  subset = bodies['subset']
289
 
290
  if include_body:
291
+ canvas = draw_bodypose(
292
+ canvas,
293
+ candidate,
294
+ subset,
295
+ score=bodies['score'],
296
+ transparent=transparent,
297
+ line_scale=line_scale,
298
+ point_scale=point_scale,
299
+ )
300
 
301
  if include_hand:
302
+ canvas = draw_handpose(
303
+ canvas,
304
+ hands,
305
+ processed_data['hands_score'],
306
+ transparent=transparent,
307
+ line_scale=line_scale,
308
+ point_scale=point_scale,
309
+ )
310
 
311
  if include_face:
312
+ canvas = draw_facepose(
313
+ canvas,
314
+ faces,
315
+ processed_data['faces_score'],
316
+ transparent=transparent,
317
+ point_scale=point_scale,
318
+ )
319
 
320
  else:
321
  # 兼容旧的数据格式 - 作为备选方案
322
  try:
323
+ processed_data = process_pose_data(pose, H, W)
324
+ bodies = processed_data['bodies']
325
+ faces = processed_data['faces']
326
+ hands = processed_data['hands']
327
  candidate = bodies['candidate']
328
  subset = bodies['subset']
329
 
330
  if include_body:
331
+ canvas = draw_bodypose(
332
+ canvas,
333
+ candidate,
334
+ subset,
335
+ score=bodies['score'],
336
+ transparent=transparent,
337
+ line_scale=line_scale,
338
+ point_scale=point_scale,
339
+ )
340
 
341
  if include_hand:
342
+ canvas = draw_handpose(
343
+ canvas,
344
+ hands,
345
+ processed_data['hands_score'],
346
+ transparent=transparent,
347
+ line_scale=line_scale,
348
+ point_scale=point_scale,
349
+ )
350
 
351
  if include_face:
352
+ canvas = draw_facepose(
353
+ canvas,
354
+ faces,
355
+ processed_data['faces_score'],
356
+ transparent=transparent,
357
+ point_scale=point_scale,
358
+ )
359
  except Exception as e:
360
  print(f"绘制旧格式数据失败: {str(e)}")
361
  # 返回空画布
 
426
  face_scores = np.array(all_face_scores) if all_face_scores else np.array([])
427
 
428
  else:
429
+ # 兼容旧的单人数据格式
430
+ raw_bodies = np.array(pose_data.get('bodies', []), dtype=np.float32)
431
+ raw_body_scores = np.array(pose_data.get('body_scores', []), dtype=np.float32)
432
+ raw_hands = np.array(pose_data.get('hands', []), dtype=np.float32)
433
+ raw_hand_scores = np.array(pose_data.get('hands_scores', []), dtype=np.float32)
434
+ raw_faces = np.array(pose_data.get('faces', []), dtype=np.float32)
435
+ raw_face_scores = np.array(pose_data.get('faces_scores', []), dtype=np.float32)
436
+
437
+ if raw_bodies.size > 0:
438
+ bodies = raw_bodies.reshape(-1, 2)
439
+ subset = np.arange(bodies.shape[0], dtype=np.int32)[None, :]
440
+
441
+ if raw_body_scores.size > 0:
442
+ scores = raw_body_scores.reshape(1, -1)
443
+ else:
444
+ scores = np.ones((1, bodies.shape[0]), dtype=np.float32)
445
+ else:
446
+ bodies = np.array([])
447
+ subset = np.array([[]])
448
+ scores = np.array([[]])
449
+
450
+ hands = raw_hands if raw_hands.size > 0 else np.array([])
451
+ hand_scores = raw_hand_scores if raw_hand_scores.size > 0 else np.array([])
452
+ faces = raw_faces if raw_faces.size > 0 else np.array([])
453
+ face_scores = raw_face_scores if raw_face_scores.size > 0 else np.array([])
454
 
455
  processed_data['bodies'] = {
456
  'candidate': bodies,
 
464
  processed_data['faces'] = faces
465
  processed_data['faces_score'] = face_scores
466
 
467
+ return processed_data