Last active
August 9, 2023 10:52
-
-
Save anujonthemove/69245d6f5cf7194913f405931f924b0f to your computer and use it in GitHub Desktop.
OpenCV Python Video Writer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import datetime | |
print(cv2.__version__) | |
def video_writer_decorator(func): | |
def wrapper(cap): | |
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
fps = int(cap.get(cv2.CAP_PROP_FPS)) | |
fourcc = cv2.VideoWriter_fourcc('M','J','P','G') | |
current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') | |
output_filename = f'output_{current_time}.avi' | |
out = cv2.VideoWriter(output_filename, fourcc, fps, (w, h)) | |
func(cap, out) | |
out.release() | |
return wrapper | |
@video_writer_decorator | |
def process_frames(cap, out): | |
while True: | |
ret, frame = cap.read() | |
if not ret: | |
break | |
out.write(frame) | |
cv2.imshow('frame', frame) | |
k = cv2.waitKey(1) | |
if k == 27: | |
cv2.destroyAllWindows() | |
break | |
if __name__ == "__main__": | |
abs_video_path = 'sample-video.mp4' | |
cap = cv2.VideoCapture(abs_video_path) | |
process_frames(cap) | |
cap.release() | |
cv2.destroyAllWindows() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
print(cv2.__version__) | |
abs_video_path = 'sample-video.mp4' | |
cap = cv2.VideoCapture(abs_video_path) | |
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
fps = int(cap.get(cv2.CAP_PROP_FPS)) | |
fourcc = cv2.VideoWriter_fourcc('M','J','P','G') | |
out = cv2.VideoWriter('test.avi', fourcc, fps, (w, h)) | |
while True: | |
ret, frame = cap.read() | |
if not ret: | |
break | |
out.write(frame) | |
cv2.imshow('frame', frame) | |
k = cv2.waitKey(1) | |
if k == 27: | |
cv2.destroyAllWindows() | |
cap.release() | |
out.release() | |
break | |
cv2.destroyAllWindows() | |
cap.release() | |
out.release() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment