read video opencv python code example
Example 1: how to read video in opencv python
import numpy as np
import cv2
cap = cv2.VideoCapture('videos/wa.avi')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Example 2: read live video from usb opencv python
import cv2
cap = cv2.VideoCapture()
cap.open(0, cv2.CAP_DSHOW)
while(True):
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Example 3: how to get camera stream cv2
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Example 4: read video opencv python
import cv2
filename_video = "path_to_your_video"
input_video = cv2.VideoCapture(filename_video)
if input_video.isOpened() == False:
print("Video not found")
sys.exit(1)
else:
while(input_video.isOpened()):
ret, frame = input_video.read()
if ret == True:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
cv2.imshow('frame',frame)
else:
break
input_video.release()
cv2.destroyAllWindows()
Example 5: read video with opencv
import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture("Resources/test_ video.mp4")
while True:
success, img = cap.read()
img = cv2.resize(img, (frameWidth, frameHeight))
cv2.imshow("Result", img)
if cv2.waitKey(1) and 0xFF == ord('q'):
break