OpenCV crashing on cv.Resize - python

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)

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.

Python import (Could be python or Lego Mindstorms libs)

I'll start this by saying I'm not the most familiar with python, and this issue could be a more general python thing that I don't get (i.e. a glaringly obvious duplicate).
In the python bindings for the ev3, a motor is referenced like this:
# hardware.py #
import ev3dev.ev3 as ev3
motor = ev3.LargeMotor('outA')
motor.connected
Where 'outA' is the output port on the robot that the motor is connected to.
If I then do:
$:python hardware.py
I get no issues and I can use the motor normally. However, if I write a new file
# do_something.py #
from hardware import *
I get an error:
Exception TypeError: "'NoneType' object is not callable" in <bound method LargeMotor.__del__ of <ev3dev.core.LargeMotor object at 0xb67d2fd0>> ignored
Does anyone know why this is happening? Is it a python thing or an ev3 thing?
My reason for wanting to import in this way is so that I can do all of the hardware setup in one file (a sizeable chunk of code) and then import this to the files that actually make the robot perform tasks.
I know that NoneType is the type of None in python, I just don't know why a direct compile works but an import doesn't.
1st Edit:
Ok, so I compiled it as:
$:python hardware.py do_something.py
$:python do_something.py
And this gave no errors.
However, upon request, I've added more code, hardware.py is the same:
# do_something.py #
from hardware import *
counter = 0
while True:
if (counter >= 1000):
break
motor.run_direct(duty_cycle_sp = 20)
counter += 1
I.e. run the motor at a cycle speed of 20 until we've been through a thousand loop iterations.This works, and runs until the loop breaks and the script ends. The same NoneType error is then given and the motor continues to run even though the script has finished. The behaviour is the same with a KeyboardInterrupt. There is no traceback given, just that error message.
First of all, python is a language at which it's codes are formed from words, and on the other hand the Lego Mindstorms "language" is formed of simple blocks. That said, logically the two languages cannot be mixed together and have nothing in common. And with having vast experience with both, I never found any thing in common between them.

glReadPixels() fails, but replacing GL_RGBA with GL_RGB makes it work, inside pyglet

On Ubuntu 14.04, I'm testing an open source project which uses pyglet.
I'm running /usr/bin/Xorg directly and separately, using the Nvidia driver with a Nvidia GPU.
The project has this part:
buffer = pyglet.image.get_buffer_manager().get_color_buffer()
image_data = buffer.get_image_data()
And pyglet.gl.lib.GLException: invalid operation occurs when it executes the second line.
Therefore I debugged using PYGLET_DEBUG_GL_* environment variables, and figured out that the error happens while calling glReadPixels(0, 0, 600, 400, 6407, 5121, <pyglet.image.c_ubyt).
The pyglet part of the stack trace is here: 1, 2
ColorBufferImage class originally uses GL_RGBA, and I tried changing it to use GL_RGB, by modifying the 2 lines here.
I didn't anticipate it, but GL_RGB made the glReadPixels() call work without the error, though I cannot use it since the open source project assumes it would be GL_RGBA.
I really want to know how to make GL_RGBA work...
Could someone please help me?
Update: I've just tried an another option, and I think changing the data type from GL_UNSIGNED_BYTE to GL_UNSIGNED_SHORT works (I also changed the buffer's primitive type from GLubyte to GLushort). If this is right, is this a bug of pyglet?

How can I get the volume of sound of a video in Python using moviepy?

I want to get the volume of sound of a video so I use the following:
import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate
clip = VideoFileClip("soccer_game.mp4")
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000)
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.audio.duration-2))]
But I get these errors:
Exception AttributeError: "VideoFileClip instance has no attribute 'reader'" in <bound method VideoFileClip.__del__ of <moviepy.video.io.VideoFileClip.VideoFileClip instance at 0x084C3198>> ignored
WindowsError: [Error 5] Access is denied
I am using IPython notebook and Python 2.7.
I assume something doesn't have the appropriate permissions. I have changed run this program as an administrator for ffmpeg.exe, ffplay.exe, ffprobe.exe.
I fixed a bug today that may have caused your problem, would you mind upgrading and trying again ? If it still doesn't work, I'll need to know your windows version.
Rather than doing own calculations, I would recommend to use an existing library or tool that considers the human-perceived loudness.
For example, ffmpeg can measure the loudness based on the EBU R 128 recommendation (in LUFS).
This discussion recommends pyloudnorm.

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