0

I am going thru the tutorials to learn OpenCV. And I have a problem. When I run this code:

import cv2
cap = cv2.VideoCapture('C:\Users\wg\174037210.avi')
while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow('Video', frame)
    if cv2.waitKey(75) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

which is plain vanilla video display code I get this error after the video finishes:

Traceback (most recent call last): File "C:/Users/wg/python/video-test.py", line 15, in cv2.imshow('Video', frame) cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

The environment is as follows:
Windows 7 Professional
Python 3.6.5
OpenCV 3.4.3

Any help is greatly appreciated. Thanks!

gameon67
  • 3,981
  • 5
  • 35
  • 61
W Busse
  • 3
  • 1
  • 4

1 Answers1

1

Give this one a shot:

import cv2

video = cv2.VideoCapture(filePath)   
frames_counter = 1

while True:
    frames_counter = frames_counter + 1
    check, frame = video.read()
    # print(frame)
    # print(check)
    if check:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow("Capturing", gray)
        key = cv2.waitKey(1)
    else:
        break

print("Number of frames in the video: ", frames_counter)
video.release()
cv2.destroyAllWindows()
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • Great! Your code worked. Why did the example code not work and your code worked? It appears that you check to see if a frame contains data otherwise it will stop. If that is needed why does the tutorial sample code omit this check and error handling – W Busse Jan 09 '19 at 06:34
  • @WBusse Perfect! well. I don't know which tute you followed but it made more sense to me to check the frame first and only display if it does. You may mark the answer to accept the answer, cheers! – DirtyBit Jan 09 '19 at 06:42
  • 1
    `if check == True:` can just be `if check:`. The sample code crashed because by the end of the video, `frame` is `None` cannot be displayed by `imshow` as stated in the assertion error – Quang Hoang Jan 09 '19 at 06:51
  • @QuangHoang noted and fixed! :) – DirtyBit Jan 09 '19 at 06:53