In this Python OpenCV lesson we are going to learn How to Play Mp4 Videos in Python OpenCV, before this we have learned that how you can read avi videos in opencv, you can use an mp4 video or you can use camera, the same code will be implemented with camera or mp4 video.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import cv2 cap = cv2.VideoCapture('mp4vid.mp4') #check if the video capture is open if(cap.isOpened() == False): print("Error Opening Video Stream Or File") while(cap.isOpened()): ret, frame =cap.read() if ret == True: cv2.imshow('frame', frame) if cv2.waitKey(25) == ord('q'): break else: break cap.release() cv2.destroyAllWindows() |
In here we are loading our mp4 video, make sure that you have already added a video in your working directory, if you are using camera you need to give 0 in cap = cv2.VideoCapture(‘mp4vid.mp4’).
1 |
cap = cv2.VideoCapture('mp4vid.mp4') |
Check if the video capture is opened, if it is not opened give error.
1 2 |
if(cap.isOpened() == False): print("Error Opening Video Stream Or File") |
Using this code we are reading our video, and we are checking if the video capture is opened we want to read the cap and show the frame, if we press the q key we want to close the video.
1 2 3 4 5 6 7 8 9 10 11 |
while(cap.isOpened()): ret, frame =cap.read() if ret == True: cv2.imshow('frame', frame) if cv2.waitKey(25) == ord('q'): break else: break |