Home > AI > Language > Swift >

integrate OpenCV into Swift


Step 1: Download opencv2.framework from the OpenCV website.

Step 2: Drag the framework into your Xcode project. You can check in the Build Phrases / Link Binary with Libraris / opencv2.framework.

You need to add other frameworks to support the opencv2, such as

Accelerate.framework

CoreFoundation.framework

CoreMedia.framework

CoreGraphics.framework

Build Settings / Framework Search Paths / $(PROJECT_DIR)/

Step 3: Create the Objective-C++ files

Wrapper.h

Wrapper.mm (You can check whether the file type is Objective-C++)

Xcode will create the Bridging-Header.h file also.

Following is the test codes.

Wrapper.h

#ifndef Wrapper_h
#define Wrapper_h
#import <Foundation/Foundation.h>

@interface Wrapper: NSObject
+ (NSString *)openCVVersionString;
@end

#endif /* Wrapper_h */

Wrapper.mm

#import "Wrapper.h"
#import <opencv2/opencv.hpp>

@implementation Wrapper : NSObject

+ (NSString *)openCVVersionString {
return [NSString stringWithFormat:@"OpenCV Version %s",  CV_VERSION];
}

@end

Bridging-Header.h

#include "Wrapper.h"

Step 4: Add PrefixHeader.pch

#ifdef __cplusplus
#include <opencv2/opencv.hpp>
#endif

Build Settings / Prefix Header / ${PROJECT_DIR}/PrefixHeader.pch

Step 5: test

print("\(OpenCVWrapper.openCVVersionString())")

Leave a Reply