Use OpenCV in Xcode 4 for a Mac OS X Application

First of all you have to install OpenCV in Mac OS X. Then in Xcode create a new Mac OS X Application project of type “Command Line Tool”.

Set a “Product Name” and choose “Foundation” for “Type” option.

In the “Build Settings” tab (clicking on the projects blue icon on the left) add following values for those options:

Inside “Search Paths”:
Header Search Paths: /usr/local/include
Library Search Paths: /usr/local/lib
Inside “Linking”:
Other Linker Flags: -lopencv_core -lopencv_highgui -lopencv_imgproc

NOTE: You can add more libraries in “Other Linker Flags” to add more OpenCV functionality, for example:

-lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_legacy -lopencv_contrib -lopencv_calib3d -lopencv_features2d -lopencv_flann -lopencv_ml -lopencv_objdetect -lopencv_video

It’s also necessary to change inside “Build Options” the next parameter or the C functions of OpenCV will not work:

Compiler for C/C++/Objetive-C: LLVM GCC 4.2

In main.m write this example code, compile (command+B) and execute (comnand+R).

//
// main.m
// OpenCVTest
//
// Created by __MyName__ on 16/09/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import 
#import "opencv/cv.h"
#import "opencv/highgui.h"

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    IplImage* img = cvCreateImage( cvSize( 640, 480 ), IPL_DEPTH_8U, 3 );
    
    cvCircle( img, cvPoint( 320, 240 ), 100, cvScalar( 255, 0, 0 , 255 ), 5, 8, 0 );
    
    cvNamedWindow( "OpenCV Window", CV_WINDOW_NORMAL );
    cvShowImage( "OpenCV Window", img );
    
    cvWaitKey(0);
    
    cvDestroyWindow( "OpenCV Window" );
    cvReleaseImage( &img );
    
    [pool drain];
    return 0;
}

If it fails compiling it’s posible that you need to add the “opencv/cv.h” import first of all, but in order to be really the first one you have to put it inside the .pch file (the one with the same name as your project) in the “Supporting Files” folder:

#ifdef __OBJC__
    #import "opencv/cv.h"
    #import 
#endif

This is because OpenCV has a MIN macro defined that also exists in Apple framework, and if you don’t have the one in OpenCV you may have errors like “LLVM GCC 4.2 Error: Statement-expressions are allowed only inside functions”.

Leave a comment ?

3 Comments.

  1. install opencv on macos 10.8.1 | 子龙山人 - pingback on Thursday September 13th, 2012 at 10:36 AM
  2. opencv,vim,mac | 子龙山人 - pingback on Monday December 17th, 2012 at 05:46 AM
  3. Excelente. Corto, pero muy completo

    Reply

Leave a Comment

Trackbacks and Pingbacks: