OpenCV is the most mature computer vision library in the world. Xcode is the best IDE on macOS. OpenCV is written in C++ and various bindings (first- and third-party) exist for most popular language. I prefer to work in C++. Although Xcode has excellent support for C++ projects, getting it to play nicely with OpenCV is rather tricky.
This post describes a quick and dirty way to setup Xcode for OpenCV projects.
1. Get the tools
Install Homebrew and then,
$ brew install opencv pkg-config
opencvwill install the latest OpenCV stable release. If you have OpenCV installed elsewhere, or perhaps you build it from source, you can skip this step.
pkg-configis a helper tool to fetch C++ compiler options for OpenCV. We will use it to configure our Xcode project.
2. Why doesn’t it “just work”
To build a C++ project:
- the compiler needs to know where to find the header files for libraries used, and
- the linker needs to know where to find the object files for said libraries
When Xcode tries to build an OpenCV project, it looks for the headers and library files in the standard search paths, and returns an error when it can’t find the OpenCV library.
3. Configure Xcode
Xcode > Build Settings:
/usr/local/Cellar/opencv/4.3.0/include/**to Header Search Paths setting
/usr/local/Cellar/opencv/4.3.0/lib/**to Library Search Paths setting
/usr/local/Cellar is Homebrew’s default installation directory.
4.3.0 is the OpenCV version I use.
pkg-config to get all the compiler flags supported by OpenCV. Obviously this is overkill as no project will ever import everything this library has to offer, but it gets the job done.
$ pkg-config --cflags --libs opencv4
Copy the entire output and paste it in the Other Linker Flags build setting.
That’s it. Xcode should be able to build your project now. You may have to set the Documentation Comments setting to
No. Clang doesn’t seem to like the documentation comments in OpenCV library and flags them as compiler warning.