获取图片中对象轮廓并替换白色
// // ViewController.m // opencvTest // // Created by mac on 2020/7/16. // Copyright © 2020 mac. All rights reserved. // #import <opencv2/opencv.hpp> #import <opencv2/imgcodecs/ios.h> #import <opencv2/imgproc.hpp> #import <opencv2/core/types.hpp> #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) UIImageView *imageView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.imageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; self.imageView.contentMode = UIViewContentModeScaleAspectFit; [self.view addSubview:self.imageView]; self.imageView.image = [self.class opencvImageEdge:[UIImage imageNamed:@"888"]]; } // 填充Holes void fillHole(const cv::Mat srcBw, cv::Mat &dstBw) { cv::Size m_Size = srcBw.size(); cv::Mat Temp = cv::Mat::zeros(m_Size.height + 2, m_Size.width + 2, srcBw.type());//延展图像 srcBw.copyTo(Temp(cv::Range(1, m_Size.height + 1), cv::Range(1, m_Size.width + 1))); floodFill(Temp, cv::Point(0, 0), cv::Scalar(255)); cv::Mat cutImg;//裁剪延展的图像 Temp(cv::Range(1, m_Size.height + 1), cv::Range(1, m_Size.width + 1)).copyTo(cutImg); dstBw = srcBw | (~cutImg); } /// 图片边缘检测 /// @param srcImage 原始图片 + (UIImage *)opencvImageEdge:(UIImage *)srcImage { //加载图片 cv::Mat mat_image_src; UIImageToMat(srcImage, mat_image_src); //创建和mat_image_src同样大小的OpenCV图片(Mat) cv::Mat mat_image_dst; mat_image_dst.create(mat_image_src.size(), mat_image_src.type()); //将图片进行灰度处理(图片变为灰色) cv::Mat mat_image_gray; cvtColor(mat_image_src, mat_image_gray, cv::COLOR_BGR2GRAY); //使用3*3内核来降噪处理 cv::Mat mat_image_edge; blur(mat_image_gray, mat_image_edge, cv::Size2i(3, 3)); //进行Canny算子处理 // 30 20对应的参数可做调整,对轮廓的获取有很大的帮助 // Canny(mat_image_edge, mat_image_edge, 30, 20, 3); Canny(mat_image_edge, mat_image_edge, 30, 20, 3); //【4】膨胀操作, 填充边缘缝隙 cv::Mat element = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); for (int i = 0;i < 3;i++) { dilate(mat_image_edge, mat_image_edge, element); } // 【5】Holes填充 for (int i = 0;i < 10;i++) // 填充10次 { fillHole(mat_image_edge, mat_image_edge); } //将OpenCV图片->转成iOS图片 return MatToUIImage(mat_image_edge); } @end
参照文章地址:
https://blog.csdn.net/guguant/article/details/54428817
https://github.com/EdenmsX/OpenCVTest/blob/master/OpenCVTestDemo/OpenCVTestDemo/OpenCVImageUtils.mm
其他
https://www.cnblogs.com/mangoroom/p/11128738.html opencv滤镜用法
https://zhuanlan.zhihu.com/p/85813603
https://www.jianshu.com/p/3aa810b35a5d