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.
Related
I am new to opencv and python and was learning the basics from the docs. I was learning about the trackbar in opencv (python).
I wrote the same code as shown in the docs here. (Note the version is 4.5.3)
Here's my code:
import numpy as np
import cv2 as cv
def nothing(x):
pass
# Create a black image, a window
img = np.zeros((300,512,3), np.uint8)
cv.namedWindow('image')
# create trackbars for color change
cv.createTrackbar('R','image',0,255,nothing)
cv.createTrackbar('G','image',0,255,nothing)
cv.createTrackbar('B','image',0,255,nothing)
# create switch for ON/OFF functionality
switch = '0 : OFF \n1 : ON'
cv.createTrackbar(switch, 'image',0,1,nothing)
while(1):
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
# get current positions of four trackbars
r = cv.getTrackbarPos('R','image')
g = cv.getTrackbarPos('G','image')
b = cv.getTrackbarPos('B','image')
s = cv.getTrackbarPos(switch,'image')
if s == 0:
img[:] = 0
else:
img[:] = [b,g,r]
cv.destroyAllWindows()
When I run this code, I get the following annoying long warning:
Using 'value' pointer is unsafe and deprecated. Use NULL as value pointer. To fetch trackbar value setup callback.
This is the full warning message if anyone wants to refer:
[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-q3d_8t8e\opencv\modules\highgui\src\window.cpp (704) cv::createTrackbar UI/Trackbar(R#image): Using 'value' pointer is unsafe and deprecated. Use NULL as value pointer. To fetch trackbar value setup callback.
I tried to understand what it is trying to say, but couldn't understand much. AFAIU, the error is in the line (and subsequent):
r = cv.getTrackbarPos('R','image')
Even thought it is a warning, I would like to get rid of it, as it uses the word unsafe and deprecated.
I have opencv-python of version 4.5.3.56. I've tried getting through the docs, but seems they are the same as for older versions, and this particular feature is deprecated in my version.
Can anyone suggest me what should be done to avoid this?
this bug in 4.5.3 is already reported and fixed (at least for python)
however, unless you rebuild it locally, you will have to wait for the next pypi release ;(
I am using deoplete-jedi to provide auto-completions inside Neovim. I found out that auto-completion does not work if I create an Image object instance using Image.open() method when using Pillow. But for Image instance created using Image.new() method, the auto-completion works correctly.
After a lot of debuging, I finally find out the reason. Because the Jedi package can not provide completions for Image instance created by Image.open() method.
The below code shows the differences:
import jedi
source1 = '''
from PIL import Image
im = Image.new('test.jpg', (128, 128))
im.
'''
script1 = jedi.Script(source1, 4, len('im.'), 'example1.py')
print(script1.completions())
source2 = '''
from PIL import Image
im = Image.open('test.jpg')
im.
'''
script2 = jedi.Script(source2, 4, len('im.'), 'example2.py')
print(script2.completions())
Since the two methods both return an Image object, I do not know why the auto-completion behaves differently.
Version info
Python: Python 3.6.8
jedi: 0.13.3
Pillow: 5.2.0
The problem typically is that things like Image.open() do things like caching, where it's pretty much impossible to infer the right type.
In this example (look at https://github.com/python-pillow/Pillow/blob/master/src/PIL/Image.py#L2690), Jedi tries to follow im -> _open_core(...) -> other im -> factory(...) -> factory seems like factory, accept = OPEN[i] -> but what is OPEN -> it's defined as an empty {}, and filled in register_open() or from the outside -> register_open is not called in the same file.
And that's where Jedi stops searching for solutions. So you can see it's not always possible to infer types. Even I'm not sure what the returned type will be and I tried to look at it for 10 minutes. The solution is usually stubs/type annotations for this.
I'm trying to use the built in opencv function TriangulatePoints for multiple views: https://docs.opencv.org/3.4.4/d0/dbd/group__triangulation.html#ga211c855276b3084f3bbd8b2d9161dc74.
Using python on linux, does anyone have experience using this function? The website only has the syntax for cpp and in python I don't know how to code it.
My code now:
import cv2
import numpy as np
point_2D = np.array([[17.4485, 709.7993], [17.4382, 709.8409]])
Proj_Matrices = np.array([ [1037.5, -6.9927, -10.0190, -4780.7], [6.9747, 1043.3, -5.8867, -731.9206], [644.7895, 383.4982, -3231.1], [1036.937, -22.8371, -28.3254, -5607.7], [23.0587, 1043.1, 3.1815, -633.4485], [650.4355, 373.6, -15.3504, -3706.5] ])
OutputArray = np.zeros((3,2))
Points_3D = cv2.sfm.triangulatePoints(point_2D, Proj_Matrices, OutputArray)
However, when I run it from the terminal I get the following error:
AttributeError: module 'cv2' has no attribute 'sfm.
I installed sfm on my computer using the instructions on the opencv site.
When I omit sfm I get the following error:
AttributeError: module 'cv2' has no attribute 'sfm'
I think I get that error since the machine thinks I'm trying to use the previous version of TriangulatePoints.
Examples of opencv code using sfm exist on the opencv website but they are in cpp.
I'm wondering what the syntax for using TriangulatePoints(with sfm) is in python? Even in cpp, I don't understand how the output array is an input to the function? Also, if anyone knows how to fix the sfm error I am receiving that would be appreciated.
Thanks!
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
When running OpenCV on Windows 7, using the standard python shell, I get the following behavior.
import cv
im = cv.LoadImageM("data/somefile.jpg")
thumb = cv.CreateMat(im.rows/6, im.cols/6, im.type)
print "Before"
cv.Resize(im, thumb)
print "After"
Gives:
>>> Before
========================= RESTART ==========================
No error is thrown, what should I look for? What causes such crashing in OpenCV/Python?
Most memory allocation in OpenCV is unchecked and can result in crashes. OpenCV also attempts to throw exceptions through C code, which may cause anything to happen (usually a crash) depending on how it was compiled.
Check whether the values of im.rows/6, etc. are what you expect and that the image sizes should be within python memory limits.
I had to rebuild OpenCV using Visual Studio (Express) 2010, in stead of MinGW, that did the trick, so I guess it was just a faulty build in the end.
i don't think your program is crashing,it is doing just what you are telling it to do.
See the codes below,am using openCv 2.2 with python 2.7.2.Try using WaitKey() to prevent crashes!
import cv
cv.NamedWindow("win",cv.CV_WINDOW_AUTOSIZE)
im= cv.LoadImageM("image.jpg")
thumb= cv.CreateMat(im.rows/3, im.cols/3, im.type)
cv.Resize(im, thumb)
cv.ShowImage("win",thumb)
cv.WaitKey(10000)