Unity OpenCV

Unity and OpenCV – Part two: Project setup

After installing OpenCV in the previous part, we can now set up the first C++ project – the steps listed below apply to all OpenCV projects, not just to use within Unity. Let’s dive right in!

  1. Create a new empty C++ project in Visual Studio.
  2. Add a first .cpp to the project – nothing needs to be in there yet, it’s just necessary to get all the project properties.
  3. At the top of the window, change the platform to x64 – we compiled the 64 bit OpenCV libraries earlier after all.
  4. Open up the project properties and switch the configuration to All Configurations so both Release and Debug are changed simultaneously. Change the target extension to .dll, and the configuration type to the same – we need a .dll to include in our Unity project.

OpenCV general c++ project properties

  1. Under C/C++ > General, add $(OPENCV_DIR)\include to the “Additional Include Directories” field. If you recall the previous part, we defined OPENCV_DIR as a system user variable, pointing to where we copied the OpenCV .dll’s, .lib’s and .hpp’s (includes). In case you are not yet familiar with C++ and wonder what these includes are about, for now it suffices to know that includes are what’s necessary to tell a .cpp file what classes exist and which members they have – this has to be defined manually, unlike C#, which knows all about other classes in the same project, or projects that are referenced.
  2. In the Linker > General options, change the “Additional Library Directories” property to $(OPENCV_DIR)\lib\Debug and $(OPENCV_DIR)\lib\Release for the Debug and Release configuration respectively. We built both the debug and release versions in the previous part, and this is where we need ’em.
  3. Finally, under Linker > Input, edit the “Additional Dependencies”. For the Debug configuration, add opencv_core310d.lib and opencv_highgui310d.lib. Notice the “d” at the end of the name – it signifies the debug version. The “310” is the version number. For the Release configuration, add the same two files, only without the “d”.

To test that everything is set up correctly, add the following two lines to the .cpp file you created in step 2:

Build (F6) in both the Debug and Release configurations. If you encounter an error, go through the steps again and double check spelling. Also check the directories in your OpenCV install directory from part one, make sure all the required folders and files are there, and you defined the system variables correctly. If any are missing, go through part one once more.

If both builds succeeded, then congratulations! We’ll meet again in the next part, when we actually have the project do something useful and integrate it with Unity.