Error while trying to save webcam picture with OpenCV - python

import cv
capture = cv.CaptureFromCAM(0)
img = cv.QueryFrame(capture)
cv.SaveImage("test.JPG", img)
Hi,
I just want to save a picture from my webcam with OpenCv and Python on my Ubuntu 10.
OpenCv can connect with the webcam.
But I get this error:
OpenCV Error: Null pointer (NULL array pointer is passed) in cvGetMat, file /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp, line 2376
Traceback (most recent call last):
File "video.py", line 5, in <module>
cv.SaveImage("test.JPG", img)
cv.error: NULL array pointer is passed

Save yourself a trip to the emergency room and use SimpleCV. It's a Pythonic wrapper for OpenCV's Python bindings and a few more tools (it uses Numpy, Scipy and PIL):
from SimpleCV import *
camera = Camera()
image = camera.getImage()
image.save('test.JPG')

I see this mistake over and over and over and over again: the CaptureFromCAM() call is failing, which means that QueryFrame() is failing as a consequence and returning NULL as image, causing SaveImage() to fail as well.
Two things that you need to take into consideration here:
1) your webcam might not be index 0 (try -1, or 1)
2) learn to code safely! Always check the return of the functions that are being called. This practice will save you a lot of time in the future:
capture = cv.CaptureFromCAM(0)
if not capture:
// deal with error, return, print a msg or something else.
img = cv.QueryFrame(capture)
if not img:
// deal with error again, return, print a msg or something else entirely.
cv.SaveImage("test.JPG", img)

Related

cv2.cuda_CascadeClassifier in python

I am attempting to use the Haarclassifier from opencv cuda, for this I found the object cv.cuda_CascadeClassifier. However, assigning cv.cuda_CascadeClassifier() to a variable spit the following error:
this object has no ''load'' attribute. I could successfully verify it
by printing their dir() print(dir(cv.cuda_CascadeClassifier)).
Is there any other way to call this object or did anyone effectively exploite the cascadeclassifier with opencv cuda?
thx
The lack of documentation for the python API really is a pain. Speaking about the version 4.5 of OpenCV, you have to call the create method when reading a xml cascade file or it'll yield segmentation fault when trying to detect. In my experience you'll also need to convert to gray scale or it will yield (-215:Assertion failed) src.type() == CV_8UC1.
Here's my working code on OpenCV 4.5.1:
import cv2
img = cv2.imread('./img_sample.jpg')
cascade = cv2.cuda_CascadeClassifier.create('./cascade_file.xml')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cuFrame = cv2.cuda_GpuMat(gray_img)
result = cascade.detectMultiScale(cuFrame).download() # download() gets the result as UMat
if result is not None:
print(result[0])
I hope this answers your question about the cuda version usage.
This is most likely due to the use of a version of openCV between 4.0.0 and 4.3.0, In those versions cuda_CascadeClassifier was disabled. In 4.4.0 This functionallity was brought back. (https://github.com/opencv/opencv_contrib/pull/2554/files)
Even though this seems to work fine in C++ it gives me a segmentation fault using the python wrapper using the following code:
classifier_cuda = cv2.cuda_CascadeClassifier('cascades_file.xml')
while True:
success, frame = vidcap.read()
cuFrame = cv2.cuda_GpuMat(frame)
result = classifier_cuda.detectMultiScale(cuFrame)
print (result)
Any solutions?
As already Breno Alef wrote, the problem of OpenCV for Python is the lack of documentation and also of some code examples, which makes difficult to understand how to write correctly Python code to use OpenCV.
Looking at the documentation of the cuda_CascadeClassifier or using the Python built-in function help() you can see that the cuda_CascadeClassifier is a subclass of cv.Algorithm, which contains the load() method, but the problem is the way cuda_CascadeClassifier works is a bit different from the Cascade class declared in opencv2/objdetect.hpp.

Using keys to toggle functions in OpenCV- Python

I am running into thread error :
QObject::moveToThread: Current thread (0x7c2d90) is not the object's thread (0xcc44d0).
Cannot move to target thread (0x7c2d90)
while trying to run the below program. when i take off the last two lines, it doesn't give me this error. Can anybody tell why this is happening?
import sys
import cv2
fileName = sys.argv[1]
print "image read from commandline"
img = cv2.imread(fileName)
print "image sucessfully read"
image = cv2.imread('testimage1.jpg', 0)
cv2.imshow('image', image )
cv2.waitKey(0)
I was using Anaconda package , now i switched to python 2.7 distribution and the error is gone.

What is the correct way to call this OpenCV function from Python?

I would like to use the selective search algorithm to segment images into possible object locations. I found that the library I already use for computer vision, OpenCV, implements this functionality as shown in the documentation here. However, I'm using Python and not C++, so I looked through OpenCV's github repositories until I found the example that I reproduced below.
#!/usr/bin/env python
'''
A program demonstrating the use and capabilities of a particular image segmentation algorithm described
in Jasper R. R. Uijlings, Koen E. A. van de Sande, Theo Gevers, Arnold W. M. Smeulders:
"Selective Search for Object Recognition"
International Journal of Computer Vision, Volume 104 (2), page 154-171, 2013
Usage:
./selectivesearchsegmentation_demo.py input_image (single|fast|quality)
Use "a" to display less rects, 'd' to display more rects, "q" to quit.
'''
import cv2
import sys
if __name__ == '__main__':
img = cv2.imread(sys.argv[1])
cv2.setUseOptimized(True)
cv2.setNumThreads(8)
gs = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()
gs.setBaseImage(img)
if (sys.argv[2][0] == 's'):
gs.switchToSingleStrategy()
elif (sys.argv[2][0] == 'f'):
gs.switchToSelectiveSearchFast()
elif (sys.argv[2][0] == 'q'):
gs.switchToSelectiveSearchQuality()
else:
print(__doc__)
sys.exit(1)
rects = gs.process()
nb_rects = 10
while True:
wimg = img.copy()
for i in range(len(rects)):
if (i < nb_rects):
x, y, w, h = rects[i]
cv2.rectangle(wimg, (x, y), (x+w, y+h), (0, 255, 0), 1, cv2.LINE_AA)
cv2.imshow("Output", wimg);
c = cv2.waitKey()
if (c == 100):
nb_rects += 10
elif (c == 97 and nb_rects > 10):
nb_rects -= 10
elif (c == 113):
break
cv2.destroyAllWindows()
Unfortunately, running this program with the command python selective_search.py "/home/christopher/DroneKit/Vision/Face Detection/Annotated Faces in the Wild/originalPics/2002/07/19/big/img_135.jpg" f gives me the following error:
Traceback (most recent call last):
File "selective_search.py", line 37, in <module>
rects = gs.process()
TypeError: Required argument 'rects' (pos 1) not found
Based upon that error message, I figured maybe I could just pass it a Python list and then the underlying C++ function would fill it with the algorithm's output. However, when I excecuted the following code:
rects = []
gs.process(rects)
print(rects)
The output was an empty list, and the image was displayed with no rectangles drawn on it. Therefore, I am at a loss on how I should call gs.process(). If it helps, the C++ declaration of the function is
CV_WRAP virtual void process(CV_OUT std::vector<Rect>& rects) = 0;
(Edit) Additional information copied from the comments:
Output from help(gs.process):
process(...) method of cv2.ximgproc_segmentation_SelectiveSearchSegmentation instance process(rects) -> None. rects = gs.process(rects) just makes rects None and causes the program to terminate with an exception
Using rects = gs.process(rects) sets rects to None and causes the program to terminate with an exception.
OpenCV version is 3.2.0.
Using a numpy array instead of a python list crashes my program with the following message:
OpenCV Error: Assertion failed (channels() == CV_MAT_CN(dtype)) in copyTo, file /home/christopher/opencv/modules/core/src/copy.cpp, line 259
terminate called after throwing an instance of 'cv::Exception'
what(): /home/christopher/opencv/modules/core/src/copy.cpp:259: error: (-215) channels() == CV_MAT_CN(dtype) in function copyTo
Aborted (core dumped)
Apparently, the version of OpenCV 3.2.0 that I compiled for Python was missing this fix locally. I went ahead and recompiled my python bindings using the latest stable release of OpenCV 3.3.0 and the latest changes to the OpenCV contrib repository and the sample script worked as expected after that.

Python OpenCV chamerMatching function reference

I have searched everywhere and I find it truly amazing that there is no reference on the chamerMatching function, especially in Python. Someone else also had the same problem with no answer:
I don't really want to know about the algorithm - I know how the algorithm works - I want to know how to call it in Python and retrieve the costs, results and bestfit. I have tried the following code.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
frame = cv2.GaussianBlur(frame, (13, 13), 0)
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
frame = cv2.adaptiveThreshold(frame,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
templ = cv2.imread("template.png",cv2.CV_LOAD_IMAGE_GRAYSCALE)
cannyframe = cv2.Canny(frame,5,50,apertureSize=3)
cannytempl = cv2.Canny(templ,5,50,apertureSize=3)
cv2.imshow("cannyframe",cannyframe)
cv2.imshow("cannytempl", cannytempl)
cv2.waitKey(0)
#The line below, and NOT any other line, crashes the program
cv2.chamerMatching(cannytempl,cannyframe)
All of it runs fine except the final call to the chamerMatching function which causes the python interpreter to crash and stop working for some reason with a message that looks like this:
With absolutely zero documentation on the function, I can't figure out why.
EDIT:
The code above now includes all the required lines to run and below is template.png.
i don't know if you still need this information. But I also needed chamfer matching for my research. And here's what I found after encountering the same dilemma as you've had.
http://code.opencv.org/issues/3602
:)

OpenCV Error: Bad argument (Array should be CvMat or IplImage) file C:\slave\WinInstallerMegaPack\src\opencv\modules\core\src\array.cpp, line 1238

Just installed SimpleCV Version 1.3 Superpack (Python 2.7) and trying the Hello Word application from Practical Computer Vision with SimpleCV
from SimpleCV import Camera, Display, Image
import time
# Initialize the camera
cam = Camera()
# Initialize the display
display = Display()
# Snap a picture using the camera
img = cam.getImage()
On the last line it fails with
OpenCV Error: Bad argument (Array should be CvMat or IplImage) in unknown function, file C:\slave\WinInstallerMegaPack\src\opencv\modules\core\src\array.cpp, line 1238
---------------------------------------------------------------------------
error Traceback (most recent call last)
C:\Python27\lib\site-packages\SimpleCV\Shell\Shell.pyc in <module>()
----> 1 img = cam.getImage()
C:\Python27\lib\site-packages\SimpleCV\Camera.pyc in getImage(self)
584
585 frame = cv.RetrieveFrame(self.capture)
--> 586 newimg = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 3)
587 cv.Copy(frame, newimg)
588 return Image(newimg, self)
error: Array should be CvMat or IplImage
I am using the PS3 Eye camera via the CL-Eye Driver on a Windows 7 PC. That is via usb. The camera works fine otherwise. Any ideas how I can fix this?
cv.CreateImage wants an image or an array. I guess your cv.GetSize(frame) is not returning an array (you ought to check exactly why that is).
You might also try
newimg = cv.CreateImage(frame, cv.IPL_DEPTH_8U, 3)
where frame should be an IplImage according to the documentation.
http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-retrieve
But check that RetrieveFrame isn't failing for some reason. For example, there are reports of camera access being denied for conflicts with Skype videochat functions. Are you running some software that might conceivably access the camera?
You can try downloading Process Explorer, and check (Find > Handle or DLL) if there's any process with a handle containing the string 'DeviceClasses'.
UPDATE: my bad, this section only applies to PCI cards and PSEye is USB {
As a desperate measure you can take a snapshot with System Restore, and install FGeng's Universal Video Support driver for Windows 7. Then check whether OpenCV recognizes it as a camera connector.
http://www.fgeng.com/drivers.htm
If it doesn't, you can wipe it out with System Restore. It is a desperate measure because anything hogging the camera would probably hog the WDM too, and so chances for success are slim, but you never know.
}
UPDATE: did a little bit of research. It turns out that the CL-Eye driver for PSEye is not without problems, depending on the application accessing it. The newer drivers have solved some problems ( threads of February 2012, maybe obsolete ). Sometimes, camera licensing may be an issue ( http://nuigroup.com/forums/viewthread/13699/ ).
You might try with the CL-Eye SDK instead of the driver, since the former explicitly lists OpenCV in the platforms, while the latter does not.
If you already have installed the SDK, you may want to check the camera number (#0, #1) just in case there's another imaging peripheral registered in the system.
Another possibility is to run DxDiag utility to diagnose a possible DirectShow snag.
Trouble here is that there's not much information to be had from the system.
You might want to copy "C:\Python27\lib\site-packages\SimpleCV\Camera.py" into a backup file, and modify it to be more informative, e.g. temporarily adding a print frame between lines 585 and 586 (N.B.: the line must be indented exactly as the one above).
There is no problem with SimpleCV. Your camera must be having some issues. Try to re-install OpenCV. Install the latest version of OpenCV(OpenCV 2.4.2)
To see if your camera works with OpenCV,
import cv2
c = VideoCapture(0)
val, img = c.read()
print val #this should be True
print img #this should not be all 0s

Categories