OpenCV是一个用C++编写的框架.苹果reference强告诉我们
不能直接将C++代码导入SWIFT.相反,为C++代码创建Objto-C或C包装器.
因此,您不能直接在快速项目中导入和使用OpenCV,但这实际上并不坏,因为您需要继续使用整个网络中完全有文档记录的框架的C++语法.
那你该怎么做呢?
OpenCVWrapper.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface OpenCVWrapper : NSObject
+ (UIImage *)processImageWithOpenCV:(UIImage*)inputImage;
@end
OpenCVWrapper.mm(对Objective-C使用文件->;新建…向导,并将.m文件重命名为.mm)
#include "OpenCVWrapper.h"
#import "UIImage+OpenCV.h" // See below to create this
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
@implementation OpenCVWrapper : NSObject
+ (UIImage *)processImageWithOpenCV:(UIImage*)inputImage {
Mat mat = [inputImage CVMat];
// do your processing here
...
return [UIImage imageWithCVMat:mat];
}
@end
作为创建新类(例如示例OpenCVWrapper)的替代方案.h/mm您可以使用Objective-C类别,通过OpenCV功能扩展现有的Objective-C类.例如UIImage+OpenCV类别:
UIImage+OpenCV.h
#import <UIKit/UIKit.h>
#import <opencv2/opencv.hpp>
@interface UIImage (OpenCV)
//cv::Mat to UIImage
+ (UIImage *)imageWithCVMat:(const cv::Mat&)cvMat;
- (id)initWithCVMat:(const cv::Mat&)cvMat;
//UIImage to cv::Mat
- (cv::Mat)CVMat;
- (cv::Mat)CVMat3; // no alpha channel
- (cv::Mat)CVGrayscaleMat;
@end
UIImage+OpenCV.mm
见https://github.com/foundry/OpenCVSwiftStitch/blob/master/SwiftStitch/UIImage%2BOpenCV.mm
通过导入我们新创建的包装器(#import "OpenCVWrapper.h"
),更新Bridging-Header,使您创建的所有Objective-C++类可供Swift使用
在Swift文件中使用包装器:
let image = UIImage(named: "image.jpeg")
let processedImage = OpenCVWrapper.processImageWithOpenCV(image)
bridge header中包含的所有Objective-C++类都可以直接从Swift获得.