Search code examples
pythonopencvpython-imaging-libraryvideo-editing

Python - How can I apply a filter to video?


I vould like to edit a video using python. My code changes colors in some frames and so on. But when I get the result my new video is not the same length as the orginal (somenthimes it is shorter and somenthimes it is longer than the original video). But what I want to get is that the videos vould be equal in length. Any ideas?

Here is a part of my code:

import io, re, requests
from PIL import  Image, ImageOps, ImageEnhance, ImageChops
import cv2
import numpy as np

cap = cv2.VideoCapture('fish.mp4')

frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
   
size = (frame_width, frame_height)
result = cv2.VideoWriter('end.avi', cv2.VideoWriter_fourcc(*'MJPG'), 30,size)

while cap.isOpened():
    ret,frame = cap.read()
    
    #the editing part

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows() # destroy all opened windows

I thing that the error is in result = cv2.VideoWriter('end.avi', cv2.VideoWriter_fourcc(*'MJPG'), 30,size) line but I am not shure.


Solution

  • I'm not exactly sure, but in your code you are giving fps constant 30. Instead, you should take the fps of the input video and give it to the output video parametrically. Like this ;

    frame_width = int(cap.get(3)) 
    frame_height = int(cap.get(4)) 
    size = (frame_width, frame_height) 
    fps = cap.get(cv2.CAP_PROP_FPS)
    result = cv2.VideoWriter('end.avi',  
                             cv2.VideoWriter_fourcc(*'MJPG'), 
                             fps, size)