Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read video files using python & Opencv

Tags:

python

opencv

I am reading an avi file usinh python 2.7 and opencv2.4.I am using windows 10.My sample code is

import numpy as np
import cv2
cap = cv2.VideoCapture('videos/wa.avi')
while(cap.isOpened()):
  ret, frame = cap.read()
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  cv2.imshow('frame',gray)
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break

cap.release()
cv2.destroyAllWindows()

When i run video is shown But the program ends with no Error

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow, file ..\..\..\..\opencv\modules\highgui\src\window.cpp, line 261
Traceback (most recent call last):
File "C:/Users/Emmanu/PycharmProjects/VideoEventDetection/test.py", line 11, in <module>
cv2.imshow('frame',frame)
cv2.error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow

What i am doing wrong?How can i correct it?

like image 240
Emmanu Avatar asked Jan 03 '17 10:01

Emmanu


People also ask

What video formats can OpenCV read?

The MPEG format 480p version is more than enough to demonstrate the basic capabilities of OpenCV's video processing. Note that OpenCV supports reading and writing several popular formats (such as AVI and MPEG).


2 Answers

The problem is in this line:

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

This line expects frame to be a 3 channel or 4 channel Mat object but instead it got some empty Mat and that is why you are getting this assertion failed. You need to check if the frame exists in video and need to handle end of video properly.

cap.isOpened() will just check if the video file can be opened for reading but it will not return a false when end of video file is reached.

Try this

like image 109
abggcv Avatar answered Sep 29 '22 20:09

abggcv


When you put cap.isOpened() it check that, the video is read properly, So the while loop is not working there.

But when you changed to while True it will execute without proper reading that's why it's giving an error.

Make sure than you are properly reading the video file.

like image 39
Rahul K P Avatar answered Sep 29 '22 19:09

Rahul K P