A blog about anything a software engineer might encounter during his programming efforts.

11 July 2012

Installation guide: OpenCV 2.4 with Visual Studio C++ 2010

After some trouble installing OpenCV 2.4 in Windows and using it with Visual C++ 2010, I decided to write a post about this, so I can hopefully save you some time figuring this one out. It is based on this wiki, but that describes how to build with CMake etc, which is not necessary (anymore?).

Okay, so first you need to download OpenCV 2.4 here. After downloading, you need to extract it. I have extracted it to "D:\OpenCV2.4.2\" and I will use this folder for the rest of this post, you can change it if you like.

Edit your PATH variable (right click on this computer, properties, then select the tab "advanced" and click on "Environment Variables", which is near the bottom).

Add these paths to your Path Variable:

D:\OpenCV2.4.2\opencv\build\x86\vc10\bin

D:\OpenCV2.4.2\opencv\build\common\tbb\ia32\vc10

Replace the beginning with your install path of course. It think that you would need to replace x86 in the first path with x64 and ia32 in the second path with intel64 if you want to build a 64 bit application, although I am not sure about this.

Now we are ready to create a project with OpenCV. In Visual C++ 2010, create a new Win32 console application called OpenCVTest. Now right click the project and select Properties.

On the left, choose C/C++ and edit the Additional Include Directories. Add these directories:

D:\OpenCV2.4.2\opencv\build\include\opencv

D:\OpenCV2.4.2\opencv\build\include

Now choose Linker and add this directory to the Additional Library Directories:

D:\OpenCV2.4.2\opencv\build\x86\vc10\lib

Again I think you need to replace x86 with x64 if you want to build a 64 bit application.

Now open the Linker group (press the + sign before it) and select Input. Add these lines to the Additional Dependencies:

opencv_core242d.lib

opencv_imgproc242d.lib

opencv_highgui242d.lib

opencv_ml242d.lib

opencv_video242d.lib

opencv_features2d242d.lib

opencv_calib3d242d.lib

opencv_objdetect242d.lib

opencv_contrib242d.lib

opencv_legacy242d.lib

opencv_flann242d.lib

Replace 242 with your version if you're not using 2.4.2. Easiest is to paste these lines in notepad, press CTRL+H and set it to find "242" and replace with "251" (would your version be 2.5.1 for example).

And this one cost me a couple of days to figure out: if you do a release build, please remove all the d's in the above filenames (so opencv_core242d.lib becomes opencv_core242.lib), otherwise it won't run properly!

Finally you're ready to use OpenCV. To test it, paste the following code in your OpenCVTest.cpp file:

#include "stdafx.h"

#include <cv.h>

#include <cxcore.h>

#include <highgui.h>

int _tmain(int argc, _TCHAR* argv[])

{

IplImage *img = cvLoadImage("D:\\funny.jpg");

cvNamedWindow("OpenCV",1);

cvShowImage("OpenCV",img);

cvWaitKey(0);

cvDestroyWindow("OpenCV ");

cvReleaseImage(&img);

return 0;

}

(Please replace D:\\funny.jpg with a valid path to an image! Also make sure that you use double backslashes in stead of one, this because the backslash is an escape character in C++.)

I'm afraid you'll have to debug the code and step through it one line at a time, so you can identify the line of code that is causing the exit.An exit value "0" normally indicates a "normal" exit, so probably somewhere showing results is skipped or something and the program just exits.Good luck!

Hi Anonymous,Your main function cannot be found, make sure it is there and set as entry point. If unsure, you can also just create a new project. Do not remove the initial "main" function, just paste the code that goes inside it.

Yes it is. First decide whether you want to create a 64 or 32 bits application. If you create a 32 bits application, you can just use the guide as it is. If you want a 64 bit application, note the parts where you include various directories, there are other directories with 64 bit libraries, but they are mentioned in the guide itself.

Any cv::Exception objects can be caught, by placing a try-block around the call that produces it, catching it as "catch(cv::Exception ex) { printf(ex.what()); }" will show you the error within.Most likely: the cv::Mat object is empty, which will produce an error when you use it, you can check this with the method ".empty()", which will return true iff the Mat object is empty.

thx for your reply .. i did not see your post.. so i was asking again and again.. i have configured as you have suggest ... there is no problem with the build ... but when i debug it .. it gives me only a gray window... and debug stopped... by saying this : The program '[1276] xiv.exe: Native' has exited with code 0 (0x0).

Please add a try/catch block around the line of code that produces the error. If you catch the exception, you can see what's in it (us its "what()" method). I can see you're not doing this, as you have an "unhandled exception", i.e. an exception which is not caught in a try/catch block.

If your image is empty, check your includes, your lib files and directory and above all, check the path to your image file. Remember to NOT use single backslashes in the path string, replace them with double backslashes or forward slashes.

I am sorry .. i am really new in this area .. i did not know how to use try/catch statement... but i have tried to debug step by step and found that the image is empty image without like .. rows and columns with 00000 ... can you please help ... i am really sorry to asking you again and again..

After following the setup process,when i build the program I get a popup window saying that the project is out of date and when i select build,the error says unable to start the program,the system cannot find the file specified(.exe file).Could u pls help me on solving it.THank you

You can just build your application and copy everything in its (release) build directory to another computer. You'll also need the dll's from the folders that you added to you system's PATH variable. You can copy these in the same folder on the new computer and it should work.Depending on the functions you use in OpenCV, you don't need every dll. You can use software like dependency walker to determine exactly what dll's your software requires.

hi.i am using opencv 2.4.2 with visual studio 2010 c++. when i build it doesn't give any error bt while debugging the error shows:'SURF.exe': Loaded 'C:\Windows\SysWOW64\rpcrt4.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\sspicli.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\cryptbase.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\ole32.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\oleaut32.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\winsxs\x86_microsoft.windows.common-controls_6595b64144ccf1df_5.82.7601.17514_none_ec83dffa859149af\comctl32.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\avifil32.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\winmm.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\msacm32.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\msvfw32.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\shell32.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\shlwapi.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\avicap32.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'C:\Windows\SysWOW64\version.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'S:\OPENCV242\build\x86\vc10\bin\opencv_imgproc242.dll', Cannot find or open the PDB file'SURF.exe': Loaded 'S:\OPENCV242\build\x86\vc10\bin\opencv_objdetect242.dll', Cannot find or open the PDB fileNative' has exited with code -1 (0xffffffff). please help me out. I am not getting why these are missing?

There's probably something wrong with your code itself. You can try stepping through it line by line using the debugger.The warnings about missing .pdb files can be ignored. Pdb files contain debug information on dll's and for pre-built dll's these are often missing (you can't debug system dll's for instance).

The fact that you get an empty Window indicates that something went awry. You can check whether your image has anything loaded with a call to .empty(). It returns true iff the image is actually empty.Most often made mistake is to use single backslashes (\) in file paths, these don't work, you have to replace them with double backslashes (\\) or forward slashes (/).Also, does your code even hit the waitKey(); line and if so, does it wait there?

Well, like I said, the warnings about the missing PDB files can be ignored, they are no cause for errors.A return value of -1 probably means that there is an exception thrown somewhere. There must be one line of code where things go wrong, so you should be able to find that line using debugging.You can also put some try/catch blocks in your code, so you can see what's in the exception. This usually gives you a better idea of what is wrong, probably an assert or something which is failing.

It basically means it can't find the dll. Either you didn't (properly) add the paths to your system's PATH variable, or your system is unaware of the change.Please check if they are added properly, if the dll is actually in these folders and you might want to try restarting visual studio or your computer, to make sure the change gets noticed.

Thank you for the post. My installation went very well but I have one problem. Console window won't close even after opencv application has closed. My OS is wind 7 64bt. MSV express C++ 2010. I did not have any problem with opencv 2.2. Please helpJo

Did you access a camera (using a CvCapture object) or anything? Otherwise you could just press the 'stop' button in Visual Studio's debugger (assuming you are running in debug mode), that will force it to stop. If in debug mode, you could also pause it and see where it hangs (if it does). The example should reach the return statement and exit normally.

Thanks for the prompt reply. I can run the exe without any problem when I termianted the program. The program closes down but console window stays on. I suspect it is something do with my coding here is my code;

You have to release the capture object as well. You can do this with cvReleaseCapture().BTW, if you are using C++ as language, it's nicer to use the cv::VideoCapture object, rather than the C-style CvCapture, and you can use cv::Mat rather than IplImage (just tips).The cv::VideoCapture object can be released with a standard 'delete' method:delete capture;

Thank you! Thank you!. You made my day. It worked as soon as I released the capture. Thank you once again. I am new to opencv and working on project, once I finish the code I would like to send it you and get some advice. Can I have your email address?

I am updating reference frame every 14seconds to accomdated the gradual change in light change in the back ground.

convert color to gray by cvCvtColor

cvAbsDiff(pre_image, cur_image, diff_img);

cvSmooth(diff_img, dif_img, CV_MEDIAN);

cvTreshold(diff_img,100,255,CV_THRESH_BINARY)

Then usingcvFindContours to find the contoursIf contours ----> MOTION

Once motion is detected. It will stop upating the previous frames.

If a person walk out after motion detection. it has to go into a mode to check only if some body has fallen on the ground.

I implemented this after motion detection no updates of previous frame. THEREFORE the frame which was taken before motion was detected becomes the reference. If contours are present for a x no of seconds then it will "man on floor". The problem with this one is that when floor has dark coloured carpet and person whereing dark clothes, it will not work. Hence to detect man on floor i dynmically changed cvThreshold level to 30, 200 but it seems to give false alarm. Is there a better way of doing it. Thanks in advance.Jo

Take a look at the BackgroundSubtractorMOG and BackgroundSubtractorMOG2 classes. They provide good alternatives for detecting objects in frames. When giving it a frame, you can supply a second parameter '0' to indicate it shouldn't be used to update the model.Both classes use a 'Mixture of Gaussians' approach to create a statistical model of the values of pixels, which will probably provide better segmentation then your approach of just taking the difference between two frames.As long as the background is fairly static, it will use relative strict models and will accept pixels as 'changed' when falling outside of the range seen during training.You can give it a new reference image every x seconds without the second parameter, to keep its model of the background up to date.

I was able to use backgroundSubtractorMOG2 to seprate background and foreground. How can I track a person in it? Let say person walks int particular region of interest then printf("alarm")and other regions don' care if person is in or out. I changed the foreground image to binary to find the contours and looked at size of it, so I can use it to generate a alarm when it go over by particular size but it did not do any good.

I'm not sure I understand your question, but if you want to determine whether a 'blob' enters a certain region, you can calculate its bounding box (or bounding rect I think it is called in OpenCV) and use that to determine the location. You can also find the Center of Mass, using the Moments (cv::Moments) of the contour.The coordinates of the CoM are calculated from the moments like this:CoM.X = m10 / m00, CoM.Y = m01 / m00.

The area (size) of a blob can be calculated using its contour and cv::contourArea().

Thank you for the info, I will look into it. At the moment I found a way to solve the problem. This is what I am doing; I am seprating the frame into 3 areas. If somebody move into the centre area, program should not do anything but when it sees a person in the left or right area it has to send a message to the serial port. At the moment I am doing this by gettting the mean value of the pixel of the fore-image of ROI and if it goes up by certain value then movement is detected. One draw back here is when light levels are low this value has to be reduced. I want to make my program smarter it will decide on this value dynamically depending on the light level.

It is Jo again. My program seems to be working fine. Now I want to port this code execute from Rasberry pi. These are my thoughts but no idea whether it will work or not.

I want install qt in my windows 7 laptop and port the code to qt and compile it for Linux Environment and then transfer the exe and dll files to the Rasberry pi and run the program. Which Linux version is good for this. Am I on the right track?

Now open the Linker group (press the + sign before it) and select Input. Add these lines to the Additional Dependencies:opencv_core242d.libopencv_imgproc242d.libopencv_highgui242d.libopencv_ml242d.libopencv_video242d.libopencv_features2d242d.libopencv_calib3d242d.libopencv_objdetect242d.libopencv_contrib242d.libopencv_legacy242d.libopencv_flann242d.libReplace 242 with your version if you're not using 2.4.2. Easiest is to paste these lines in notepad, press CTRL+H and set it to find "242" and replace with "251" (would your version be 2.5.1 for example).

And this one cost me a couple of days to figure out: if you do a release build, please remove all the d's in the above filenames (so opencv_core242d.lib becomes opencv_core242.lib), otherwise it won't run properly!

Hi Michel,I have followed the steps you have mentioned. I am getting a system error"The program can't start because opencv_core242d.dll is missing from your computer. Try reinstalling the program to fix this problem."I have added the path"C:\OpenCV2.4.2\opencv\build\x86\vc10\bin" which is my directory path in the path variable.

It means you are using the 64 bit libraries, while trying to create a 32 bit build. You can either change your build configuration in Visual Studio to actually create a 64 bit build, or you can switch to the OpenCV 32 bit libraries. Please note that the will always have to match and that a 32 bit build will run on both 32 and 64 bit computers, while a 64 bit build will only run on 64 bit computers.

I tried to reinstall Visual Studio, installed Visual C++ distributed packages, downloaded and copied to working directories files .dll missing... but errors still there.COuld you please give me a hint for this struggle?Thanks.

I just noticed this line in your output:Loaded 'C:\opencv242\build\x86\vc9\bin\opencv_core242d.dll'It seems like you are using the VS 2008 dll's of opencv. There should be a folder vc10 rather than vc9 for Visual Studio 2010.I hope that's your problem.

im very anxious to try to learn how to use visual studio c++ 2010 express and open cv 2.4.5. ive followed your blog steps to the letter (except that i did not the the instruction referencing 'D:\OpenCV2.4.2\opencv\build\common\tbb\ia32\vc10' as i do not run 'itanium' platform).yes ive replaced your 'd:\opencv2.4.2\' path with my 'c:\data\lib\opencv245\' path and the link to the graphic file. when i try to compile i get this error...

to note, ive not compiled a c program for over 20 years, so i am more than rusty here, and ive never really ever had to link against 3rd party libraries as we are doing here. im confused by the reference to 'opencv_calib.obj' i assume this is an object file that the compiler was to have built??? but why isnt it referencing ''opencv_calib245d.obj'? i am begging here for some help.

Sorry to say I have never encountered a problem with a .obj file. If you do a search on the OpenCV folders, is there any such file as the linker is searching for? If so, you might try and add that directory (and maybe even the file(s) itself) to the linker setup in the configuration (as I've done in the guide with the .lib files). Hopefully that will solve your problem.

well, seeing as i did NOT follow one line of your instruction (thinking because i was not on 'itanium' platform), perhaps this is the problem. i did not put into my path envvar '...opencv\build\common\tbb\ia32\vc10'. my question to you is, 'should this folder exist after installing opencv?' as after a fresh install, i find this folder does NOT exist. under '...opencv\build' there is no 'common' sub folder. perhaps this is the issue?

The common folder only contains 3rd party libraries, such as Intel's tbb. But the opencv libraries (such as the opencv calib you seem to be missing) should be in D:\OpenCV2.4.2\opencv\build\x86\vc10\lib (or your variant thereof).But I only have .lib files in these folder, no .obj files, so I'm still at a loss what's going wrong for you.Or are you by any chance building OpenCV itself? That would (and should) produce obj files during that task.

i figured it out. i evidently read your page that speaks to entering the program and compiling it. perhaps there was a different page i did not see that spoke about the requirement to use intel's 'tbb' (threading building block) library as well. there are several ways one can add this functionality to vc++, using the tbb 'visual studio plug-in', copying all of the tbb *.dlls into one of your existing opencv search path folders, or unzipping the entire 'tbb' library into where you store your general 3rd party libraries and adding the '...\tbb##\bin\ia32\vc##' and '...\tbb##\bin\ia32\vc##\irml' dirs to your path env var. i opted for the latter method. and now it compiles !!! thanks.

attempt to obtain the coordinates x, y of an object to measure its speed in a particular area, but the speed of the movement is fast and I have not the number of samples per unit time need ... I'm using filtering by color, question is:

1) is faster using detection using contour or color?

2) depends on the webcam, how many frames per second can take? this amount is configurable with opencv?

What approach is faster is fully dependent on how you do them and on what resolution, but my first guess would be that colour segmentation is easiest and quickest.As to the processing speed: Do you use multiple threads to make the most use of your CPU? Also, don't forget that USB2 has limited bandwith, at 2MPixel with no compression (don't use MJPG as it has a very negative influence on image quality for Computer Vision) you cannot get much more than 2 or 3 frames per second over a USB2 port.There are USB3 cameras which can reach much higher speeds, but they are quite expensive.

You can control the FPS with OpenCV, but you can test with other software what the highest possible settings are for your camera. Remember: the higher the resolution, the lower the framerate.

This is the first time I am working with opencv in Visual Studio. I have worked in ubuntu though. I was trying to install opencv. 1.I extracted it. Edited the path variable in system properties as D:\opencv\build\x64\vc10\bin

2. I set VCC++ directories as $(OPENCV_BUILD)\x64\vc10\lib;$(LibraryPath).

3.C/C++ additional include directories as $(OPENCV_BUILD)\include\opencv;$(OPENCV_BUILD)\include\opencv2

There is tiny mistake in your step 3: $(OPENCV_BUILD)\include\opencv; Should be $(OPENCV_BUILD)\include; For some reason the default is that and for opencv2 you add \opencv2.That is because all references to the header files are as 'opencv/highgui.cs', so if you already added the 'opencv/' part, it won't find them.

Completely off-topic... but I noticed you have solved your blogger problem where it was showing only the first 200 comments on this post. I'm having the same problem... Could you tell me how you changed the "Load more..." link to "Newer" and "Newest"? :)

Hi Michael...I am facing a virtual problem with opencv. i am using 64bit win7 and vs2010. When i run face_detection program it just open camera window and does not detect the face(in 64bit debug). But same code when I run in my friend's computer of 32bit win7 it works fine. So should i do to fix the problem.[i have tried that code in 32bit debug by suitable configuring property_manager in my computer it compiled successfully even. But gives run time error of 0x0000007b and terminate with showing c:\windows\sysWOW\kernel32.dll cannot open.][I downloaded new kernel32.dll but it not copying in c:\windows\sysWOW folder]Please helpThank You

The first is just a warning, it says how to disable it.The second is a fault in Segmentation.cpp. It tells you that the left brace ('{') isn't matched before the End-Of-File was found. This just means that you have at least one more '{' in your file than you have '}'. These should match, for every '{' you should have a matching '}'.

Hello.. I'm using Visual studio 2010 and i downloaded opencv2.4.11 and configure it according to your described steps..but it is showing the error while debugging, error is Fatel error lnk1181: cannot open input file 'opencv_calib3d2411d.lib'

Hello,MichaelI am working with a code that finds moving vehicles. When I added the find contours method, that's where the program has struct.It is showing unhandled exception at memory location....The code is as follows: