OpenCV Python Assertion Failed - python

I am trying to run opencv-python==3.3.0.10 on a macOS 10.12.6 to read from a file and show the video in a window. I have exactly copied the code from here http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html, section 'Playing' video from file.
The code runs correctly and shows the video, however after termination of the video it breaks the program, giving the following error:
Assertion failed: (ec == 0), function unlock, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/libcxx/libcxx-307.5/src/mutex.cpp, line 48.
Does anyone have any idea of what might cause this?
Code snippet for your convenience (edited to include some suggestions in the comment)
cap = cv2.VideoCapture('vtest.avi')
while(True):
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()

It's not clear from your question, but it looks like you're specifically running into a situation where the video completes playing without being interrupted. I think the issue is that the VideoCapture object is already closed by the time you get to cap.release(). I'd recommend putting the call to release inside of the if statement by the break.
I've not had time to experiment, but I normally follow this pattern:
reader = cv2.VideoCapture(<stuff>)
while True:
success, frame = reader.read()
if not success:
break
I'd not had to call release explicitly in those contexts.

Related

won't play video or give error

When I try to open and play a video, the code runs and finishes in 0.2 seconds, without any errors or playing the actual video. The code finishes without doing anything.
import numpy as np
import cv2
cap = cv2.VideoCapture(r'C:\Users\Hayden\Desktop\test.mp4')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(30) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The only recommendation I've seen for this is to change the waitKey parameter to 1, but that doesn't make a difference right now.
I appreciate any and all help!
I would recommend you use os.startfile.
You have to import os then say I had a file in a directory path C:\Users\me\Videos
Then I would do,
os.startfile('C:\Users\me\Videos'). This is if you are on Windows, if you are not,
don't include the 'C:\' in that. If you get a unicode error in the path, use double backslashes.
os.startfile('C:\\Users\\me\\Videos')

Assertion failure : size.width>0 && size.height>0 in function imshow

i am using opencv2 and python on raspberry pi. and i am new with python and opencv. i tried to read a jpeg image and display image it shows the following error:
/home/pi/opencv-2.4.9/modules/highgui/src/window.cpp:269: \
error: (-215) size.width>0 && size.height>0 in function imshow.
and the code is:
import cv2
# windows to display image
cv2.namedWindow("Image")
# read image
image = cv2.imread('home/pi/bibek/book/test_set/bbb.jpeg')
# show image
cv2.imshow("Image", image)
# exit at closing of window
cv2.waitKey(0)
cv2.destroyAllWindows()
The image fails to load (probably because you forgot the leading / in the path). imread then returns None. Passing None to imshow causes it to try to create a window of size 0x0, which fails.
The poor error handling in cv probably owes to its quite thin wrapper layer on the C++ implementation (where returning NULL on error is a common practice).
it's the path which is causing the problem, i had the same problem but when i gave the full path of the image it was working perfectly.
While using Raspbian in Rpi 3 I had the same problem when trying to read qrcodes. The error is because cv2 was not able to read the image. If using png image install pypng module.
sudo pip install pypng
Use r in the code where you specified the file address.
For Example:
import cv2
img = cv2.imread(r'D:\Study\Git\OpenCV\resources\lena.png')
cv2.imshow('output', img)
cv2.waitKey(0)
r stands for "raw" and will cause backslashes in the string to be interpreted as actual backslashes rather than special characters.
In my case, I had forgotten to change the working directory of my terminal to that of my code+testImage. Hence, it failed to find the image there.
Finally, this is what worked for me:
I saved the image and Python file on Desktop. I changed my cmd directory to it,
cd Desktop
And then checked for my file:
ls
And this was my code that worked:
import cv2
import numpy as np
im = cv2.imread('unnamed.jpg')
#Display the image
cv2.imshow('im',im)
cv2.waitKey(2000) #Milliseconds
I am also getting a similar error, so instead of opening a new question, I thought maybe it would be a good idea to gather it all here since there's already some helpful answers...
My code (textbook code to open a video using OpenCV in Python):
import cv2 as cv
import os
path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
os.chdir(path)
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file)
if not cap.isOpened():
print("Error opening Video File.")
while True:
# Capture frame-by-frame
ret, frame = cap.read()
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly, ret is True
if not ret:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
The reason why I am dumbfounded is that I am getting the same error - BUT - the video is actually played... When running the code the Python interpreter opens up an instance of Python running the video. Once the video ends, it breaks out of the loop, closes the video and throws the error:
Traceback (most recent call last):
File "C:/Users/username/Documents/smile-main/video-testing.py", line 24, in
cv.imshow('frame',frame)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wwma2wne\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
I'd appreciate any input!
**
EDIT: How I fixed my error!
**
I encased my code in a try/except like this:
# Import required libraries
import cv2 as cv
import os
path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
# test_path = 'C:/Users/username/Downloads'
os.chdir(path)
os.getcwd()
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file) #cap for "Video Capture Object"
if not cap.isOpened():
print("Error opening Video File.")
try:
while True:
# Capture frame-by-frame
ret, frame = cap.read()
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# if frame is read correctly, ret is True
if not ret:
print("Can't retrieve frame - stream may have ended. Exiting..")
break
except:
print("Video has ended.")
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()
I'd still appreciate any input on why this error popped up even though the video played fine, and why the try/except eliminated it.
Thank you!
One of the reasons, this error is caused is when there is no file at the path specified. So, a good practice will be to verify the path like this ( If you are on a linux based machine ):
ls <path-provided-in-imread-function>
You will get an error if the path is incorrect or the file is missing.
While reading the image file, specifying the color option should solve this,
for example:
image=cv2.imread('img.jpg',cv2.IMREAD_COLOR)
adding the cv2.IMREAD_COLOR should solve this
This problem happened to me when i just failed to write the extension of the image.
Please check if you forgot to write the extension or any other part of the full path to the image.
Remember, extension is required whether you are printing image using OpenCV or Mathplotlib.
I solve it by using this code
os.chdir(f"{folder_path}")
It is because the image is not loaded. For me at VScode the relative path was problem but after copying the file path from VSCode itself the problem was solved.
I had the same problem too, on VSCode. Tried running the same code on Notepad++ and it worked. To fix this issue on VSCode, don't forget to open the folder that you're working in on the left pane. This solved my issue.

OpenCV: Face detection taking advantage of a command line

I run this (first one) example that launches the webcam of my latop so that I can see myself on the screen.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I installed OpenBr on Ubuntu 14.04 LTS and I run successfully this command on a picture of myself:
br - gui -algorithm ShowFaceDetection -enrollAll -enroll /home/nakkini/Desktop/myself.png
The above command I run on the Terminal displays my picture and draws a square around my face (face detection), it also highlights my eyes in green.
My Dream:
I wonder if there is a way to combine this command with the short program above so that when the webcam is launched I can see my face surrounded by the green rectangle ?
Why do I need this ?
I found similar programs in pure OpenCV/Python for this purpos. However, for later needs, I need more things than the simple face detection and I judge by myself that OpenBR will save me lot of headache. That is why I am looking for a way to run the command line somewhere inside the code above as a first but big step.
Hints:
The frame in the code corresponds to myself.png of the command line. The solution to be found will try to pass frame in the place of myself.png to the command line within the program itself.
Thank you very much in advance.
EDIT:
After correcting the typos of #Xavier's solution I have no errors. However the program does not run as I want it:
First, the camer is launched and I see myself but my face is not detected with a green rectangle. Secondly, I press any key to exit but the program does not exit: it shows me a picture of myself with my face detected. A last key press exists the program. My goal is to see my face detected during the camera functionment.
you do not need openbr for this at all.
just see opencv's python face-detect tutorial
something like this should work
import numpy as np
import cv2
import os
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.imwrite( "/home/nakkini/Desktop/myself.png", gray );
os.system('br - gui -algorithm -ShowFaceDetection -enrollAll -enroll /home/nakkini/Desktop/myself.png')
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Why does the examples from the introductory OpenCV video tutorial throw errors and what is the preferred work around?

When testing the video playback example from the OpenCV introductory video tutorial, my videos (.m4v and .mov) always freeze for a little bit after they are done and then throws this error message:
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-33-6ff11ed068b5> in <module>()
15
16 # Our operations on the frame come here
---> 17 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
18
19 # Display the resulting frame
error: /home/user/opencv-2.4.9/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor
My interpretation is that this is because the last frame will be empty and lack the channels that cvtColor() expects and the image can therefore not be displayed. If I modify the example code slightly and replace the while(True) with a for loop that ends after the last frame in the video, I get no such message and the video window closes instead of freezing.
However, I assume there is a reason to why this is not the default behaviour in OpenCV and I'm afraid my modification will screw something up further down the road (completely new to OpenCV). So now I would like input on a few things:
Why is the while(True) the default for showing the video, since it is freezing and throwing an error message (if this is not unique to my setup)?
Is it safe to have the for loop or should I stick to while(True) and wait for the error message every time I play a video?
Is there a preferred way to have OpenCV exit video playback gracefully?
I have tried the suggestions here and they did help with not freezing up the kernel completely, but the video still freezes and the error message still shows. The for loop alternative seems smoother.
I'm using the Ipython Notebook with Python 2.7.9 and OpenCV 2.4.9 on Ubuntu 14.04. Below is the code I'm executing.
import cv2
video_name = '/path/to/video'
cap = cv2.VideoCapture(video_name)
# while(True): #causes freeze and throws error
for num in range(0,int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Since I ended up wanting to loop the video at some occasions, the following proved to be the best solution for me.
import numpy as np
import cv2
cap = cv2.VideoCapture('/path/to/vid.mp4')
frame_counter = 0
loop = True
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
frame_counter += 1
if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
if loop == True:
frame_counter = 0
cap = cv2.VideoCapture(video_name)
else:
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
If you don't need to loop you videos just use
if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
break
or Padraic's solution (slightly modified)
try:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
except cv2.error:
break
The try/except statement does give a short delay where the video freezes before closing. The if statement closes it immediately when playback is finished.
I am still interested if someone can explain while the error message is encountered in the first place since padraic said this is not the case on his machine.
EDIT: So I noticed I misread the tutorial and should use while(cap.isOpened()) instead of while(True), but I still get the same error with while(cap.isOpened()).

Grabbing Analog video into python using opencv

Well, it seems like my question had been asked many times before and unfortunately, no one replied. I hope someone will help.
I have an Easycap device that converts the analog images from my analog camera to digital signals through a USB port.
The device is identified to the system in the Device Manager under "Sound, Video and game controllers" category as "SMI Grabber Device".
I use a simple Python code to display the video from this device. I also have an embedded webcam in my laptop.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if cv2.waitKey(1) & 0xFF == ord('s'):
cv2.imwrite('screenshot.jpg',frame)
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
First, when I unplug the Easycap, CaptureVideo(0) returns the embedded webcam video stream. However, when I plug the Easycap, an error appears:
"Traceback (most recent call last):
File "C:\Users\DELL\Desktop\code\cam.py", line 10, in
cv2.imshow('frame',frame)
error: ......\src\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0"
Notice that, any number except 0 makes the program display the webcam image. So if I tried cap = cv2.CaptureVideo(1), it will show the webcam, cap = cv2.CaptureVideo(20) is the same.
I also tried to enter "SMI Grabber Device" instead of 0 or 1 in the VideoCaptureconstructor function, but it didn't make any difference.
I'm using Windows 8, and I've installed the accompanying driver for Easycap. The software that comes with the driver (called ULead) works fine and display the CCTV camera video. I tried to display the images while I'm closing that program, and without, the result is the same.
I used before a C# program with Aforge library which had getCamList method or something which allowed me to choose the specific device I want to display from a comboBox. I can't find a similar function is opencv.
I'm using OpenCV 2.4.6. I didn't try the code on prior versions.
I really need to understand why this code doesn't work, knowing that I'm just a very beginner of opencv and image processing.
I hope someone can help.
I am using EasyCAP too.
You must check that ret is True.
I am use below code
while True:
ret, frame = vc.read()
if ret:
break
cv2.waitKey(10)
h, w = frame.shape[:2]
print h, w
while True:
ret, frame = vc.read()
if ret:
cv2.imshow(WID, frame)
if cv2.waitKey(1) == 27:
break
Let there be light!
On serious note, I struggled with the same problem and I hope this helps!
the original thread + answer

Categories