habulaj commited on
Commit
417fcb1
·
verified ·
1 Parent(s): f38dc84

Update detect_crop_video.py

Browse files
Files changed (1) hide show
  1. detect_crop_video.py +181 -41
detect_crop_video.py CHANGED
@@ -237,6 +237,106 @@ def check_nvenc_support():
237
  return False
238
 
239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  def detect_and_crop_video(video_path, output_video_path, text_cut=True):
241
  """
242
  Detecta a região com movimento no vídeo e gera um vídeo cropado.
@@ -252,68 +352,108 @@ def detect_and_crop_video(video_path, output_video_path, text_cut=True):
252
  return False
253
 
254
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
 
 
255
 
256
  # Sample frames to detect motion
257
  num_samples = 15
258
  indices = np.linspace(0, total_frames - 1, num_samples, dtype=int)
259
 
260
- frames = []
 
261
  for i in indices:
262
  cap.set(cv2.CAP_PROP_POS_FRAMES, i)
263
  ret, frame = cap.read()
264
  if ret:
 
265
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
266
- frames.append(gray)
267
 
268
  cap.release()
269
 
270
- if len(frames) < 2:
271
- print(f"❌ Erro: Não foi possível ler frames suficientes ({len(frames)}/{num_samples}) para análise de movimento.")
272
  return False
273
 
274
- print(f"🔍 Analisando movimento em {len(frames)} frames amostrados...")
275
-
276
- # Calculate accumulated difference
277
- h, w = frames[0].shape
278
- accum_diff = np.zeros((h, w), dtype=np.float32)
279
 
280
- for i in range(len(frames) - 1):
281
- diff = cv2.absdiff(frames[i], frames[i+1])
282
- accum_diff = cv2.add(accum_diff, diff.astype(np.float32))
 
 
 
 
 
 
 
 
 
 
 
283
 
284
- accum_diff = cv2.normalize(accum_diff, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
285
- _, thresh = cv2.threshold(accum_diff, 20, 255, cv2.THRESH_BINARY)
286
-
287
- kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15))
288
- thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
289
- thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
290
-
291
- contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
292
-
293
- if not contours:
294
- print("❌ Aviso: Nenhum movimento detectado nos frames selecionados.")
295
- return False
296
 
297
- print(f"📊 Encontrados {len(contours)} contornos de movimento iniciais.")
 
 
 
 
 
298
 
299
- x_min, y_min = w, h
300
- x_max, y_max = 0, 0
301
-
302
- found_any = False
303
- for c in contours:
304
- if cv2.contourArea(c) > 500:
305
- found_any = True
306
- x, y, cw, ch = cv2.boundingRect(c)
307
- x_min = min(x_min, x)
308
- y_min = min(y_min, y)
309
- x_max = max(x_max, x + cw)
310
- y_max = max(y_max, y + ch)
311
 
312
- if not found_any:
313
- print("❌ Aviso: Nenhum movimento significativo (>500px area) detectado.")
314
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
 
316
- print(f"✅ Movimento consolidado na região: {x_min},{y_min} até {x_max},{y_max}")
 
 
 
 
 
 
 
 
 
 
 
317
 
318
  # Inset Logic (2px)
319
  inset = 2
 
237
  return False
238
 
239
 
240
+ def get_crop_detect_coords(video_path, limit=24, skip=5, duration=5):
241
+ """
242
+ Uses ffmpeg cropdetect filter to find the content area (removing black bars).
243
+ Returns (w, h, x, y) or None if detection fails.
244
+ """
245
+ try:
246
+ # Pula os primeiros segundos (skip) para evitar intros pretas,
247
+ # analisa por 'duration' segundos.
248
+ cmd = [
249
+ "ffmpeg", "-ss", str(skip), "-i", video_path,
250
+ "-t", str(duration), "-vf", f"cropdetect={limit}:16:0",
251
+ "-f", "null", "-"
252
+ ]
253
+ print(f"🎬 Executando ffmpeg cropdetect...")
254
+ result = subprocess.run(cmd, capture_output=True, text=True, check=False)
255
+
256
+ # O output do cropdetect sai no stderr
257
+ output = result.stderr
258
+
259
+ # Procurar pela última linha com 'crop='
260
+ import re
261
+ matches = re.findall(r"crop=(\d+):(\d+):(\d+):(\d+)", output)
262
+ if matches:
263
+ # Pegar a última ocorrência para garantir que a detecção estabilizou
264
+ w, h, x, y = map(int, matches[-1])
265
+ return w, h, x, y
266
+ return None
267
+ except Exception as e:
268
+ print(f"⚠️ Erro ao executar cropdetect: {e}")
269
+ return None
270
+
271
+
272
+ def get_content_density_crop(frames, color_var_threshold=8, complexity_threshold=10, min_density=0.15):
273
+ """
274
+ Analyzes row-by-row color variance and complexity to find the 'congruent line of colors'.
275
+ Isolates colorful video frames from monochromatic text overlays.
276
+ Returns (y_min, y_max).
277
+ """
278
+ if not frames:
279
+ return None
280
+
281
+ num_frames = len(frames)
282
+ h, w = frames[0].shape[:2]
283
+ all_y_min = []
284
+ all_y_max = []
285
+
286
+ for frame in frames:
287
+ if len(frame.shape) != 3:
288
+ continue
289
+
290
+ # 1. Color Variance Check (Crucial for 'Várias cores de forma congruente')
291
+ # In monochrome text (white/black/gray), R, G, B are identical or very close.
292
+ # Across a real video frame, colors vary significantly along the row.
293
+ b, g, r = cv2.split(frame.astype(np.int16))
294
+ rg = r - g
295
+ gb = g - b
296
+ br = b - r
297
+ # Variância de cor na linha
298
+ color_variance = np.std(rg, axis=1) + np.std(gb, axis=1) + np.std(br, axis=1)
299
+
300
+ # 2. Complexity Density (Variation across the row)
301
+ # Identifica linhas que são complexas (movimento/textura) em vez de texto isolado
302
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).astype(np.int16)
303
+ diff = np.abs(gray[:, 1:] - gray[:, :-1])
304
+ row_complexity = np.sum(diff > 15, axis=1) / w
305
+
306
+ # Unimos critérios: Deve ter variância de cor OU ser muito complexo
307
+ # (Para suportar vídeos P&B, mantemos uma margem de complexidade alta)
308
+ is_content = (color_variance > color_var_threshold) | (row_complexity > 0.40)
309
+
310
+ # Linhas que superam os critérios de conteúdo congruente
311
+ content_rows = np.where(is_content)[0]
312
+
313
+ if len(content_rows) > 0:
314
+ # Encontrar o maior bloco contínuo (pula texto isolado)
315
+ diffs = np.diff(content_rows)
316
+ # O split ocorre onde a diferença não é 1 (quebra na continuidade)
317
+ splits = np.where(diffs != 1)[0] + 1
318
+ blocks = np.split(content_rows, splits)
319
+
320
+ # Escolher o maior bloco contínuo em termos de número de linhas
321
+ main_block = max(blocks, key=len)
322
+
323
+ all_y_min.append(main_block[0])
324
+ all_y_max.append(main_block[-1])
325
+
326
+ if not all_y_min or not all_y_max:
327
+ return None
328
+
329
+ # Usamos o percentil 50 (mediana) para as fronteiras para estabilidade
330
+ y_min = int(np.percentile(all_y_min, 50))
331
+ y_max = int(np.percentile(all_y_max, 50))
332
+
333
+ # Adicionamos uma margem de segurança de 2px para não cortar o frame real
334
+ y_min = max(0, y_min - 2)
335
+ y_max = min(h, y_max + 2)
336
+
337
+ return y_min, y_max
338
+
339
+
340
  def detect_and_crop_video(video_path, output_video_path, text_cut=True):
341
  """
342
  Detecta a região com movimento no vídeo e gera um vídeo cropado.
 
352
  return False
353
 
354
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
355
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
356
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
357
 
358
  # Sample frames to detect motion
359
  num_samples = 15
360
  indices = np.linspace(0, total_frames - 1, num_samples, dtype=int)
361
 
362
+ frames_gray = []
363
+ frames_bgr = []
364
  for i in indices:
365
  cap.set(cv2.CAP_PROP_POS_FRAMES, i)
366
  ret, frame = cap.read()
367
  if ret:
368
+ frames_bgr.append(frame)
369
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
370
+ frames_gray.append(gray)
371
 
372
  cap.release()
373
 
374
+ if len(frames_gray) < 2:
375
+ print(f"❌ Erro: Não foi possível ler frames suficientes ({len(frames_gray)}/{num_samples}) para análise.")
376
  return False
377
 
378
+ # ---------------------------------------------------------
379
+ # Passo 1: Tentar detectar bordas via FFmpeg cropdetect
380
+ # ---------------------------------------------------------
381
+ crop_coords = get_crop_detect_coords(video_path)
 
382
 
383
+ use_motion_fallback = True
384
+ if crop_coords:
385
+ cw, ch, cx, cy = crop_coords
386
+ original_area = w * h
387
+ crop_area = cw * ch
388
+ reduction = (1 - crop_area / original_area) * 100
389
+
390
+ # Se houve uma redução significativa (>10%), confiamos no cropdetect
391
+ if reduction > 10:
392
+ print(f"✅ Cropdetect sugeriu: {cw}x{ch} @ ({cx},{cy}) | Redução: {reduction:.1f}%")
393
+ x_min, y_min, x_max, y_max = cx, cy, cx + cw, cy + ch
394
+ use_motion_fallback = False
395
+ else:
396
+ print(f"⏩ Cropdetect sugeriu redução irrelevante ({reduction:.1f}%). Usando motion fallback...")
397
 
398
+ # ---------------------------------------------------------
399
+ # Passo 2: Fallback para detecção de movimento (OpenCV)
400
+ # ---------------------------------------------------------
401
+ if use_motion_fallback:
402
+ print(f"🔍 Analisando movimento em {len(frames_gray)} frames amostrados...")
403
+
404
+ # Calculate accumulated difference
405
+ accum_diff = np.zeros((h, w), dtype=np.float32)
 
 
 
 
406
 
407
+ for i in range(len(frames_gray) - 1):
408
+ diff = cv2.absdiff(frames_gray[i], frames_gray[i+1])
409
+ accum_diff = cv2.add(accum_diff, diff.astype(np.float32))
410
+
411
+ accum_diff = cv2.normalize(accum_diff, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
412
+ _, thresh = cv2.threshold(accum_diff, 20, 255, cv2.THRESH_BINARY)
413
 
414
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15))
415
+ thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
416
+ thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
417
+
418
+ contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
419
+
420
+ if not contours:
421
+ print("❌ Aviso: Nenhum movimento detectado nos frames selecionados.")
422
+ return False
 
 
 
423
 
424
+ print(f"📊 Encontrados {len(contours)} contornos de movimento iniciais.")
425
+
426
+ x_min, y_min = w, h
427
+ x_max, y_max = 0, 0
428
+
429
+ found_any = False
430
+ for c in contours:
431
+ if cv2.contourArea(c) > 500:
432
+ found_any = True
433
+ x, y, cw, ch = cv2.boundingRect(c)
434
+ x_min = min(x_min, x)
435
+ y_min = min(y_min, y)
436
+ x_max = max(x_max, x + cw)
437
+ y_max = max(y_max, y + ch)
438
+
439
+ if not found_any:
440
+ print("❌ Aviso: Nenhum movimento significativo (>500px area) detectado.")
441
+ return False
442
+
443
+ print(f"✅ Movimento consolidado na região: {x_min},{y_min} até {x_max},{y_max}")
444
 
445
+ # ---------------------------------------------------------
446
+ # Passo 3: Refinamento por Densidade de Conteúdo (Garante linha divisória congruente)
447
+ # ---------------------------------------------------------
448
+ density_coords = get_content_density_crop(frames_bgr)
449
+ if density_coords:
450
+ dy_min, dy_max = density_coords
451
+ print(f"🎨 Refinamento de densidade sugeriu: Y de {dy_min} até {dy_max}")
452
+ # Aplicamos o refinamento se ele for mais restritivo (interno) ou se o movimento falhou
453
+ # Para evitar cortar o vídeo original por erro, conferimos se a área é razoável
454
+ y_min = max(y_min, dy_min)
455
+ y_max = min(y_max, dy_max)
456
+ print(f"✨ Região refinada final: Y de {y_min} até {y_max}")
457
 
458
  # Inset Logic (2px)
459
  inset = 2