Random Sequence

As I found, incorporating the OpenCV image processing library into your Cocoa app is more difficult that it sounds.

Sponsored Links:

Building OpenCV 2.2 for Snow Leopard

The 2.2 release of OpenCV supports building on x86_64 systems. I spent longer than I expected to setting up a test Xcode Cocoa project where I could begin experimenting with the latest release, targeting i386 & x86_64. Here’s how I got there:

Install CMake

Building OpenCV 2.2 requires using CMake.

CMake is a unified, cross-platform, open-source build system that allows developers to build, test and package software by specifying build parameters in simple, portable text files. (Wikipedia)

Being a clean-shaven developer, this is the first time I’ve needed to use this tool. It doesn’t come included with Snow Leopard, so you need to obtain this from somewhere else. I used MacPorts. If you’ve previously installed MacPorts for something else, it’s worth doing an update before you install anything:

sudo port selfupdate

This may take some time. When that’s done:

sudo port clean cmake; sudo port install cmake;

The clean command may save you doing this twice if you’ve had a build which failed.

Download & Configure OpenCV

The latest version (2.2 at the time of writing) should be available here: http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/

Once you’ve downloaded & extracted the source code, open a terminal window and head to that folder, then make yourself a build folder:

cd OpenCV-2.2.0
mkdir build
cd build    

Ask ccmake to make us an Xcode project:

ccmake -G "Xcode" ../ 

In the ccmake interactive console, you should see a “EMPTY CACHE” at the top of the console window. Hit ‘c’ to create an initial configuration. Once that’s done, use the arrow keys to move down the list, enter to change a value. My configuration looked like this (I changed only BUILD_SHARED_LIBS & BUILD_TESTS, both to OFF):

BUILD_EXAMPLES                  *OFF                                                                                            
BUILD_LATEX_DOCS                *OFF                                                                                            
BUILD_NEW_PYTHON_SUPPORT        *OFF                                                                                             
BUILD_PACKAGE                   *OFF                                                                                            
BUILD_SHARED_LIBS               *OFF                                                                                             
BUILD_TESTS                     *OFF                                                                                             
BZIP2_LIBRARIES                 */usr/lib/libbz2.dylib                                                                          
CMAKE_BACKWARDS_COMPATIBILITY   *2.4                                                                                            
CMAKE_BUILD_TYPE                *                                                                                               
CMAKE_CONFIGURATION_TYPES       *Debug;Release;MinSizeRel;RelWithDebInfo                                                        
CMAKE_INSTALL_PREFIX            */usr/local                                                                                     
CMAKE_OSX_ARCHITECTURES         *                                                                                               
CMAKE_OSX_DEPLOYMENT_TARGET     *                                                                                               
CMAKE_OSX_SYSROOT               */Developer/SDKs/MacOSX10.6.sdk                                                                 
CMAKE_VERBOSE                   *OFF                                                                                            
EIGEN2_INCLUDE_PATH             *EIGEN2_INCLUDE_PATH-NOTFOUND                                                                   
ENABLE_PROFILING                *OFF                                                                                            
ENABLE_SSE                      *ON                                                                                             
ENABLE_SSE2                     *ON                                                                                             
ENABLE_SSE3                     *OFF                                                                                            
ENABLE_SSE41                    *OFF  
ENABLE_SSE42                    *OFF                                                                                            
ENABLE_SSSE3                    *OFF                                                                                            
EXECUTABLE_OUTPUT_PATH          */Users/mrwalker/Downloads/OpenCV-2.2.0/build/bin                                               
INSTALL_C_EXAMPLES              *OFF                                                                                            
INSTALL_PYTHON_EXAMPLES         *OFF                                                                                            
IPP_PATH                        *IPP_PATH-NOTFOUND                                                                              
LIBRARY_OUTPUT_PATH             */Users/mrwalker/Downloads/OpenCV-2.2.0/build/lib                                               
OPENCV_BUILD_3RDPARTY_LIBS      *ON                                                                                             
OPENCV_CONFIG_FILE_INCLUDE_DIR  */Users/mrwalker/Downloads/OpenCV-2.2.0/build                                                   
OPENCV_EXTRA_C_FLAGS            *                                                                                               
OPENCV_EXTRA_C_FLAGS_DEBUG      *                                                                                               
OPENCV_EXTRA_C_FLAGS_RELEASE    *                                                                                               
OPENCV_EXTRA_EXE_LINKER_FLAGS   *                                                                                               
OPENCV_EXTRA_EXE_LINKER_FLAGS_  *                                                                                               
OPENCV_EXTRA_EXE_LINKER_FLAGS_  *                                                                                               
OPENCV_WARNINGS_ARE_ERRORS      *OFF                                                                                            
OPENEXR_INCLUDE_PATH            *OPENEXR_INCLUDE_PATH-NOTFOUND                                                                  
PVAPI_INCLUDE_PATH              *PVAPI_INCLUDE_PATH-NOTFOUND                                                                    
USE_FAST_MATH                   *ON                                                                                             
USE_IPP                         *OFF                                                                                            
USE_O3 
USE_OMIT_FRAME_POINTER          *ON                                                                                             
WITH_1394                       *ON                                                                                             
WITH_CARBON                     *OFF                                                                                            
WITH_CUDA                       *OFF                                                                                            
WITH_EIGEN2                     *ON                                                                                             
WITH_FFMPEG                     *ON                                                                                             
WITH_JASPER                     *ON                                                                                             
WITH_JPEG                       *ON                                                                                             
WITH_OPENEXR                    *ON                                                                                             
WITH_PNG                        *ON                                                                                             
WITH_PVAPI                      *ON                                                                                             
WITH_QT                         *OFF                                                                                            
WITH_QT_OPENGL                  *OFF                                                                                            
WITH_QUICKTIME                  *OFF                                                                                            
WITH_TBB                        *OFF                                                                                            
WITH_TIFF                       *ON                                                                                             

Hit ‘c’ to reconfigure for the new settings, then ‘g’ to write out the configuration and exit. Open the build folder - it should now contain an XCode project:

open OpenCV.xcodeproj

Fat Binaries

Building this Xcode project in Debug or Release configuration will make the static libraries for your current system architecture. If you’re going to link against these static libraries with a universal binary, you’re going to need multi-architecture libraries:

  • Select OpenCV at the top of the project source tree, then choose File > Get Info from the menu (cmd-i).
  • Select the ‘build’ tab at the top of the window
  • Change the Configuration to Release
  • Under architectures, uncheck ‘Build Active Architecture Only’
  • If you’re targeting the Mac App Store, remove the PPC architectures from the Valid Architectures list
  • Close the project info panel.

Now set the active configuration to Release, build your project. You’ve built yourself multi-architecture static libraries.

Linking Against OpenCV

Create a new Xcode project. I used a command line tool to test the first example project from Learning OpenCV:

  • Choose File > New Project
  • Choose Mac OS X > Application from the source list
  • Choose Command Line Tool from the project templates
  • Choose Foundation under Type
  • Save the project. I named mine CVDemo and saved to the Desktop.

Repeat the “fat binaries” process from above to make sure your test project has the same build architectures as the libraries you’re going to link against.

Add the static libraries from your OpenCV project.

  • In your OpenCV project, Open the Products group in the source tree
  • Drag everything ending ‘.a’ from this project to the source tree in your new project.
  • Check “Copy items into destination group’s folder”
  • Check the add to target checkbox for your target (mine is called CVDemo)
  • Click Add

Frameworks & Build Settings

OpenCV 2.2 itself links against the Cocoa, QuartzCore and QTKit frameworks.

  • In your new project, select your target. Choose File > Get Info
  • Select the ‘General’ tab
  • Click the ‘+’ at the very bottom left of the Linked Libraries section
  • Select Cocoa, QuartzCore and QTKit from the list, click ‘Add’

Xcode needs to know where it’s going to find your static libraries. Still looking at the Target Info window:

  • Select the ‘Build’ tab
  • Scroll to ‘Linking’, double-click ‘Other Linker Flags’
  • Click ‘+’, Enter ‘-lstdc++’ (without quotes), click ‘OK’

Headers

The headers for OpenCV 2.2 are split amongst various modules. I don’t know a sensible way to collect these together from the Xcode project (please let me know if you do), so I re-configured everything in a new build folder:

In the root folder of your downloaded source code, make a new folder:

cd OpenCV-2.2.0
mkdir build_unix
cd build_unix
ccmake -G "Unix Makefiles" ../
  • Generate the base configuration (‘c’)
  • change the settings as before with one change: set CMAKE_INSTALL_PREFIX to a path inside your build_unix folder. Mine was /Users/mrwalker/Downloads/OpenCV-2.2.0/build_unix/unix_install
  • configure again (‘c’)
  • generate the make files (‘g’)

In the terminal, build & install the unix makefile:

 make; make install

This will collect the headers you need together into unix_install/include.

  • Using the Finder, copy opencv & opencv2 from unix_install/include to new folder next to your new project (CVDemo). I named mine ‘headers’

Xcode needs to know where to look for the OpenCV headers. Still looking at the Target Info window:

  • Select the ‘Build’ tab
  • Scroll to ‘Search Paths’, double-click ‘Header Search Paths’
  • Click ‘+’, Enter ‘headers’ (without quotes), click ‘OK’

Sample Code

In your test project (CVDemo), edit main.m with a test project. Mine looked like this:

#import <Foundation/Foundation.h>

#import "opencv2/imgproc/imgproc_c.h"
#import "opencv2/highgui/highgui_c.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString *filePath = nil;

    if (argc > 1) {
        filePath = [[NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding] stringByExpandingTildeInPath];       
    } else {
        filePath = @"/Users/mrwalker/Desktop/test.jpg";
    }

    IplImage *img = cvLoadImage([filePath cStringUsingEncoding:NSUTF8StringEncoding], 1);   
    cvSmooth( img, img, CV_GAUSSIAN, 3, 3 , 0, 0);

    cvNamedWindow("Test1", CV_WINDOW_AUTOSIZE); 
    cvShowImage("Test1", img); 
    cvWaitKey(0); 
    cvReleaseImage(&img); 
    cvDestroyWindow("Test1");   

    [pool drain];
    return 0;
}

Build & Run

That’s it, you should now have an environment to play with OpenCV 2.2 on Snow Leopard.

If this article has saved you some time and you want to say thanks, you could buy my Albums app, tell your friends about my Free Intro Quiz app, or just say thanks via twitter.

Sponsored Links: