devkunalnaik commited on
Commit
e11e479
Β·
1 Parent(s): 47c8f24

Fix: remove duplicate swap() and dead _pose/_get_landmarks code from body_swap.py

Browse files
Files changed (1) hide show
  1. processors/body_swap.py +0 -140
processors/body_swap.py CHANGED
@@ -166,143 +166,3 @@ class BodySwapper:
166
  if mask.ndim == 3:
167
  mask = mask[:, :, 0]
168
  return mask
169
-
170
- def _get_landmarks(self, bgr: np.ndarray):
171
- """Return (x, y) pixel coords for all 33 pose landmarks, or None."""
172
- rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
173
- results = self._pose.process(rgb)
174
- if not results.pose_landmarks:
175
- return None
176
- h, w = bgr.shape[:2]
177
- return [
178
- (int(lm.x * w), int(lm.y * h))
179
- for lm in results.pose_landmarks.landmark
180
- ]
181
-
182
- @staticmethod
183
- def _bbox(mask: np.ndarray):
184
- """Bounding box (x1, y1, x2, y2) of non-zero mask region, or None."""
185
- ys, xs = np.where(mask > 128)
186
- if len(ys) == 0:
187
- return None
188
- return int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())
189
-
190
- @staticmethod
191
- def _torso_centroid(landmarks: list) -> tuple[float, float] | None:
192
- """Return the mean (x, y) of the four torso landmarks."""
193
- pts = [landmarks[i] for i in _TORSO_LANDMARKS if i < len(landmarks)]
194
- if not pts:
195
- return None
196
- xs = [p[0] for p in pts]
197
- ys = [p[1] for p in pts]
198
- return float(np.mean(xs)), float(np.mean(ys))
199
-
200
- # ── Public API ────────────────────────────────────────────────────────────
201
-
202
- def swap(
203
- self,
204
- source_bgr: np.ndarray,
205
- target_bgr: np.ndarray,
206
- blend_strength: float = 0.85,
207
- ) -> tuple[np.ndarray | None, str]:
208
- """
209
- Swap the source person's body into the target scene.
210
-
211
- Returns:
212
- (result_bgr, status_message)
213
- """
214
- try:
215
- # ── 1. Segment both images ────────────────────────────────────────
216
- src_mask = self._segment(source_bgr)
217
- tgt_mask = self._segment(target_bgr)
218
-
219
- src_bbox = self._bbox(src_mask)
220
- tgt_bbox = self._bbox(tgt_mask)
221
-
222
- if src_bbox is None:
223
- return None, "No person detected in source image."
224
- if tgt_bbox is None:
225
- return None, "No person detected in target image."
226
-
227
- sx1, sy1, sx2, sy2 = src_bbox
228
- tx1, ty1, tx2, ty2 = tgt_bbox
229
-
230
- # ── 2. Estimate poses ─────────────────────────────────────────────
231
- src_lm = self._get_landmarks(source_bgr)
232
- tgt_lm = self._get_landmarks(target_bgr)
233
-
234
- # ── 3. Scale source to match target bounding-box size ─────────────
235
- tgt_w, tgt_h = tx2 - tx1, ty2 - ty1
236
-
237
- src_person = source_bgr[sy1:sy2, sx1:sx2]
238
- src_mask_crop = src_mask[sy1:sy2, sx1:sx2]
239
-
240
- src_resized = cv2.resize(src_person, (tgt_w, tgt_h), interpolation=cv2.INTER_LINEAR)
241
- mask_resized = cv2.resize(src_mask_crop, (tgt_w, tgt_h), interpolation=cv2.INTER_LINEAR)
242
-
243
- # ── 4. Optional pose-guided translation offset ────────────────────
244
- offset_x, offset_y = 0, 0
245
- if src_lm and tgt_lm:
246
- src_c = self._torso_centroid(src_lm)
247
- tgt_c = self._torso_centroid(tgt_lm)
248
- if src_c and tgt_c:
249
- # Map source centroid into the cropped-then-resized space
250
- scale_x = tgt_w / max(sx2 - sx1, 1)
251
- scale_y = tgt_h / max(sy2 - sy1, 1)
252
- src_cx_resized = (src_c[0] - sx1) * scale_x
253
- src_cy_resized = (src_c[1] - sy1) * scale_y
254
- # Offset in target coordinates
255
- tgt_cx_in_roi = tgt_c[0] - tx1
256
- tgt_cy_in_roi = tgt_c[1] - ty1
257
- offset_x = int(tgt_cx_in_roi - src_cx_resized)
258
- offset_y = int(tgt_cy_in_roi - src_cy_resized)
259
-
260
- # ── 5. Build a full-canvas composite ─────────────────────────────
261
- h_tgt, w_tgt = target_bgr.shape[:2]
262
- canvas_fg = np.zeros_like(target_bgr)
263
- canvas_mask = np.zeros((h_tgt, w_tgt), dtype=np.uint8)
264
-
265
- # Destination rectangle after applying offset
266
- dst_x1 = np.clip(tx1 + offset_x, 0, w_tgt)
267
- dst_y1 = np.clip(ty1 + offset_y, 0, h_tgt)
268
- dst_x2 = np.clip(tx1 + offset_x + tgt_w, 0, w_tgt)
269
- dst_y2 = np.clip(ty1 + offset_y + tgt_h, 0, h_tgt)
270
-
271
- # Corresponding source slice
272
- src_x1 = dst_x1 - (tx1 + offset_x)
273
- src_y1 = dst_y1 - (ty1 + offset_y)
274
- src_x2 = src_x1 + (dst_x2 - dst_x1)
275
- src_y2 = src_y1 + (dst_y2 - dst_y1)
276
-
277
- if dst_x2 <= dst_x1 or dst_y2 <= dst_y1:
278
- return None, "Pose offset moved source body completely out of frame."
279
-
280
- canvas_fg[dst_y1:dst_y2, dst_x1:dst_x2] = src_resized[src_y1:src_y2, src_x1:src_x2]
281
- canvas_mask[dst_y1:dst_y2, dst_x1:dst_x2] = mask_resized[src_y1:src_y2, src_x1:src_x2]
282
-
283
- # ── 6. Color-correct source to match target's region ──────────────
284
- canvas_fg = apply_color_correction(canvas_fg, target_bgr, canvas_mask)
285
-
286
- # ── 7. Feather the mask and alpha-blend ───────────────────────────
287
- soft_mask = feather_mask(canvas_mask, blur_radius=21)
288
- soft_mask = (soft_mask.astype(float) * blend_strength).clip(0, 255).astype(np.uint8)
289
-
290
- result = alpha_blend(canvas_fg, target_bgr, soft_mask)
291
-
292
- # ── 8. Seamless clone for photorealistic blending (best-effort) ───
293
- try:
294
- center_x = int((dst_x1 + dst_x2) / 2)
295
- center_y = int((dst_y1 + dst_y2) / 2)
296
- # seamlessClone requires a clean binary mask
297
- sc_mask = (canvas_mask > 10).astype(np.uint8) * 255
298
- result = cv2.seamlessClone(
299
- canvas_fg, target_bgr, sc_mask,
300
- (center_x, center_y), cv2.NORMAL_CLONE,
301
- )
302
- except Exception as e:
303
- print(f"[BodySwapper] seamlessClone skipped: {e}")
304
-
305
- return result, "Body swap completed successfully."
306
-
307
- except Exception as exc:
308
- return None, f"Body swap error: {exc}"
 
166
  if mask.ndim == 3:
167
  mask = mask[:, :, 0]
168
  return mask