Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a video in opencv(python)

Tags:

python

opencv

I am a begginer in OpenCV and Python. I tried to load a video and displaying it using code given below:

import cv2
cap = cv2.VideoCapture('G:\3d scanner\2.mmv')
while(1):
    _ , img2=cap.read()
    cv2.namedWindow('video',cv2.WINDOW_NORMAL)
    cv2.imshow('video',img2)            
    k=cv2.waitKey(1) & 0xFF
    if k==27:
        break
cap.release()
cv2.destroyAllWindows()

But it showing the following error:

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow, file ..\..\..\..\opencv\modules\highgui\src\window.cpp, line 261
File "test3.py", line 8, in <module>
cv2.imshow('video',img2)
cv2.error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow

There are previous questions on this site regarding this issue but the answers given were using cv library but not cv2.

Any idea of what is wrong in this?

like image 282
MANDY Avatar asked Apr 09 '16 19:04

MANDY


2 Answers

This might help you:

import numpy as np
import cv2

cap = cv2.VideoCapture('linusi.mp4')

while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

If it doesn't work, there are a lot of useful explanations in their documentation: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html

like image 172
Lum Ramabaja Avatar answered Sep 18 '22 02:09

Lum Ramabaja


There are a couple important differences when using VideoCapture on a video file. First off, there's no built in frame delays like when you're capturing from a webcam. Since most computers are very powerful these days, unless you deliberately introduce a delay between frames, the video will be displayed in a blink of an eye.

Secondly, the video has an end unlike input from your webcam, so you need to explicitly handle that case. I suspect what's happening in your case is that the video is completing in a matter of milliseconds, and then the final cap.read() is returning an empty matrix which imshow() subsequently complains about.

See Opening video with openCV +python. One of the answers in there is directly applicable to your situation.

like image 35
Aenimated1 Avatar answered Sep 20 '22 02:09

Aenimated1