fork download
  1. ; your code goes here
  2.  
  3. # This script adds a trailing light effect ("đèn vèo đít") to a tracked object in a video using OpenCV and MoviePy.
  4.  
  5. from moviepy.editor import VideoFileClip, CompositeVideoClip
  6. import cv2
  7. import numpy as np
  8. from moviepy.video.VideoClip import VideoClip
  9.  
  10. # Load video
  11. video_path = "/mnt/data/snaptik.vn_b2961.mp4"
  12. clip = VideoFileClip(video_path)
  13.  
  14. # Use a simple tracker based on background subtraction (for demonstration)
  15. cap = cv2.VideoCapture(video_path)
  16. fps = cap.get(cv2.CAP_PROP_FPS)
  17. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  18. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  19.  
  20. # Background subtractor
  21. fgbg = cv2.createBackgroundSubtractorMOG2()
  22. positions = []
  23.  
  24. # Track object positions
  25. while True:
  26. ret, frame = cap.read()
  27. if not ret:
  28. break
  29. fgmask = fgbg.apply(frame)
  30. contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  31. if contours:
  32. largest = max(contours, key=cv2.contourArea)
  33. M = cv2.moments(largest)
  34. if M["m00"] != 0:
  35. cx = int(M["m10"] / M["m00"])
  36. cy = int(M["m01"] / M["m00"])
  37. positions.append((cx, cy))
  38. else:
  39. positions.append((0, 0))
  40. else:
  41. positions.append((0, 0))
  42.  
  43. cap.release()
  44.  
  45. # Generate effect per frame
  46. def make_effect_frame(t):
  47. frame = np.zeros((height, width, 4), dtype=np.uint8)
  48. index = int(t * fps)
  49. tail_length = 10
  50. for i in range(tail_length):
  51. idx = index - i
  52. if 0 <= idx < len(positions):
  53. x, y = positions[idx]
  54. alpha = int(200 * (1 - i / tail_length))
  55. cv2.circle(frame, (x, y), 20, (255, 255, 0, alpha), -1)
  56. return frame
  57.  
  58. # Create and overlay effect clip
  59. effect = VideoClip(make_effect_frame, duration=clip.duration).set_duration(clip.duration)
  60. final = CompositeVideoClip([clip, effect])
  61.  
  62. # Output video
  63. final.write_videofile("/mnt/data/output_with_tail_light.mp4", codec="libx264", audio_codec="aac")
  64.  
  65. (exit)
  66. ; empty line at the end
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Standard output is empty