形态学处理
1. 灰度化与二值化
这个在opencv中实现起来十分简单
cvtColor(src,temp, COLOR_BGR2GRAY); threshold(temp,temp, 0, 255, THRESH_OTSU); 复制代码
当然二值化效果是否理想,阈值选取是否恰当还是要根据imshow
二值化后的图来调整的。
2. 形态学操作
关于形态学的一些基本操作,比如腐蚀、膨胀、开运算(先腐蚀后膨胀),闭运算(先膨胀后腐蚀) ……这些已经有很多博客介绍了,我这里就简单总结一些复合运算的特点。
- 开运算可以去除图像周围边缘的瑕疵、噪音
- 闭运算可以去除图像内部的缺失点、噪音
3. 利用形态学取样
如何我们需要得到水平向的元素,那我们选择的结构元素就是水平的,然后开运算滤掉竖直向;反之也是一样
如果遇到更复杂的情况,可以先选出不需要的,然后图像作差直接去掉这部分,然后再选取,这样效果就会好很多。
4. 代码部分
#include <iostream> #include<opencv2/opencv.hpp> #include<opencv2/highgui.hpp> #include<opencv2/imgproc.hpp> using namespace std; using namespace cv; void work1() { Mat src = imread("D:/3/7_1.jpg"); Mat temp,result; Mat element = getStructuringElement(MORPH_RECT, Size(15,15),Point(-1,-1)); cvtColor(src,temp, COLOR_BGR2GRAY); threshold(temp,temp, 0, 255, THRESH_OTSU); morphologyEx(temp, result, MORPH_CLOSE, element, Point(-1, -1), 1); imshow("7_1.jpg", src); imshow("result7_1", result); } void work2() { Mat src = imread("D:/3/7_2.jpg"); Mat temp, result; Mat element = getStructuringElement(MORPH_RECT, Size(15, 15), Point(-1, -1)); cvtColor(src, temp, COLOR_BGR2GRAY); threshold(temp, temp, 0, 255, THRESH_OTSU); morphologyEx(temp, result, MORPH_OPEN, element, Point(-1, -1), 1); imshow("7_2.jpg", src); imshow("result7_2", result); } void work3() { Mat src = imread("D:/3/7_3.jpg"); Mat temp, result; Mat element = getStructuringElement(MORPH_RECT, Size(15, 15), Point(-1, -1)); cvtColor(src, temp, COLOR_BGR2GRAY); threshold(temp, temp, 0, 255, THRESH_OTSU); morphologyEx(temp, result, MORPH_CLOSE, element, Point(-1, -1), 1); imshow("7_3.jpg", src); imshow("result7_3", result); } void work4() { Mat src = imread("D:/3/7_4.jpg"); Mat temp, result; Mat element = getStructuringElement(MORPH_RECT, Size(1,5), Point(-1, -1)); cvtColor(src, temp, COLOR_BGR2GRAY); threshold(temp, temp, 0, 255, THRESH_OTSU); morphologyEx(temp, result, MORPH_OPEN, element, Point(-1, -1), 1); imshow("7_4.jpg", src); imshow("result7_4", result); } void work5() { Mat src = imread("D:/3/7_5.jpg"); Mat temp,dst, result; Mat element0= getStructuringElement(MORPH_RECT, Size(1,20), Point(-1, -1)); Mat element1 = getStructuringElement(MORPH_RECT, Size(20,1), Point(-1, -1)); cvtColor(src, temp, COLOR_BGR2GRAY); //去除竖向线条 morphologyEx(temp,dst, MORPH_OPEN, element0, Point(-1, -1), 1); temp = temp - dst; morphologyEx(temp, result, MORPH_OPEN, element1, Point(-1, -1), 1); imshow("7_5.jpg", src); imshow("result7_5", result); } int main() { work1(); work2(); work3(); work4(); work5(); waitKey(0); return 0; } 复制代码