Python OpenCV – Reading a Video from cam or saved file

Python OpenCV library can be use to read a video, the video can be a live camera feed or a recorded video file. The below code is use to read a video from my laptop web cam.

Some explaination : at line 24 (cv2.waitKey(25) & 0xFF == ord('q')) :

  • waitKey return a 32 bit of the key that the user keyed. The 25 is 25 milliseconds(ms). If the argument is too big, like 500, you will notice a lag in the video due to the frame rate. 0 will freeze the video hence 0 is suitable for image.
  • 0xFF is hexidecimal for 0b11111111. And is only needed if your machine is 64bit else (cv2.waitKey(25) == ord('q')is sufficient . So a AND operator between 32 bit and 8 bit will result in a 8 bit. ‘ord’ will get the binary for letter ‘q’.
  • So if user hit ‘q’ key, the AND operation will result in a 8 bit binary of letter ‘q’ . So LHS = RHS and therefore break the loop.
import numpy as np
import cv2

#cap = cv2.VideoCapture(r'C:\Users\Linawati\Documents\ACCS\OpenCV\VideoForVideoCapture.mp4')
cap = cv2.VideoCapture(0)

# Check if camera opened successfully

if (cap.isOpened()== False): 
    print("Error opening video stream or file")

# Read until video is completed

  # Capture frame-by-frame, ret is boolean to check if there is frame
    ret, frame =
    if ret == True:
  # Display the resulting frame

 # Press Q on keyboard to  exit
        if cv2.waitKey(25) & 0xFF == ord('q'):
      # Break the loop
#Close video file or capturing device 

# Closes all the frames

Output camera stream:

This image generated from below code ↓, which does the same thing but with scaled down window and less line of code
import numpy as np
import cv2

cap = cv2.VideoCapture(0)

#Loop for video stream
while (True):
    stream = cv2.waitKey(1)   #Load video every 1ms and to detect user entered key
    #Read from videoCapture stream and display
    ret,frame =
    frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
    cv2.imshow("Frame", frame)
    if stream & 0XFF == ord('q'):  #Letter 'q' is the escape key
        break                      #get out of loop

Reading from saved video file:

The code:

import numpy as np
import cv2

#Video must be in the same directory if exact path is not given
cap = cv2.VideoCapture(r'VideoForVideoCapture.mp4')

#metadata of video, extra..not necessary
fps = int(cap.get(cv2.CAP_PROP_FPS))
frame_number = cap.get(cv2.CAP_PROP_FRAME_COUNT)
video_time = frame_number/fps

while True:
    ret, img =
    #exit loop if video ends
    if not ret:
    #resize video to fit screen, slight skew in the x axis,
    #to fit screen
    img = cv2.resize(img, (0,0), fx=0.45, fy=0.5)
    #Rotate video 90 deg clockwise
    img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE )
    cv2.imshow('Recorded Video',img)
    #exit loop anytime u want by entering 'q' key
    if cv2.waitKey(1) & 0xFF == ord('q'):