Cannot load the camera for the second time in OpenCV Python - python

I am developing a simple program which loads an external camera through USB connection. When I run the program for the first time, it loads the camera and executes the rest of the code successfully. But if I stop the execution and try to re-run the program, it doesn't load the camera. Yet, if I remove the USB cable and plug it again, the program runs perfectly (The error still occurs if I re-run the program)
Below is my implementation,
import cv2 as cv
import pytesseract
import imutils
capture = cv.VideoCapture(0)
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
temperature = 0
tot = 0
for i in range(10):
_, frame = capture.read()
frame = imutils.resize(image=frame, width=500)
frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
frame_gray = frame_gray[:50, :88]
cv.imshow('frame', frame)
try:
temperature = float(pytesseract.image_to_string(frame_gray))
tot = tot + temperature
except ValueError:
print('except')
cv.imshow('Frame', frame_gray)
if cv.waitKey(20) & 0xFF == ord('q'):
break
print(tot / 10)
capture.release()
cv.destroyAllWindows()
And below is the generated error when I run the program for the second time
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-5rb_9df3\opencv\modules\videoio\src\cap_msmf.cpp (372) `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -2147023901
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-5rb_9df3\opencv\modules\videoio\src\cap_msmf.cpp (384) `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -2147023901
[ WARN:1] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-5rb_9df3\opencv\modules\videoio\src\cap_msmf.cpp (912) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147023901
Traceback (most recent call last):
File "D:\Studies\OpenCV\Lab07\Lab.py", line 15, in <module>
frame = imutils.resize(image=frame, width=500)
File "C:\Python39\lib\site-packages\imutils\convenience.py", line 69, in resize
(h, w) = image.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'
[ WARN:1] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-5rb_9df3\opencv\modules\videoio\src\cap_msmf.cpp (434) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
So basically I have to plug out and plug in the USB cable in order to re-run the program. How can I solve this issue? Thanks in advance!

in first time try to use the method cv.VideoCapture.open and check that it returns True or in the same principle use cv.VideoCapture.isOpened
using open() method call release() before opening a new device
capture = cv.VideoCapture()
capture.open(0)
if not capture.IsOpened() :
...
...
capture.release()
warning be sure to call release() before exit the script
the problem can also come from your camera, check with another one

Related

How to capture video with an external camera using opencv

I'm trying to capture a video from my pixy2 camera.
I wrote this code:
import cv2 as cv
vid = cv.VideoCapture(1, cv.CAP_DSHOW)
while (True):
ret, frame = vid.read()
cv.imshow('frame', frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
vid.release()
cv.destroyAllWindows()
and I'm getting this error:
"C:\Users\User\PycharmProjects\OpenCV tutorial\venv\Scripts\python.exe" "C:/Users/User/PycharmProjects/OpenCV tutorial/OpenCV_1.py"
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\OpenCV tutorial\OpenCV_1.py", line 14, in <module>
cv.imshow('frame', frame)
cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-sn_xpupm\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
Process finished with exit code 1
Any help, please!!
actually this error doesn't base on your videocapture operation. -As properly u set the capture parameter as 1 -
Here are two tips that will you help to determine the reason behind this error;
First use this line right after vid = cv.VideoCapture(1, cv.CAP_DSHOW) this line on your code:
vid not cap.isOpened(): print("Cannot open camera") exit()
This code helps you to understand whether your external camera is on or off.
The second tip is about the reading stage.
if not ret: print("Can't receive frame (stream end?). Exiting ...") break
You will get the error at 1.st step or 2.nd step then, yes!
By the way Welcome :)

Opencv "select timeout" error with camera_capture on vm Ubuntu 16.04

I am using Ubuntu 16.04 on vm player. I have written a script to connect laptop's webcam. But, I got select timeout error with ret, frame = video_capture.read(), although I selected camera from "removable devices" section.
When I tried to run script on windows, it was successful.
code: read_video.py
import numpy as np
import cv2
video_capture = cv2.VideoCapture(0)
while(True):
ret, frame = video_capture.read()
cv2.imshow("Frame",frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
error:
read_video.py
select timeout
select timeout
OpenCV Error: Assertion failed (total() == 0 || data != __null) in Mat, file /tmp/binarydeb/ros-kinetic-opencv3-3.3.1/modules/core/include/opencv2/core/mat.inl.hpp, line 500
Traceback (most recent call last):
File "read_video.py", line 9, in <module>
ret, frame = video_capture.read()
cv2.error: /tmp/binarydeb/ros-kinetic-opencv3-3.3.1/modules/core/include/opencv2/core/mat.inl.hpp:500: error: (-215) total() == 0 || data != __null in function Mat
How can I solve it?

How to correctly check if a camera is available?

I am using OpenCV to open and read from several webcams. It all works fine, but I cannot seem to find a way to know if a camera is available.
I tried this code (cam 2 does not exist):
import cv2
try:
c = cv2.VideoCapture(2)
except:
print "Cam 2 is invalid."
But this just prints a lot of errors:
VIDEOIO ERROR: V4L: index 2 is not correct!
failed to open /usr/lib64/dri/hybrid_drv_video.so
Failed to wrapper hybrid_drv_video.so
failed to open /usr/lib64/dri/hybrid_drv_video.so
Failed to wrapper hybrid_drv_video.so
GStreamer Plugin: Embedded video playback halted; module v4l2src0 reported: Internal data stream error.
OpenCV Error: Unspecified error (GStreamer: unable to start pipeline
) in cvCaptureFromCAM_GStreamer, file /builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_gstreamer.cpp, line 832
VIDEOIO(cvCreateCapture_GStreamer(CV_CAP_GSTREAMER_V4L2, reinterpret_cast<char *>(index))): raised OpenCV exception:
/builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_gstreamer.cpp:832: error: (-2) GStreamer: unable to start pipeline
in function cvCaptureFromCAM_GStreamer
OpenCV Error: Unspecified error (unicap: failed to get info for device
) in CvCapture_Unicap::initDevice, file /builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_unicap.cpp, line 139
VIDEOIO(cvCreateCameraCapture_Unicap(index)): raised OpenCV exception:
/builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_unicap.cpp:139: error: (-2) unicap: failed to get info for device
in function CvCapture_Unicap::initDevice
CvCapture_OpenNI::CvCapture_OpenNI : Failed to enumerate production trees: Can't create any node of the requested type!
<VideoCapture 0x7fa5b5de0450>
No exception is thrown. When using c.read() later, I do get False, but I would like to do this in the initialisation phase of my program.
So, how do I find out how many valid cameras I have or check if a certain number 'maps' to a valid one?
Using cv2.VideoCapture( invalid device number ) does not throw exceptions. It constructs a <VideoCapture object> containing an invalid device - if you use it you get exceptions.
Test the constructed object for None and not isOpened() to weed out invalid ones.
For me this works (1 laptop camera device):
import cv2 as cv
def testDevice(source):
cap = cv.VideoCapture(source)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', source)
testDevice(0) # no printout
testDevice(1) # prints message
Output with 1:
Warning: unable to open video source: 1
Example from: https://github.com/opencv/opencv_contrib/blob/master/samples/python2/video.py
lines 159ff
cap = cv.VideoCapture(source)
if 'size' in params:
w, h = map(int, params['size'].split('x'))
cap.set(cv.CAP_PROP_FRAME_WIDTH, w)
cap.set(cv.CAP_PROP_FRAME_HEIGHT, h)
if cap is None or not cap.isOpened():
print 'Warning: unable to open video source: ', source
Another solution, which is available in Linux is to use the /dev/videoX device in the VideoCapture() call. The devices are there when the cam is plugged in. Together with glob(), it is trivial to get all the cameras:
import cv2, glob
for camera in glob.glob("/dev/video?"):
c = cv2.VideoCapture(camera)
Of course a check is needed on c using isOpened(), but you are sure you only scan the available cameras.
Here is a "NOT working" solution to help you prevent tumbling over in this pitfall:
import cv2 as cv
import PySpin
print (cv.__version__)
# provided by Patrick Artner as solution to be working for other cameras than
# those of Point Grey (FLIR).
def testDevice(source):
cap = cv.VideoCapture(source)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', source)
# ... PySpin / Spinnaker (wrapper/SDK libary) ...
system = PySpin.System.GetInstance()
cam_list = system.GetCameras()
cam = ''
cam_num = 0
for ID, cam in enumerate(cam_list):
# Retrieve TL device nodemap
if ID == cam_num:
print ('Got cam')
cam = cam
cam.Init()
# ... CV2 again ...
for i in range(10):
testDevice(i) # no printout
You can try this code:
from __future__ import print_function
import numpy as np
import cv2
# detect all connected webcams
valid_cams = []
for i in range(8):
cap = cv2.VideoCapture(i)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', i)
else:
valid_cams.append(i)
caps = []
for webcam in valid_cams:
caps.append(cv2.VideoCapture(webcam))
while True:
# Capture frame-by-frame
for webcam in valid_cams:
ret, frame = caps[webcam].read()
# Display the resulting frame
cv2.imshow('webcam'+str(webcam), frame)
k = cv2.waitKey(1)
if k == ord('q') or k == 27:
break
# When everything done, release the capture
for cap in caps:
cap.release()
cv2.destroyAllWindows()

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow

I am running the following code on Raspberry Pi with pi camera, I have the broadcom drivers for it and all, but I am getting an error. Perhaps something to do with the dimensions of the video feed, but I do not know how to set it on Linux.
Code:
import cv2
import numpy as np
cap = cv2.VideoCapture()
while True:
ret, img = cap.read()
cv2.imshow('img', img)
if cv2.waitKey(0) & 0xFF == ord('q):
break
Error:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow,
file /home/pi/opencv-3.3.0/modules/highgui/src/window.cpp, line 325
Traceback (most recent call last):
File "check_picam_with_opencv.py", line 10, in <module>
cv2.imshow('img', img)
cv2.error: /home/pi/opencv-3.3.0/modules/highgui/src/window.cpp:325: error:
(-215) size.width>0 && size.height>0 in function imshow
Provide an id to VideoCapture.
cap = cv2.VideoCapture(0)
Also check the value of ret, see if it's TRUE or FALSE
print (ret)
Edit:
To capture a video, you need to create a VideoCapture object. Its argument can be either the device index or the name of a video file. Device index is just the number to specify which camera.
cap = cv2.VideoCapture(0)
To check whether the cap has been initialized or not, you can use cap.isOpened() function, which returns True for successful initialization and False for failure.
if cap.isOpened() == False:
print ("VideoCapture failed")
cap.read() returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of the video by checking this return value.
ret, frame = cap.read()
if ret == False:
print("Frame is empty")
Further reading here.

attribute error: none type object has no shape

I can't run this script successfully.
I have tried running it via command line whilst passing arguments and without. I have also tried to run in a virtualenv to no avail. I suspect I am missing a driver for PiCamera to work
# if a video path was not supplied, grab the reference
# to the webcam
if not args.get("video", False):
camera = cv2.VideoCapture(0)
# otherwise, grab a reference to the video file
else:
camera = cv2.VideoCapture(args["video"])
# keep looping
while True:
# grab the current frame
(grabbed, frame) = camera.read()
The error:
Traceback (most recent call last):
File "/home/pi/ball-tracking/ball_tracking.py", line 48, in <module>
frame = imutils.resize(frame, width=600)
File "/usr/local/lib/python2.7/dist-packages/imutils/convenience.py"`enter code here`, line 45, in resize
(h, w) = image.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'
The 'nonetype' object referred to the frame that was not passed to the resize method.
This is solved by loading the pre-installed v4l2 drivers before running the code as such:
sudo modprobe bcm2835-v4l2

Categories