Computer Vision Talks All you want and should know about computer vision is here

12Jan/11116

Using OpenCV in Objective-C code

opecv-plus-apple

After publishing Building OpenCV for iOS article many of readers asked me how to use OpenCV within ObjectiveC code, because they encountered compilation errors. In this post I'll show you how to use OpenCV and ObjectiveC to make some image processing.

In this post I'll use GLImageProcessing sample demo from Apple. Also you will need precompiled OpenCV for iPhone. How to make it read here.

I've copied all OpenCV stuff to "opencv" folder into the GLImageProcessing. Here is project directory structure:

example-directory-structure

Now, let's add OpenCV to our project.

First step - specify the place, where the OpenCV headers are located. Add the path to OpenCV headers to the “Header Search Paths” property:

opencv-include-headers

Second step - set up path where the OpenCV libraries are. Please note: you will need to repeat this step for each configuration (debug/release, device/simulator) because of directory structure of the OpenCV libs. Add path of the OpenCV libraries to the “Library Search Paths” property (for release device this will be “opencv/lib/iphoneos/Release” if you follow directory structure listed above).

Third step: Tell linker to include OpenCV to the output executable:opencv-link-libraries

As you can see i prefer use linker flags instead using XCode UI (Targets -> GLImageProcessing -> Link Binary With Libraries -> Add -> Existing Files...). There are several reasons: i prefer this way because i don't trust XCode :) (Actually because for all my projects i use cross-platform build system which allows to do such things much easies, but this is a topic for another article).

Now, add #include <opencv2/opencv.hpp> to header files . I’ve added this include to Imaging.h header right after #include <OpenGLES/ES1/glext.h>. Crossing fingers and hitting "Build and Run".....Oooops, compilation errors. Let's see, what we can do with all those errors. First of all - change extensions of all .m files which include OpenCV headers to .mm. This tells compiler that such file contains mixed ObjectiveC and C++ code. Also change extensions of all .c files to .cpp, because OpenCV uses STL, which is absent for pure C and thus you'll get compilation errors.

Now, only one compilation error left:

opencv/include/opencv2/core/core.hpp:432: error: statement-expressions are allowed only inside functions
opencv/include/opencv2/core/core.hpp:432: confused by earlier errors, bailing out

These errors are caused by MIN symbol, which is a macro in OpenCV and a function, defined somewhere in UIKit or other frameworks..Simple solution - include OpenCV before iOS frameworks.

So...with all these fixes all builds fine. Now it's time to add some OpenCV code.. Let's change the matrix multiplication code!

File Imaging.cpp

// Matrix Utilities for Hue rotation
static void matrixmult(float a[4][4], float b[4][4], float c[4][4])
{
int x, y;
float temp[4][4];
for(y=0; y&lt;4; y++)
	for(x=0; x&lt;4; x++)
		temp[y][x] = b[y][0] * a[0][x] +
			     b[y][1] * a[1][x] +
                             b[y][2] * a[2][x] +
                             b[y][3] * a[3][x];
for(y=0; y&lt;4; y++)
	for(x=0; x&lt;4; x++)
		c[y][x] = temp[y][x];
}

A little crappy code, isn't it? Let's rewrite it!

// Matrix Utilities for Hue rotation
static void matrixmult(float a[4][4], float b[4][4], float c[4][4])
{
	cv::Mat(4,4,CV_32FC1, c) = cv::Mat(4,4,CV_32FC1, a) * cv::Mat(4,4,CV_32FC1,b);
}

A bit of comments. cv::Mat is a type of OpenCV matrix. We initialize a matrix view, which takes data from the float[4][4] array, but not copy it. Result of multiplication of two views (a and b) assigned to view c which is a result.

Hit "Build and Run", and here we go:

Screenshot 2011.01.12 11.11.45

This is a very simple example which demonstrates that you can use OpenCV even with ObjectiveC without any problems.

Good luck in your projects!

Comments (116) Trackbacks (6)
  1. Sorry for my poor english.

    Thanks very much for this article. But i don’t understand how to include Opencv before ios frameworks? Simplement put the #include before any other include/import in this file .mm?

  2. very nice tutorial. exactly what i was looking for. thx

  3. Hello, i am getting a library error and its just weird. My library path is $(SRCROOT)/opencv/libs/universal/Release and Linker flags are -libopencv_core because my filename is libopencv_core.a but complier says :

    ld: warning: directory ‘opencv/libs/universal/Debug’ following -L not found
    ld: library not found for -libopencv_core
    collect2: ld returned 1 exit status
    Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 failed with exit code 1

    Where do i make mistake? :S

    • Ah it was because of whitespaces…!

      • Hi, thanks for all…really well done!..but..I have the same problem:

        Ld /Users/Darione/Library/Developer/Xcode/DerivedData/GLImageProcessing-denjvkhbarpnimgxncuiuvacfosz/Build/Products/Debug-iphonesimulator/GLImageProcessing.app/GLImageProcessing normal i386
        cd /Users/Darione/Downloads/GLImageProcessing
        setenv MACOSX_DEPLOYMENT_TARGET 10.6
        setenv PATH “/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin”
        /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/g++-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/Darione/Library/Developer/Xcode/DerivedData/GLImageProcessing-denjvkhbarpnimgxncuiuvacfosz/Build/Products/Debug-iphonesimulator -L/Users/Darione/Downloads/GLImageProcessing/opencv/lib/iphonesimulator/Debug -F/Users/Darione/Library/Developer/Xcode/DerivedData/GLImageProcessing-denjvkhbarpnimgxncuiuvacfosz/Build/Products/Debug-iphonesimulator -filelist /Users/Darione/Library/Developer/Xcode/DerivedData/GLImageProcessing-denjvkhbarpnimgxncuiuvacfosz/Build/Intermediates/GLImageProcessing.build/Debug-iphonesimulator/GLImageProcessing.build/Objects-normal/i386/GLImageProcessing.LinkFileList -mmacosx-version-min=10.6 -libopencv_core -Xlinker -objc_abi_version -Xlinker 2 -framework Foundation -framework UIKit -framework OpenGLES -framework QuartzCore -framework CoreGraphics -o /Users/Darione/Library/Developer/Xcode/DerivedData/GLImageProcessing-denjvkhbarpnimgxncuiuvacfosz/Build/Products/Debug-iphonesimulator/GLImageProcessing.app/GLImageProcessing

        ld: library not found for -libopencv_core
        collect2: ld returned 1 exit status
        Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/g++-4.2 failed with exit code 1

        I don’t find my error..because it is not due to whitespaces.

        Dario

  4. Hi, I am ios noob here. I’ve been following several of your posts, and am very appreciative of your efforts to make it easy for people like me to get started with iphone dev.

    I believe I followed your instructions in this post strictly, and everything goes well until I modified matrixmult() with opencv features — before this point i was able to compile the project successfully.

    However once I modify the function and add #include to top of Imaging.cpp, I get 66 linking warnings and 6 linking errors.

    Here’s 2 of the typical warnings:

    ld: warning: unsigned long const& std::min(unsigned long const&, unsigned long const&)has different visibility (default) in opencv_ios_build/lib/debug-iphonesimulator/libopencv_core.a(alloc.o) and (hidden) in /Users/haoest/Development/GLImageProcessing/build/GLImageProcessing.build/Debug-iphonesimulator/GLImageProcessing.build/Objects-normal/i386/Imaging.o
    ld: warning: cv::Mat::MSize::MSize(int*)has different visibility (default) in opencv_ios_build/lib/debug-iphonesimulator/libopencv_core.a(matop.o) and (hidden) in /Users/haoest/Development/GLImageProcessing/build/GLImageProcessing.build/Debug-iphonesimulator/GLImageProcessing.build/Objects-normal/i386/Imaging.o

    And here are all 6 errors:
    Undefined symbols:
    “_gzclose”, referenced from:
    icvClose(CvFileStorage*) in libopencv_core.a(persistence.o)
    “_gzrewind”, referenced from:
    icvRewind(CvFileStorage*) in libopencv_core.a(persistence.o)
    “_gzgets”, referenced from:
    icvGets(CvFileStorage*, char*, int)in libopencv_core.a(persistence.o)
    “_gzeof”, referenced from:
    icvEof(CvFileStorage*) in libopencv_core.a(persistence.o)
    “_gzopen”, referenced from:
    _cvOpenFileStorage in libopencv_core.a(persistence.o)
    “_gzputs”, referenced from:
    icvPuts(CvFileStorage*, char const*)in libopencv_core.a(persistence.o)
    ld: symbol(s) not found
    collect2: ld returned 1 exit status

    Would you be so kind to tell me what I might have done wrong, please?

  5. Hello, while creating libs we selected with ffmpeg but i cant use CvVideoWriter class in my project, which library should i add to linker flags to use that function? i added -lopencv_video but it didnt help :/

  6. I have followed the instructions and everything seems to work really well, apart from the fact I’m having the same error as Borluse:

    opencv/include/opencv2/core/core.hpp:432:0 opencv/include/opencv2/core/core.hpp:432: error: statement-expressions are allowed only inside functions

    I am including like this:

    #include
    #import “GogsViewController.h”

    @implementation GogsViewController

    Any ideas?

    • I removed the includes from the Gogs_Prefix.pch file – I didn’t see how to add opencv2 include in there as I couldn’t rename that to .mm, right?

      Builds lovely now :D

  7. Maybe I’m being dumb but I’m stuck at the third step. Where are you getting those file names from? I have a bunch of files called lib*something* in my opencv/lib/debug-iphoneos and other folders under the lib directory, should i use these filenames instead? there is nothing to do with lopencv_flann or many of the other names shown in the screenshot.

    • I have another problem too, what am I meant to include where? #include right? But in which headers and/or implementations, and why? Thanks.

    • -lopencv_flann tells linker to add static library named “opencv_flann. “. Default lib preffix is “lib” (you can change it in XCode, but it “lib” by default), and static lib extension is “.a”, so writing “-lopencv_flann” will mean add “libopencv_flann.a” to link stage.

      • Okay cheers for that. I don’t have the legacy or contrib library files, and I have a bunch of other files you haven’t linked to. I grabbed the SVN and then used your batch script to make it iPhone compatible. Should I just use the library files I have in my lib folder irregardless of name?

        • Try, at least) Or you can do even simplier – add libraries to “Link with static libs” stage right in the XCode workspace. It’s probably the simpliest way to do this.
          I don’t remember how exactly it’s name, but this build stage definitely contains “Link” word.

  8. Hey could anyone make libraries work with iOS 4.3? I tried to add same libraries but it didnt work, it says
    “opencv_ios_build/include/opencv2/ml/ml.hpp:2075:15: error: map: No such file or directory”. So maybe EKhvedchenya can edit the script for 4.3 :p

  9. Hello, I upgraded to XCode4 and iOS SDK 4.3 and created a new project, did the same things i did before, I got a weird error because of a code written in OpenCV file

    In file included from opencv_build_ios/include/opencv2/opencv.hpp:56,
    from /Volumes/Mac Archive/xx/xx/xx-Prefix.pch:5:
    opencv_build_ios/include/opencv2/ml/ml.hpp:2075:15: error: map: No such file or directory
    opencv_build_ios/include/opencv2/ml/ml.hpp:2076:18: error: string: No such file or directory
    opencv_build_ios/include/opencv2/ml/ml.hpp:2077:20: error: iostream: No such file or directory
    In file included from opencv_build_ios/include/opencv2/opencv.hpp:56,
    from /Volumes/Mac Archive/xx/xx/xx-Prefix.pch:5:
    opencv_build_ios/include/opencv2/ml/ml.hpp:2084: error: expected specifier-qualifier-list before ‘public’
    opencv_build_ios/include/opencv2/ml/ml.hpp:2106: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘CvMLData’
    opencv_build_ios/include/opencv2/ml/ml.hpp:2186: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘cv’

    In ml.hpp line 2075:

    #include
    #include
    #include

    line 2084:
    public:

    where am i doing wrong? library paths seems oke. New XCode has a different folder setup, i put pre-complied libraries to the first folder, it gives error from a header file so paths seems correct, i also added libraries like -lopencv_core. Sorry for bothering i am a student and learning :p

    • I have the same problem. Did you solve it?

      • RTFM :)

        “error: map: No such file or directory” message indicates that compiler found #include
        directive in .m file which is compiled as ObjectiveC module, not ObjectiveC++.

        That’s why i noticed this in post: “change extensions of all .m files which include OpenCV headers to .mm. “

  10. So I managed to build for debug/simulator.
    When I try to compile for debug/devbice it fails with the message :

    ld: library not found for -lopencv_ts
    collect2: ld returned 1 exit status
    Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 failed with exit code 1

    Which is quite logical since opencv_ts seems not to not exists for the device.

    So :
    what is this library ?
    Why does the linker wants it ?
    How do I get rid of this error ?

    THank you in advance

    • Hi! Yes, you are right, opencv_ts is no more present in build since this project depends on google test framework.

      I’ll commit updated template project for XCode 4 really soon. This project is already configured (i’ve set search header directories, added linker instructions).

      Just give me a few hours to polish the template :)

  11. Aloha my new Ukrainian friend!

    Using latest Xcode, followed your instructions. Got several linker problems, which I solved as I will explain. Got a warning for each of the libraries, as follows…

    Apple Mach-O Linker Warning
    Ignoring file opencv/lib/debug-iphoneos/libopencv_core.a, file was built for archive which is not the architecture being linked (armv6)

    Solution: in Project (and/or Targets) change Architecture from Standard (armv6 armv7) to Optimized (armv7).

    With that change, plus adding -lz to the Other Linker Flags line, the OpenCV version of matrixmult in Imagingcpp compiles, links, and runs perfectly.

    Mahalo nui loa! (Thank you very much, in Hawaiian.)

  12. Thanks for posting this – it’s just what I’ve been looking for. However, I’ve hit a small problem. It’s the same problem Haqn had. The issue is in ml.hpp and I’m getting errors like “Map: No such file or directory”, “String: No such file or directory”, “iostream: No such file or directory”, ….

    I’m using The latest release of XCode.

    Any ideas on why?

    • Ok, so I sorted that problem! I hadn’t changed all of my .m files to be .mm instead. However, I’ve got one final error now. core.hpp “statement-expressions are allowed only inside functions”. Any ideas?

  13. Hi I’m having the same problem, but I don’t understand what to do… I’ve the #include as the first Line in my header files, but I still get errors like that:
    …/opencv/include/opencv2/core/core.hpp:432:0
    …/opencv/include/opencv2/core/core.hpp:432: error: statement-expressions are allowed only inside functions

    Please help me :)

  14. Hi again, I’ve solved the problem now by removing my #import commands from Prefix.pch

    But not I’ve got 5 remaining errors:

    “_cvReleaseHaarClassifierCascade”, referenced from:

    -[OpenCV releaseStorageAndCascade] in OpenCV.o

    “_cvCvtColor”, referenced from:

    -[ImageConverter CreateIplImageFromUIImage:] in ImageConverter.o

    “_cvMatchTemplate”, referenced from:

    -[CardDealerView captureOutput:didOutputSampleBuffer:fromConnection:] in CardDealerView.o

    “_cvHaarDetectObjects”, referenced from:

    -[OpenCV detectElementsOn:withCascade:inView:] in OpenCV.o

    “_cvLoadHaarClassifierCascade”, referenced from:

    -[OpenCV detectElementsOn:withCascade:inView:] in OpenCV.o

    ld: symbol(s) not found for architecture armv7

    collect2: ld returned 1 exit status

  15. My Library Search Path:
    opencv/lib/iphoneos/Debug

    My Header Search Path:
    opencv/include

    My Other Linker Flags:
    -lopencv_core
    -lopencv_flann
    -lopencv_legacy
    -lopencv_lapack
    -lopencv_contrib
    -lz
    -zlib

  16. Okay my Problem is solved now, I need some other linker flags for it to run, big THX and great work!

    -lopencv_haartraining_engine
    -lopencv_imgproc
    -lopencv_ml
    -lopencv_objdetect

    • Hi Cristian i have a problem including -lopencv_haartraining_engine infact when i try to add the .a library the app return a warning:

      ld: warning: ignoring file /Users/xxx/…/opencv/lib/debug-universal/libopencv_haartraining_engine.a, file was built for archive which is not the architecture being linked (armv7)
      followed by error on _cvCreateCameraCapture, _cvRetreiveFrame and _cvGrabFrame functions.

      i try to download libopencv_haartraining_engine.a library built for armv7 from github but the result is the same…

  17. Your script ran but the include folder was empty.. I think something broken with the sources..
    i tried with the trunk .. the libraries created successfully but no header files in the include folder.

    Thanks
    Eran

    • It seems that something wrong with opencv sources. I ran my script today against OpenCV trunk revision and all was built fine.
      However i updated build script today (fixing minor bugs).
      If you remove “> /dev/null” string at line 67 in the build script you will get all XCode build process output. It can help locate where the compilation error occurs.

  18. Hi!
    I’m thinking about making a simple image-comparison-app.

    I want to take a photo of for example a simple triangle and then compare it to a triangle in the app and see if they are similiar. Is that possible with the opencv? Do you know any good example for this kind of problem?

    Greetings from Sweden!

    • Hello there!

      Do you intend your algorithm would be scale and rotation invariant (e.g detect similar images even if test image rotated and does not fit all frame)?
      If yes – take a look into feature descriptors (especially SURF or aSIFT)
      If no you can try very simple and fast BRIEF descriptor.
      Also you can try to use face recognition approach – with haar classifier detector and PCA eigen face algorithm for similarity estimation.

      Where to start:
      OpenCV sample demos: find_obj, facedetect

      • Hi and thank you for your quick response!
        The things being photographed will be small geometrical shapes on for example a piece of paper and always fit the frame.

        Do you think this is possible for me to fix with only objective-c knowledge? Or is it over my head?

  19. I think I may have a problem with some of the compiling steps in the script. I have my own project set up correctly as per this tutorial, but in some of my code where I use:

    cvFindFundamentalMat(…);

    I was getting errors relating to contrib3d not being found. Looking in to my folder of compiled libraries I noticed a few of them didn’t actually have the full library files expected (including contrib3d). Here is the ouput when I run the compile script:

    Normally: http://pastie.org/1819008
    With cmake’s > /dev/null on line 67 commented out: http://pastie.org/1819162

    It seems to be a problem with cmake? For now I’ll try grab the libraries from the project, I assume that will work.

  20. I’m using xcode 4, and the setting is different, can you tell me how to make it on xcode 4

  21. Hello,
    Thanks for the nice instructions about integrating OpenCV-2.2.0 to my xCode. I am trying to use some cv functions such as cvLoad(…) and the cvHaarDetectObjects(…), but I am getting an error cvHaarDetectObjects() was not declared in this scope or cvLoad() was not declared in this scope. I probably need to add another linker flag such as -lopencv_haartraining_engine, but I don’t have it as an .a file in my lib directory (I added all the others). How can I create it or what else I can try? I tried dragging the file haarcascade_frontalface_alt_tree.xml into the resources directory, but it did not work.

    I will be very thankful if you can help me with this problem.

    Thanks,
    Nick

    • Hi!
      1) “XXX was not declared in this scope” message is a compiler error and have no common with linker flags. You missing some includes.
      2) cvLoad has not been tested to work on iOS. Just FIY
      3) Haartraining engine is a part of sample application that trains cascade using set of sample images. It does not contain functions you trying to use.

  22. great help at least to kick off

  23. Hey there, thanks for the nice tut. Well i got a problem while building.

    “cv::Mat::deallocate()”, referenced from:
    cv::Mat::release() in Imaging.o
    “cv::operator*(cv::Mat const&, cv::Mat const&)”, referenced from:
    matrixmult(float (*) [4], float (*) [4], float (*) [4])in Imaging.o
    “cv::fastFree(void*)”, referenced from:
    cv::Mat::~Mat() in Imaging.o

    ld: symbol(s) not found
    collect2: ld returned 1 exit status

    Actually i removed -lopencv_lapack from “Other Linker Flags” since i didn’t find that library in any Directory under opencv. Is it creating the problem? Thanks in advance, really i am struggling …..

  24. Strange. Show your “linker flags” option plz.

  25. I get the following link error:

    Undefined symbols for architecture armv7:
    “_cvCalcOpticalFlowPyrLK”, referenced from:
    -[OpenCVTestViewController alignImages:imageB:] in OpenCVTestViewController.o
    ld: symbol(s) not found for architecture armv7

    Is this because highgui is not supported on iOS?

    Many thanks for putting this tutorial together.

  26. Hi there, very nice tut. I quite having problem solving the error User “sasi” had 2 Posts above.

    Getting Linker error while compiling:
    —————–
    Undefined symbols:
    “cv::fastFree(void*)”, referenced from:
    cv::Mat::~Mat() in Imaging.o
    “cv::operator*(cv::Mat const&, cv::Mat const&)”, referenced from:
    matrixmult(float (*) [4], float (*) [4], float (*) [4])in Imaging.o
    “cv::Mat::deallocate()”, referenced from:
    cv::Mat::release() in Imaging.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status
    ———

    Dont know what to do. My Linker flags are:
    -lopencv_core
    -lopencv_flann
    -lopencv_legacy
    -lopencv_lapack
    -lopencv_contrib

    • Looking correct. cv::Mat implementation are in opencv_core module.
      Haven’t tested my demo on XCode 4, by the way. Maybe there are other warnings?
      Also check that the opencv libraries has contains code for the active architecture you building for.

  27. Hi there!
    This site has been extremely helpful, thank you for sharing.
    I was able to implement using the compiled version of the opencv libs but when I tried to use the FAST algorithm (fast corner detection) the linker can’t find the symbol. I also tried looking it up in the libopencv_features2d.a using the ‘nm’ command but it’s not there. Should I compile the libraries again with a special flag to get this function?

    Thanks,
    Samix

    • Hi, thanks :)

      Everything should works exactly as described here. Of course, you are responsible to pass necessary libraries to the linker.

      The additional linker flags option should looks like this:
      “-lopencv_calib -lopencv_contrib -lopencv_core -lopencv_features2d -lopencv_flann -lopencv_imgproc -lopencv_legacy -lopencv_ml -lopencv_objdetect -lopencv_video”

      It passes all OpenCV library to linker. This should works. If not – check the linker output (especially warnings) carefully. Probably it can’t find specified libs in the search directories.

      • Hi again,

        Thanks, but I’ve put all the relevant library I believe, the function “FAST” prototype is in features2d.hpp but the libopencv_features2d.a doesn’t seem to include it.

        I have no warnings. Only this linker error:

        Ld /Users/samisalloum/Library/Developer/Xcode/DerivedData/MyFirstAVApp-brlplviioxnqspequtbzfelpjkgs/Build/Products/Release-iphoneos/MyFirstAVApp.app/MyFirstAVApp normal armv7
        cd /Users/samisalloum/Documents/Projects/MyFirstAVApp
        setenv IPHONEOS_DEPLOYMENT_TARGET 4.3
        setenv PATH “/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin”
        /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/llvm-g++-4.2 -arch armv7 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk -L/Users/samisalloum/Library/Developer/Xcode/DerivedData/MyFirstAVApp-brlplviioxnqspequtbzfelpjkgs/Build/Products/Release-iphoneos -Lopencv/lib/release-iphoneos -F/Users/samisalloum/Library/Developer/Xcode/DerivedData/MyFirstAVApp-brlplviioxnqspequtbzfelpjkgs/Build/Products/Release-iphoneos -filelist /Users/samisalloum/Library/Developer/Xcode/DerivedData/MyFirstAVApp-brlplviioxnqspequtbzfelpjkgs/Build/Intermediates/MyFirstAVApp.build/Release-iphoneos/MyFirstAVApp.build/Objects-normal/armv7/MyFirstAVApp.LinkFileList -dead_strip -lz -lopencv_core -lopencv_flann -lopencv_legacy -lopencv_lapack -lopencv_contrib -lopencv_imgproc -miphoneos-version-min=4.3 -framework Accelerate -framework QuartzCore -framework CoreVideo -framework CoreMedia -framework AVFoundation -framework UIKit -framework Foundation -framework CoreGraphics -o /Users/samisalloum/Library/Developer/Xcode/DerivedData/MyFirstAVApp-brlplviioxnqspequtbzfelpjkgs/Build/Products/Release-iphoneos/MyFirstAVApp.app/MyFirstAVApp

        Undefined symbols for architecture armv7:
        “cv::FAST(cv::Mat const&, std::vector<cv::KeyPoint, std::allocator >&, int, bool)”, referenced from:
        -[CaptureSessionManager opencvFastCornerDetect:] in CaptureSessionManager.o
        ld: symbol(s) not found for architecture armv7
        collect2: ld returned 1 exit status

        • Look at the output you just posted – there is no mention about opencv_features2d library, but it has to be.
          Add the “-lopencv_features2d” :)

          • :) Thanks a lot, at the beginning at I felt a bit silly but I actually did add it in the linker flags but for some reason didn’t work so I added it using the “Targets -> MyProjectName -> Link Binary With Libraries -> Add -> Existing Files…)” and it worked.

            Thanks again, especially for your fast responses :D

  28. Thank you for the information! The manner you displayed the information is absolutely excellent! All of my friends will know about this site!

  29. Hi again!

    I was wondering if you could have a look at this problem I’m having:
    When I add the following definition of a matcher:

    BruteForceMatcher<L2 > matcher;

    I get the following linker error:
    ld: bad codegen, pointer diff in cv::BruteForceMatcher<cv::L2 >::clone(bool) constto global weak symbol cv::DescriptorMatcher::clone_op(cv::Mat) for architecture armv7

    I’m not having any problems using cvCanny or SURF library functions, I didn’t even have any problem defining: cv::SurfDescriptorExtractor extractor;

    Do you have any idea?

    Thanks in advance,
    Sami

  30. Frankly,
    if you were close to me i would kiss you!

    thank you so much

  31. This is golden. You just saved me a ton of time. Very articulate, illustrative and step-by-step. You’re awesome. If I knew where you lived, I would send you some flowers.

  32. Hi,
    have dw your https://github.com/BloodAxe/opencv-ios-template-project
    after compiling its gives following errors + warning on xcode 3.2

    1.
    /work/Examples/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/iOSplusOpenCVAppDelegate.h:15:12 /work/Examples/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/iOSplusOpenCVAppDelegate.h:15:12: error: unknown property attribute ‘strong’

    2.
    /work/Examples/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/main.m:15:3 /work/Examples/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/main.m:15:3: error: unexpected ‘@’ in program

    3.
    /work/Examples/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/ImageProcessingImpl.mm:120:0 /work/Examples/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/ImageProcessingImpl.mm:120: error: ‘__bridge’ was not declared in this scope

    4.
    /work/Examples/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/ImageProcessingImpl.mm:120:0 /work/Examples/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/ImageProcessingImpl.mm:120: error: expected `)’ before ‘CFDataRef’

    please help …

    • The sample project’s minimal requirements is XCode 4.

      • installed xcode 4 Build 4A304a..some errors reduced…but still 2 errors..same one…
        1.
        /Users/mohsinj/Downloads/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/iOSplusOpenCVAppDelegate.h:15:12: error: unknown property attribute ‘strong’ [3]

        2.
        file://localhost/Users/mohsinj/Downloads/BloodAxe-opencv-ios-template-project-5bf9444/iOSplusOpenCV/main.m: error: Parse Issue: Unexpected ‘@’ in program

        its for @autoreleasepool in main.m

        got warning too in prefix.h …
        “This project uses features only available in iOS SDK 5.0 and later.”

        do you have xcode 4 sample prj ? or m i going wrong somewhere??

  33. Hi !

    First, thanks for this tuto, it’s exaclty what I need :) .
    However I have an error I don’t understand.
    When I compile the program GLImageProcessing without openCV, it works. Then I add openCV as you do, I correct the errors (.c in .cpp, .m in .mm, include opencv before ios frameworks) and all is good. But, I have another error :
    “validateTexEnv()” referenced from :
    (list of files in which it appears)
    Symbol(s) not found
    Collect2: ld returned 1 exit status.

    I don’t understand why I get this message. Do you have any idea of the problem?
    Thanks!

    • Hi Steve,

      It’s an undefined reference to function “validateTexEnv” somewhere in the code. I suggest you to search for it in the project.

      PS: There is updated version of OpenCV sample project. It can be found on my github page. I recommend to use it.

      • I ran into the same issue.

        validateTexEnv is defined in the “Debug.c” file contained in the GLImageProcessing project.

        Steve, the reason you’re seeing that is that you’ve followed EK’s instructions above for renaming Imaging.c to have the cpp extension but Imaging.c also includes Debug.h/uses a function defined in Debug.c

        However because of C++ symbol name mangling when you have C++ call a C function you have to either:

        [1] rename Debug.c -> Debug.cpp so that symbols defined in there are mangled similarly

        or

        [2] add an extern “C” around the appropriate c++ code. For example, you could wrap the “include “Debug.h” with an extern “C” block. (i.e. extern “C” { #include “Debug.h” } )

  34. I download your sample and meet a error while compiling:
    Code Sign error: a valid provisioning profile matching the application’s Identifier ‘unnamed.iOSplusOpenCV’ could not be found.
    It seems that no one above meet the same problem, I have no idea how to fix it.
    I am using Xcode Version 4.0.1 Build 4A1006 .
    And I have another question that in folder externalLibs\opencv\lib,only debug and release, where is the device and simulator ? Can it be used for both?

    • Well, change the base SDK, and change a scheme, the Code Sign error will disappear.
      But then, I meet the same problem with Mohsin, whose problem not solved, God help us!

    • It’s fat binaries. They contain both i386, armv6 & armv7 architectures.
      The sample project is written with use of iOS 5 SDK.

      • Thank you for your answer, now I know why I can’t run your sample, by follow your instruction, I can use some opencv function now.
        But have you ever try to use libface( a open free library that used opencv for face recognition) in IOS, I tried my best but can’t, because this library uses a lot of function that disabled in IOS, so I tried to pick out the face recognition module, finally, I found that the key function cvCalcEigenObejcts can’t be used, once I include the the statement-expressions error appears, I use instead. But I find that I can’t use “new”, then I change the file extension from m to mm, and the statement-expressions error comes agagin. Anyway, forget it.

        My last request is can you offer us the opencv library that with simulator and device separated(Release is enough)? I don’t want the fat binaries(more that 100M, this is crazy).

        • Hi, right now i can’t do this because my iOS developer program has been expired and the renewal process is pretty slow for Ukrainian citizens :/.
          So until Apple process my request i can’t help you with that.
          However you can use my OpenCV build script to create separate binaries.

  35. hello, now i encounter a very strage problem,when copy the file,it will be broke,it can’t find the opencv lib and header,such as this no such file ,it can’t find it ,i don’t know why ,please help me…

    • What are you talking about? Can you be more specific in details?

      • the question is ,there are a project ,and it had Configuration with opencv ,it works,but if i copy it ,and then open the file ,it always say it can’t find the header,#impotr #improt,i really don’t know why ,it the same with the original file,but i open it ,the problem will be happen,can u help me? i have tried many times ,the i recomve all the opencv ,and restart configurate the opencv ,it still broke ,can find the header

  36. EKhvedchenya,are u here,can u give me the answaer,the question has confused me very long time ,i can’t copy the file ,and there are another question ,i download the project from github,the opencv configuration is correct ,but when i build it ,it always say can’t find the heaer opencv2/imgproc/imgproc_c.h opencv2/objdetect/objdetect.hpp
    i really don’t know why ,pls help me

  37. EKhvedchenya,wait for u。。。

  38. i have solving it,thanks

  39. dear all,

    i have tried to set up this example with the acutel GLImageProcessing code from the apple website. but something goes wrong. the build fails with “map” file not found in the ml.hpp of the opencv. i saw that one of you has a problem with a similar error but i renamed the file which includes the opencv header fromm .c to .cpp and .m to .mm. in this case i renamed Debug.c to Debug.cpp, Imaging.c in Imaging.cpp and Texture.m in Texture.mm. the renaming i have tried in the xcode project view and also in finder and include them again in the project.
    everything fails, could somebody help me please?

    • okay, i renamed every .m file or .c or .cpp to .mm, so addtionally i have now EAGLView.mm, ViewController.mm, Debug.mm and main.mm. and it seem like ViewController could be with the ending .m and the main also. so now it should running, but why i need Debug.mm i dont understand. :-)

  40. Hi,
    I am searching for some help on ‘face detection through objective c’. All posts i googled talks about detection but no one talks bout how its done for objective C. Can any body throw some light on it.

    Thanks in advance

  41. thank you very much for this posting, i got stuck in compiling c++ headers in .mm file. but locating opencv pre-compile headers before iOS frameworks and then magic happened.. thank you very much..

  42. Hi, i m new with opencv and i try to run some simple code in eclipse but i get this error:

    Building target: RGBToGray
    Invoking: GCC C++ Linker
    g++ -L/usr/local/lib/ -o”RGBToGray” ./RGBToGray.o -lopencv_highgui -lopencv_imgproc -lopencv_video -lopencv_flann -lopencv_features2d -lopencv_objdetect -lopencv_ml -lopencv_legacy -lopencv_calib3d -lopencv_contrib -lopencv_imgproc
    /usr/bin/ld: ./RGBToGray.o: undefined reference to symbol ‘cv::fastFree(void*)’
    /usr/bin/ld: note: ‘cv::fastFree(void*)’ is defined in DSO /usr/local/lib/libopencv_core.so.2.3 so try adding it to the linker command line
    /usr/local/lib/libopencv_core.so.2.3: could not read symbols: Invalid operation
    collect2: ld returned 1 exit status
    make: *** [RGBToGray] Error 1

    I added c++ linker path as /usr/local/lib and i don’t get it. Please help me?

  43. I’ve got 2 errors…
    cxoperations.hpp – Semantic issue: No viable overloaded ‘=’
    //Mat::operator = (m);
    cxmat.hpp – Semantic issue: Call to non-static member function without an object argument
    //r = Range(0, d.size());

    How can I get rid of that?
    Thanks very much!

    • o, btw, it is strange that there are no errors running on Xcode 3.2.6, but the above 2 errors come out when compiling on Xcode 4.3 @@
      and although it can be built successfully on Xcode 3.2.6, the app just quit itself immediately just after launched, I wonder what the problem is…

      Any help from you is appreciated, thanks again!

      • hello, I met with the same issue with you, have you solved?

        • have been dealing with so many errors these days… if i remember correctly, the solutions for the semantic issues should be
          1. change the extension of source files in which the OpenCV framework is used or imported from ‘.m’ to ‘.mm’. (This tells the compiler that the file includes mixed Objective-C and C++ code.)
          2. In Project settings, switch to “LLVM GCC 4.2 compiler”.

          Though it’s a bit too late…. Hope it is helpful for you! =]

  44. What the need of openCV here in this app?
    I downloaded the GLImageProcessing sample demo from Apple and just run it in xcode without making any changes and got the same result that you shown in this post.
    Brightness, Contrast and all other works fine on scroll.
    So I can’t figure out why you added openCV in this project.
    I will be pleased if you can clear this doubt of mine.


Leave a comment

(required)