人工智能iOS开发经验收集图像识别

【IOS】OpenCV摄像头实时图像处理(灰度,二值化,轮廓检测

2017-05-15  本文已影响1835人  雨影

关于 OpenCV的集成请看这一篇文章http://www.jianshu.com/p/c51ceb85e64e
初始化方法:

    self.videoCamera = [[CvVideoCamera alloc] initWithParentView:self.imageView];
    self.videoCamera.delegate = self;
    self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
    self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPreset640x480;
    self.videoCamera.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationPortrait;
    //self.videoCamera.rotateVideo =YES; //设置是旋转
    self.videoCamera.defaultFPS = 30;
    [self performSelector:@selector(open:) withObject:nil afterDelay:0.1];

要注意`` [self performSelector:@selector(open:) withObject:nil afterDelay:0.1];
这个方法中执行打开摄像头的操作,否则会出现摄像头画面旋转90的情况.不知道什么原因.

- (IBAction)open:(id)sender {
    [self.videoCamera start];
}

修改显示效果在此方法中写处理方法-(void)processImage:(cv::Mat &)image ``

IMG_0434.PNG

二值化处理

     cv::Mat gray;
     cv::cvtColor(image, gray, CV_BGR2GRAY);// 转换成灰色
     //6.使用灰度后的IplImage形式图像,用OSTU算法算阈值:threshold
     IplImage grey = gray;
     unsigned char* dataImage = (unsigned char*)grey.imageData;
     int threshold = Otsu(dataImage, grey.width, grey.height);
     printf("阈值:%d\n",threshold);
     //7.利用阈值算得新的cvMat形式的图像
     cv::threshold(gray, image, threshold, 255, cv::THRESH_BINARY);

IMG_0435.PNG

灰度

    cv::cvtColor(image, image, CV_RGBA2GRAY);

IMG_0432 2.PNG

轮廓提取

  cv::Mat   canny_output;//临时变量和目标图的定义
     cv::Mat midImage(self.imageView.bounds.size.height, self.imageView.bounds.size.width, CV_8UC1);
     //图像处理
     cvtColor(image,midImage,CV_BGR2GRAY,3);//将图像转化为灰度图
     //GaussianBlur(midImage,midImage,cv::Size(3,3),0,0); //高斯模糊
     blur(midImage, midImage,cv::Size(3,3));
     Canny(midImage, canny_output, 80,255 );//
     
     //轮廓提取
     std::vector<std::vector<cv::Point>> contours;
     findContours(canny_output,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
     //轮廓拣选
     
     image.setTo(cv::Scalar(0,255,0,0),canny_output);
IMG_0433.PNG

背景设为白色的轮廓提取

   // 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, 60);
     // Fill image with white color
     image.setTo(cv::Scalar::all(255));
     // Change color on edges
     image.setTo(cv::Scalar(0,128,255,255),edges);
上一篇下一篇

猜你喜欢

热点阅读