Monday, January 18, 2010

OpenCV with Python on Windows

Well, it was inevitable. First I installed OpenCV with Python bindings on Mac OS, then on Ubuntu... and now it's time to run it on Windows. Yayyy...

Here's how I got OpenCV 2.0 with Python 2.6 working on Windows.

1. Install OpenCV2.0 from Sourceforge (This was already done when I arrived on the Windows machine, hence the hacking below).
2. Install Python 2.6 if you don't have it already.
3. Make some edits to your Environment Variables:
a) Add C:/Python2.6;C:/OpenCV2.0/bin_old to PATH
b) Add C:/OpenCV2.0/Python2.6/Lib/site-packages to PYTHONPATH
4. Test from within Command Prompt. Navigate to C:/OpenCV2.0/samples/swig_python. Try python delaunay.py

NOTE: This isn't really the recommended way to get things working. The recommended way is to install Python 2.6 and then OpenCV2.0, in that order. You could probably also reinstall OpenCV2.0 again after upgrading to Python 2.6, but I didn't want to.

I'm writing this in case you also got an error such as "ImportError: No module named opencv.cv" , etc. when trying out the swig_samples in OpenCV2.0.

34 comments:

tsubakmetov said...

Has this worked well for you? I tried something very similar and ran into the following problem with code I tried running:

if I use the old bindings:

from opencv import cv
cv.cvSomeFunction

It works fine, but then I can't seem to pass an array of CvPoint2D32f as parameter to GetPerspectiveTransform - I always get python errors about invalid args.

If I use the new bindings:

import cv
cv.SomeFunction

then a large number of functions such as cv.Canny cause python.exe itself to crash, though passing parameters to GetPerspectiveTransform is easy.

Searching online, it seems like the issue is the python binaries are built with Visual C++ and OpenCV is built with mingw.

It sounds like my options are to build python with mingw (which is apparently non-standard and will mean I can't use other python modules without also building them, and even then there are conflicts with system DLLs). Or I can compile OpenCV with Visual Studio, but then if I don't build it with the exact version of visual studio python was built with I'll get the same problems.

Do you have any thoughts on how to make it all work without wasting huge amounts of time (I expect my first efforts at building python or opencv will fail since google seems to turn up all kinds of people having problems with either). Really I just want to use OpenCV, and ironically what I like about OpenCV is that it seems to make so many things I want to do so easy. (once I can get it all installed!)

tsubakmetov said...

oops - meant to check the "email follow-ups" checkbox.

And thanks if you have pointers of any kind!

Unknown said...

To be honest, after testing the demo program I mentioned (which worked fine), I ended up not using the Windows OpenCV due to camera driver problems. If you like, you can post some of the code that's giving you problems and I can test it out on my machine.

tsubakmetov said...

Not sure if this will come through in a comment, but I'll try. Here is using the old-style interface. It works without crashing, but I can't figure out how to pass arrays of points to GetPerspectiveTransform:

#! /usr/bin/env python
from opencv import cv
from opencv import highgui

image = highgui.cvLoadImage ("GobanPic.jpg")
if not image: sys.exit(-1)

# What format do I use for src and dst?!
#src = [(0,0), (1,0), (0,1), (1,1) ]
#dst = [ (0,0), (17,0), (0,17), (17,17) ]
#trans = cv.cvCreateMat(3, 3, cv.CV_32FC1)
#cv.cvGetPerspectiveTransform(src, dst, trans)

# convert to grayscale and find edges
gray = cv.cvCreateImage (cv.cvSize (image.width, image.height), 8, 1)
edge = cv.cvCreateImage (cv.cvSize (image.width, image.height), 8, 1)
cv.cvCvtColor(image, gray, cv.CV_BGR2GRAY)
print "calling Canny - won't crash"
cv.cvCanny (gray, edge, 100, 300, 3)
print "done with Canny - didn't crash"

highgui.cvNamedWindow ("test", highgui.CV_WINDOW_AUTOSIZE)
highgui.cvShowImage ("test", edge)
highgui.cvWaitKey (0)

tsubakmetov said...

And here is using the new-style interface. GetPerspectiveTransform works, or at least I don't get any python errors trying to call it:

#! /usr/bin/env python
import cv

image = cv.LoadImage ("Monkey300.jpg")
if not image: sys.exit(-1)

print "Depth = ", image.depth
print "nChannels = ", image.nChannels

src = [(0,0), (1,0), (0,1), (1,1) ]
dst = [ (0,0), (17,0), (0,17), (17,17) ]
trans = cv.CreateMat(3, 3, cv.CV_32FC1)
cv.GetPerspectiveTransform(src,dst, trans)
print "GetPerspective worked"

# convert to grayscale and find edges
gray = cv.CreateImage ((image.width, image.height), 8, 1)
edge = cv.CreateImage ((image.width, image.height), 8, 1)
cv.CvtColor(image, gray, cv.CV_BGR2GRAY)
print "calling Canny - which will crash"
cv.Canny (gray, edge, 100, 300, 3)
print "done with Canny - crashes before here"

cv.NamedWindow ("test", cv.CV_WINDOW_AUTOSIZE)
cv.ShowImage ("test", edge)
cv.WaitKey (0)

tsubakmetov said...

Both versions have no indenting, but it looks like blogger wrapped some of the lines which might get in the way of python parsing.

As for the images used, I was using my own picture, but for a test, I grabbed some from google images. Here's one to use:
http://image.guardian.co.uk/sys-images/Guardian/Pix/gallery/2002/01/03/monkey300.jpg

This picture works fine in the old-style interface version, but crashes in the new-style.

Now, the funny thing is that if I use a different image, like this one:
http://warp.povusers.org/pics/GobanPic.jpg

Then the new-style test code works without crashing, but my larger script still crashes on a different image function.

I'm guessing it's some minor incompatibility between the python and opencv binaries - given that they were built with different compilers.

Looking some more online, I found this:
http://www.instructables.com/id/Using-openCV-1.0-with-python-2.5-in-Windows-XP/step2/Copy-the-compiled-python-modules-into-site-package/

which has instructions for installing OpenCV 1.0 with Python 2.5. More importantly, they put up a zip file of the OpenCV binaries built with the same compiler as the one used for python 2.5. I think the easiest route might be to just uninstall everything and try to use this.

But if you could try out these scripts or if you had any idea how to pass an array of points to the old-style cvGetPerspectiveTransform, I'd greatly appreciate it.

tsubakmetov said...

Ok, I think I found a solution. I found this like: http://ioctl.eu/blog/2009/10/24/opencv2_msvc

where someone compiled up opencv 2.0 with Visual Studio 2005 and posted an installer.

I uninstalled opencv, downloaded the installer above, installed it, copied the DLLs to windows\system32, and copied the site-packages directory to my python 2.6 directory and suddenly it seems to work without crashing.

Anyway, thanks for the offer of help, but I think I got it working. :)

Unknown said...

Huzzah! Glad to hear you got it working. Thanks for letting me know. Sounds like you were dead-on for the compiler incompatibilities. Meanwhile, the cvGetPerspectiveTransform arguments are still irking me... Anyway, good luck in your project. OpenCV is really great once you get past the installation stage :-)

alexlp said...

Does anybody get an error while using cv.CvtColor(self.frame, self.grayscale, cv.CV_RGB2GRAY) and win32. There is no traceback, program just terminating.

tsubakmetov said...

I'm guessing it's either the same problem I had, with incompatible binaries or your destination or source image is the wrong size or format. The destination should be the same width/height of the source, but should be a different pixel format. OpenCV seems to be very picked about that sort of thing and just crashes without explaining.

tsubakmetov said...

Oh, and btw, my project is coming along nicely. Given an image of a go board, it converts to gray, uses dilate to remove the grid on the board, canny to detect edges, hough to find the biggest lines, kmeans to separate them by angle and position to get the four sides, some python code to intersect the lines and sort the corners, GetPerspectiveTransform to get a transform from the original board image to a canonical square board image. Then I search at each board intersection to classify the pixels as empty or a white or black stone. Then I generate a standard sgf file of the board positions. I still have some work to do, especially tweaking the canny and hough parameters and the stone classifier, but it works reasonably well on some of my test images.

It's been a bit tedious finding online examples of calls to specific opencv functions - getting data into and out of matrices is especially annoying to find the right voodoo. But at the same time, it is amazing to have all of these mature, highly optimized tricks available to do the heavy lifting for the project.

I've also been making use of the line and circle drawing primitizes and a custom mouse handler to greatly aid in debugging. For a debugging environment, I'm using Idle as an editor and just running the code from the command line to see what happens - with some debug print statements and drawing. If I have trouble with an API call, I use an interactive shell to make a bunch of attempts until it accepts it without errors.

alexlp said...

self.capture = cv.CaptureFromCAM(0)

self.frame = cv.QueryFrame(self.capture)

self.image_size = cv.GetSize(self.frame)

self.grayscale = cv.CreateImage(self.image_size, 8, 1)

cv.CvtColor(self.frame, self.grayscale, cv.CV_RGB2GRAY)


GregA, I'v check size. it's 320x240, what wrong with pixel format?

tsubakmetov said...

That looks right. I suspect you're having a problem with incompatible DLLs. What version number of python and OpenCV are you using, and what compiler and version were they compiled with? If you just got the standard windows installers for python2.6 and OpenCV2.0, then you have the exact problem I had. Which is that python2.6 is compiled with Microsoft's Visual Studio, while OpenCV2.0 is compiled with Mingw, a version of gcc, I think - and not 100% compatible with python's binary.

If that's your situation, the only solutions I could find after much searching was to either compile both myself or to find different binaries. In one of the comments above, I found a version of OpenCV2.0 compiled with Visual Studio 2005, and that was worked beautifully with the standard python2.6 windows binary, apparently also compiled with visual studio.

If you feel sure you have compatible binaries for python and opencv, then I'm not sure what it is.

alexlp said...

Yes, you where right.
Compilation error. In linux all is good.

Hotel in Tuscany said...

Very good page. I have added it to my RSS feed. I am looking for some info on hotel in Tuscany can you help with that.

Adrian Perez said...

After many travails trying to get things set up properly, your post helped me greatly. I'm new to OpenCV, and was getting very frustrated with exactly how to get things running. Thank you.

Unknown said...

thanks for the feedback :)

Anonymous said...

of grt help indeed!!!!

Rlly thnkx....god bless u.

Anonymous said...

of grt help indeed!!!!

Rlly thnkx....god bless u.

splinewave said...

Hey Angelica: Question for you:

I am trying to capture from a Sony Handicam DCR-HC38, running the code below, passing [-1 .. 3] to the CaptureFromCAM function. The code runs, but I get no image (only a grey window). I'm new to windows, open-cv, python, and cameras, and I see that you decided not to use opencv/python/windows for your purpose. Do I need to "wrap" the camera somehow? Skype recognizes the camera, but python/opencv won't. I'm running Windows Vista if that helps any. Any tips would help a lot.

//

import cv

cv.NamedWindow("camera", 1)

capture = cv.CaptureFromCAM(-1)

while True: img = cv.QueryFrame(capture) cv.ShowImage("camera", img) if cv.WaitKey(10) == 27: break

Unknown said...

Hi splinewave,

I'm afraid it might be because your camera isn't supported by OpenCV :S

http://opencv.willowgarage.com/wiki/Welcome/OS

Sometimes non-supported cameras seem to "just work", but this might explain your problem.

Pavan said...

Hello,
Im using OpenCV 2.1.0 and python 2.6

I tried to execute the facedetect.py file located in python samples in opencv. but it gives me the following error.

Traceback (most recent call last):
File "C:\OpenCV2.1\samples\python\facedetect.py", line 63, in
cascade = cv.Load(options.cascade)

TypeError: OpenCV returned NULL

environmental variables set by me are.

ENVIRONMENTAL VARIABLES:

variable name: PATH
variable value: C:/Python26;C:/OpenCV2.1/bin

variable name: PYTHONPATH
variable value: C:/OpenCV2.1/Python2.6/Lib/site-packages

SYSTEM VARIABLES:

variable name: PATH
variable value: %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\Intel\DMIX;C:/Python26;C:/OpenCV2.1/bin

variable name: PYTHONPATH
variable value: C:/OpenCV2.1/Python2.6/Lib/site-packages


Please solve this problem.
Thank you.

Unknown said...

Hi Pavan,

Do any of the other sample programs work? Is it just facedetect.py that is the problem?

Angelica

Pavan said...

Many other programs like camera.py, camshift.py, delaunay.py, convexhull.py,contours.py,edge.py,morphology.py, work just fine.

There are also other programs which give errors along with facedetect.py .

For example peopledetect.py gives the following error.

Traceback (most recent call last):
File "C:\OpenCV2.1\samples\python\peopledetect.py", line 15, in
print "cannot read " + sys.argv[1]
IndexError: list index out of range

Anonymous said...

sys.argv[1] is the first command line argument. It looks like it expects to get an image filename as the first command line arg and you aren't giving one. Either it's that or the way you are calling it (maybe from a batch file or something) isn't passing on the command line arg.

Pavan said...

Ok... but im worried about facedetect.py. I need to execute it inorder to complete my project.

jhvhjvc said...

i am working on a python code based on image processing on windows platform .. but i am facing problem while running an already written code which demands python, python image library,libsvm and open CV 1 .. i have inatalled python 2.6, PIL and open CV 1 but i am getting missing dlls error first i got highgui100.dll missing i downloaded and copied to c:/windows then the error became opencv100.dll missing , i again did similar thing but the dll missing error keeps coming up with different name each time .. i also added the c:/opencv2.0 as environment variable path but the code did not work
Kindly help me in this case. it is very urgent. i know you have very less time for unknown mails but i have only you as a hope in my project

Unknown said...

Hi GregA

Have been reading the posts here and already I have been much enlightened :). Thank you.

I am trying to get OpenCV+Python2.6 up and running in Windows 7.

I have had similar issues to you in that simple functions seem to work fine, but functions like cvCanny cause Python to crash and I get a message "python.exe has stopped working".

Do you have any advice on how I might get OpenCV+Python2.6 in Windows 7 to fly?

Been googling, but information regarding this has been sparse, this post has been the closest to what I'm looking for.

Thanks in advance :).

Bryan

meistergrimbart said...

Hi all,
i have a similar problem.
i have installed opencv2.2 on win7 64bit. then i did the compiling and the c and c++ examples work fine. But when i try to install python2.7 64bit on windows its not possible to run the python examples. it always says "C:\OpenCV2.2\samples\python>python camera.py
Traceback (most recent call last):
File "camera.py", line 1, in
import cv
ImportError: DLL load failed: %1 ist keine zulõssige Win32-Anwendung." It means that it is no correct win32 application. But why is this happening? I installed everything (opencv, python2.7) in 64bit mode. can anybody help?

Anonymous said...

hye,i'm still new in programming.I got a problem.

I'm already follow your step but it seem like:

cannot read import cv
statement

Deepak said...

Hi pavan,
for facedetect.py try cascade =cv.Load(options,cascade)

Deepak said...

And after changing that '.' by a ','! I executed the program and I am getting the following error:
"NameError: name 'cascade' is not defined"
How do i resolve this?

harsh sharma said...

fathers day

father's day messages 2016

fathers day messages 2016

fathers day messages 2016

Happy fathers Day

Happy Fathers Day

fathers day quotes

fathers day messages 2016

fathers day messages

fathers day poems

fathers day greetings

fathers day wishes

Dhruval said...

free netflix account
netflix login password
netflix accounts
free netflix account
pof login

plentyoffish login