Advertisement
m4s5813

texto en video

Jun 13th, 2025
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. import cv2
  2.  
  3. def calcula_escala_font(texto, font, thickness_base, ancho_frame, margin):
  4.     # Medimos a escala 1.0
  5.     (w_texto, _), _ = cv2.getTextSize(texto, font, 1.0, thickness_base)
  6.     # Ajustamos la escala para que el texto + 2*margin entre en el frame
  7.     escala = (ancho_frame - 1*margin) / w_texto
  8.     return escala
  9.  
  10. # Parámetros
  11. video_path   = "./video.mp4"
  12. cap          = cv2.VideoCapture(video_path)
  13. fps          = cap.get(cv2.CAP_PROP_FPS)
  14. w            = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  15. h            = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  16. fourcc       = cv2.VideoWriter_fourcc(*"mp4v")
  17. out          = cv2.VideoWriter("video_con_margen.mp4", fourcc, fps, (w, h))
  18.  
  19. texto            = "Hola Hola"
  20. font             = cv2.FONT_HERSHEY_SIMPLEX
  21. thickness_base   = 2
  22.  
  23. # 1) Espacio al borde del vídeo
  24. margin_video     = 100  
  25.  
  26. # 2) Padding interno del rectángulo al texto
  27. pad_text         = 20  
  28.  
  29. # Calcula escala y grosor
  30. fontScale = calcula_escala_font(texto, font, thickness_base, w, margin_video)
  31. thickness = max(1, int(thickness_base * fontScale))
  32.  
  33. # Recalculamos tamaño del texto y coordenadas
  34. (text_w, text_h), baseline = cv2.getTextSize(texto, font, fontScale, thickness)
  35. # Centrado (toma en cuenta sólo el ancho disponible: w - 2*margin_video)
  36. x = margin_video + ((w - 2*margin_video) - text_w) // 2
  37. y = (h + text_h) // 2
  38.  
  39. while True:
  40.     ret, frame = cap.read()
  41.     if not ret: break
  42.  
  43.     t = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0
  44.     if 0.0 <= t <= 5.0:
  45.         # Fondo negro (usa pad_text para el interior)
  46.         tl = (x - pad_text, y - text_h - baseline - pad_text)
  47.         br = (x + text_w + pad_text, y + baseline + pad_text)
  48.         cv2.rectangle(frame, tl, br, (0,0,0), cv2.FILLED)
  49.  
  50.         # Texto centrado dentro del rectángulo
  51.         cv2.putText(frame, texto, (x, y),
  52.                     font, fontScale, (255,255,255),
  53.                     thickness, cv2.LINE_AA)
  54.  
  55.     out.write(frame)
  56.  
  57. cap.release()
  58. out.release()
  59. print("✓ Vídeo generado como video_con_margen.mp4")
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement