❌

Reading view

There are new articles available, click to refresh the page.

open-cv open video

Playing a video in OpenCV is similar to opening an image, but it requires a loop to continuously read multiple frames.

Source Code

import cv2

video = cv2.VideoCapture("./data/video.mp4")

while(video.isOpened()):
    isTrue, frame = video.read()
    
    if(isTrue):
        frame = cv2.resize(frame,(800,500))
        cv2.imshow("play video",frame)
        if(cv2.waitKey(24)&0xFF == ord('q')):
            break
    else:
        break

video.release()
cv2.destroyAllWindows()

Video

Functions

Explain Program

Import OpenCV Library

import cv2

VideoCapture

This function is used to open a video by specifying a video path.

  • If you pass 0 as the argument, it opens the webcam instead.

isOpened

This function returns a boolean value to check if the video or resource is opened properly.

Use while to start a loop. with the condition isOpened().

read

This function reads a video frame by frame.

  • It returns two values:
    1. Boolean: True if the frame is read successfully.
    2. Frame Data: The actual video frame.

Use if(isTrue) to check if the data is properly read, then show the video.

  • Resize the video resolution using resize function.
  • Show the video using imshow.
  • Exit video on keypress if(cv2.waitKey(24)&0xFF == ord('q')).
    • Press β€˜qβ€˜ to break the video play loop.
Why Use &0xFF ?
  • This ensures the if condition runs correctly.
  • waitKey returns a key value, then performs an AND operation with 0xFF (which is 255 in hexadecimal).
  • If any number is used in an AND operation with 0xFF, it returns the same number.
    Example: 113 & 0xFF = 113 (same value as the first operand).

ord

The ord function returns the ASCII value of a character.

  • Example: ord('q') returns 113.

Finally, the if condition is validated.
If true, break the video play. Otherwise, continue playing.

release

This function releases the used resources.

destroyAllWindows() closes all windows and cleans up used memory.

Additional Link

github code

❌