Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Last active March 22, 2023 10:54
Show Gist options
  • Select an option

  • Save EteimZ/6b25f7c2921ba5c0c4d6ed1747ae80e7 to your computer and use it in GitHub Desktop.

Select an option

Save EteimZ/6b25f7c2921ba5c0c4d6ed1747ae80e7 to your computer and use it in GitHub Desktop.
Working with Video in opencv
import numpy as np
import cv2 as cv
cap = cv.VideoCapture('vid.mp4')
while cap.isOpened():
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cv.imshow('frame', gray)
if cv.waitKey(1) == ord('q'):
break
cap.release()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
import sys
cap = cv.VideoCapture(0)
if not cap.isOpened():
sys.exit("Cannot open camera")
while True:
# capture frame-by-frame
ret, frame = cap.read()
# if frame is read correctly ret is True
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# Convert frame to gray
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) == ord('q'):
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
# Define codec by specifying four character code
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
frame = cv.flip(frame, 0)
# write the flipped frame
out.write(frame)
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):
break
# Release everything if job is finished
cap.release()
out.release()
cv.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment