OpenCV3.4.1集成到iOS - 实现一个实时边缘检测功能的APP

@hanq  2018年03月16日 17:05

实现一个实时边缘检测功能的APP

参考网络上的资源,OpenCV集成入门篇,实现一个实时边缘检测功能的APP,类似于漫画风格相机的功能。

下载SDK

OpenCV平台的relase支持Win,iOS,Android平台的SDK支持,点击这里下载最新的SDK

集成SDK

  • 解压缩得到.framework文件。以3.4.1为例,这里会下载到文件opencv-3.4.1-ios-framework.zip,解压缩得到opencv2.framework
  • Xcode中新建iOS项目
  • 右击Xcode项目文件,选择Add Files to将解压到.framework加入到项目中
  • 配置项目属性Build Settings,将Enable Bitcode改为NO
  • 配置Info.plist文件,增加相机权限申请
    <key>NSCameraUsageDescription</key>
    <string>开启摄像头以获取视频数据</string>
  • 预编译文件引入头文件,配置PrefixHeader.pch文件,并填写如下内容
    #ifdef __cplusplus
    #include "opencv2/opencv.hpp"
    #endif
  • ViewController.m修改文件名为ViewController.mm,并引入头文件:
    #import <opencv2/videoio/cap_ios.h>
    #import <opencv2/imgproc/types_c.h>
    #import <opencv2/imgcodecs/ios.h>
  • 增加属性对象
    @property (weak, nonatomic) IBOutlet UIImageView *imageView;
    @property (nonatomic,strong) CvVideoCamera *videoCamera;
  • 实现CvVideoCameraDelegate代理
    - (void)processImage:(cv::Mat &)image{
        
        cv::Mat gray;
        
        // Convert the image to grayscale;
        cv::cvtColor(image, gray, CV_RGBA2GRAY);
        
        // Apply Gaussian filter to remove small edges
        cv::GaussianBlur(gray, gray, cv::Size(5,5), 1.2,1.2);
        
        // Calculate edges with Canny
        cv::Mat edges;
        
        cv::Canny(gray, edges, 0, 80);
        
        // Fill image with white color
        image.setTo(cv::Scalar::all(255));
        
        // Change color on edges
        image.setTo(cv::Scalar(0,128,255,255),edges);
        
        // Convert cv::Mat to UIImage* and show the resulting image
        self.imageView.image = MatToUIImage(image);
    }
  • viewDidLoad中实现初始化
    self.videoCamera = [[CvVideoCamera alloc] initWithParentView:self.imageView];
    self.videoCamera.delegate = self;
    self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
    self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPreset640x480;
    self.videoCamera.rotateVideo = YES;
    self.videoCamera.defaultFPS = 30;
    
    [self.videoCamera start];
  • 切换成真机查看效果

运行环境

  • macOS High Sierra 10.13.3
  • Xcode 9.2
  • OpenCV 3.4.1

参考资料


添加新评论