fork download
  1. ; your code goes here
  2. from sys
  3.  
  4. (exit)
  5. ; empty line at the end
Success #stdin #stdout 0.01s 5320KB
stdin
# This script adds a trailing light effect ("đèn vèo đít") to a tracked object in a video using OpenCV and MoviePy.

from moviepy.editor import VideoFileClip, CompositeVideoClip
import cv2
import numpy as np
from moviepy.video.VideoClip import VideoClip

# Load video
video_path = "/mnt/data/snaptik.vn_b2961.mp4"
clip = VideoFileClip(video_path)

# Use a simple tracker based on background subtraction (for demonstration)
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Background subtractor
fgbg = cv2.createBackgroundSubtractorMOG2()
positions = []

# Track object positions
while True:
    ret, frame = cap.read()
    if not ret:
        break
    fgmask = fgbg.apply(frame)
    contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if contours:
        largest = max(contours, key=cv2.contourArea)
        M = cv2.moments(largest)
        if M["m00"] != 0:
            cx = int(M["m10"] / M["m00"])
            cy = int(M["m01"] / M["m00"])
            positions.append((cx, cy))
        else:
            positions.append((0, 0))
    else:
        positions.append((0, 0))

cap.release()

# Generate effect per frame
def make_effect_frame(t):
    frame = np.zeros((height, width, 4), dtype=np.uint8)
    index = int(t * fps)
    tail_length = 10
    for i in range(tail_length):
        idx = index - i
        if 0 <= idx < len(positions):
            x, y = positions[idx]
            alpha = int(200 * (1 - i / tail_length))
            cv2.circle(frame, (x, y), 20, (255, 255, 0, alpha), -1)
    return frame

# Create and overlay effect clip
effect = VideoClip(make_effect_frame, duration=clip.duration).set_duration(clip.duration)
final = CompositeVideoClip([clip, effect])

# Output video
final.write_videofile("/mnt/data/output_with_tail_light.mp4", codec="libx264", audio_codec="aac")
stdout
Standard output is empty