Unable to read MP4 and avi files in OpenCV Python

Viewed 6703

I want to just read and display an MP4 video using OpenCV, I wrote the following basic code for it:

import cv2

input_video_path = './Input Video/Input_video1.mp4'

cap = cv2.VideoCapture(input_video_path)

while(cap.isOpened()):
    ret, frame = cap.read()
    print(frame, ret)
    cv2.imshow("frame", frame)

cap.release()
cv2.destroyAllWindows()

When I run it, it reads 1st few frames and then all other frames are None:

[[[  7  14  27]
  [  7  14  27]
  [  7  14  27]
  ...
  ...
  [ 60  57  64]
  [ 70  62  64]
  [ 72  64  66]]] True
None False
Traceback (most recent call last):
  File "D:/Project/ML IP and Coding/Cynapto_Task/exploring_face_detection_methods.py", line 10, in <module>
    cv2.imshow("frame", frame)
cv2.error: OpenCV(3.4.2) C:\Miniconda3\conda-bld\opencv-suite_1534379934306\work\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

I also printed the ret variable which confirms the same behavior. I tried with 2-3 different videos and even with .avi format but got the same result.

I searched online for a solution but could only find about codecs and installing codecs in my virtual environment. I don't have much knowledge about video file formats and codecs.

Can someone help me with this?

I am using:

Python 3.7, OS: Windows, environment: conda, OpenCV v4.5.0

1 Answers

If you recieved ret as False it means that video reach end frame. If video isn't finished but you recieved False, it probably broken.

Try this code:

import cv2

input_video_path = './Input Video/Input_video1.mp4'

cap = cv2.VideoCapture(input_video_path)

while(cap.isOpened()):
    ret, frame = cap.read()
    print(frame, ret)
    if ret:
        cv2.imshow("frame", frame)
        cv2.waitKey(1)
    else:
        break

cap.release()
cv2.destroyAllWindows()
Related