我尝试了Core.hpp, Base.hpp header must be compiled as C++错误。
我将BITCODE设置为NO

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

@interface OpenCV : NSObject
    /// Converts a full color image to grayscale image with using OpenCV.
+ (nonnull UIImage *)cvtColorBGR2GRAY:(nonnull UIImage *)image;
+ (cv::Mat)cvMatFromAdjustedUIImage:(UIImage *)image;
+ (cv::Mat)cvMatFromUIImage:(UIImage *)image;
+ (cv::Mat)cvMatGrayFromUIImage:(UIImage *)image;
+ (cv::Mat)cvMatGrayFromAdjustedUIImage:(UIImage *)image;
@end

在我的OpenCVSample.mm中,我在 header 中包含了#import "OpenCV.h

Git:https://github.com/n1tesh/OpenCV-Demo

最佳答案

您需要的是预编译头文件。在包含内容的.xcodeproj文件的同一文件夹中创建PrefixHeader.pch文件:

#ifndef PrefixHeader_pch
#define PrefixHeader_pch

#ifdef __cplusplus
#include "opencv2/opencv.hpp"
// include other opencv2 headers if needed.
#endif

#endif /* PrefixHeader_pch */

然后转到Project的Build Settings,搜索Prefix Header并将其设置为PrefixHeader.pch

此外,如果要将桥MMOpenCVHelper.h调用为您的快速代码,则它必须仅是Objective-C++。将任何OpenCV或标准C++放入MMOpenCVHelper.mm中。例如:

MMOpenCVHelper.h :
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

// These two headers god to mm file
// #include <opencv2/imgproc/imgproc.hpp>
// #include <opencv2/highgui/highgui.hpp>


@interface MMOpenCVHelper : NSObject
+ (UIImage *) applyOpenCVTo: (UIImage*) uiImage;

// these methods have to be in mm file, hence private
// + (UIImage *)UIImageFromCVMat:(cv::Mat)cvMat;
// + (cv::Mat)cvMatFromAdjustedUIImage:(UIImage *)image;
// + (cv::Mat)cvMatFromUIImage:(UIImage *)image;
// + (cv::Mat)cvMatGrayFromUIImage:(UIImage *)image;
// + (cv::Mat)cvMatGrayFromAdjustedUIImage:(UIImage *)image;


@end

以及 MMOpenCVHelper.mm :
#import "MMOpenCVHelper.h"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

@implementation MMOpenCVHelper

// implementation of public methods:
+ (UIImage *) applyOpenCVTo: (UIImage*) uiImage{
    cv::Mat cvFrame = [MMOpenCVHelper cvMatFromAdjustedUIImage: uiImage];
    // do something with cvFrame using OpenCV
    cv::Mat ret = cvFrame.clone();

    return [MMOpenCVHelper UIImageFromCVMat: ret];
}

// Implementations of the conversion functions:
+ (UIImage *)UIImageFromCVMat:(cv::Mat)cvMat{
    // do something here
    return uiImage;
}

+ (cv::Mat)cvMatFromAdjustedUIImage:(UIImage *)image;
+ (cv::Mat)cvMatFromUIImage:(UIImage *)image;
+ (cv::Mat)cvMatGrayFromUIImage:(UIImage *)image;
+ (cv::Mat)cvMatGrayFromAdjustedUIImage:(UIImage *)image;
@end

稍后,您可以在SomeSwiftFile.swift中进行操作(请验证一下,因为我对Swift不太熟悉):
let UIImage * processedImage = MMOpenCVHelper.applyOpenCVTo(uiImage);

07-27 14:42