Swift 4: Installing OpenCV in iOS by CocoaPods
- Johnny Lee
- Dec 17, 2017
- 2 min read
Thank you for the guidelines from Boris, we can install OpenCV framework in iOS for image detection. However in my case I have encountered some problems that you may facing now. So here is my step by step guide showing how to install openCV is Xcode project.
1) Install CocoaPods
Just in case you don't know what is CocoaPods, install follow the guidelines here.
2) Add OpenCV into Podfile
Open the <your-project-name>.xcworkspace, go to the Podfile, add OpenCV in it.
3) Install OpenCV into your project
Go to your project directory, type "pod install" to install the framework according to the Podfile.
4) Form a Wrapper for OpenCV
As the OpenCV Framework is writing in C++, so we need to wrap it in a Objective-C++ file, in order to make Xcode recognize the API calls.
4.1) Form Wrapper File

Create a new Cocoa Touch Class called "OpenCVWrapper" like the image shown. A dialog will be shown to ask whether you would like to create a bridging header as well. Press "Creating Bridging Header".

The class inherits NSObject and written in Objective-C. Wait, dont you ask me to create a class in Objective-C++ ? Yes. Therefore, after creating the class, simply change the prefix of "OpenCVWrapper.m" to "OpenCVWrapper.mm" to make a Objective-C++ class.

5) Import the Wrapper Class in the Bridging Header
Go to "<your-project-name>-Bridging-Header.h", import the Wrapper in order to le swift can know it can call the methods in "OpenCVWrapper.h"
6) Import the OpenCV Library into the wrapper
Import the library in "OpenCVWrapper.mm". According to the issue here, REMEMBER TO IMPORT THE LIBRARY BEFORE THE HEADER FILE. Now you can use the library of openCV from the wrapper File!
7) Done !
You can test the wrapper class according to the step 7 of Boris article as mentioned. Have fun !
Comments