很多实际的项目中都会遇到线的提取。比如航拍图片中的电缆线提取,道路交通中的标记线提取(自动驾驶会用到),航母上飞机跑道线的提取等。非常实用也非常重要
原理方法:
图像形态学操作的时候,可以通过自定义的结构元素实现结构元素对输入图像的一些对象敏感、另外一些对象不敏感,这样就会让敏感的对象改变而不敏感的对象保留输出。通过使用两个最基本的心态学操作——膨胀和腐蚀,使用不同的结构元素对输入图像的操作、得到想要的结果。
膨胀——输出像素值是结构元素覆盖下输入图像的最大像素值
腐蚀——输出像素值是结构元素覆盖下输入图像的最小像素值
提取步骤:
1、输入灰度彩色图像imread
2、转换为灰度图像cvtColor
3、转换成二值图像adaptiveThreshold
4、定义结构元素
5、开操作提取 水平线和垂直线
#include
#include
#include
using namespace cv;
const String path = "H:\\c++opencv\\提取水平和垂直线\\lines.png";
const String Output_Window = "Output_window";
Mat src = imread(path, IMREAD_REDUCED_COLOR_2);
Mat dst, dst2;
int main(int argc, char**argv) {
if (!src.data)
{
printf("Could not load the demo image...");
return false;
}
namedWindow("Source Pic", CV_WINDOW_AUTOSIZE);
imshow("Source Pic", src);
cvtColor(src, dst, CV_BGR2GRAY);
adaptiveThreshold(~dst, dst2, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 13, -2);
int xpoint = 11;
int ypoint = 11;
Mat dst3,dst4;
Mat hkerne = getStructuringElement(MORPH_RECT, Size(xpoint, 1), Point(-1, -1));
Mat vkerne = getStructuringElement(MORPH_RECT, Size(1, ypoint), Point(-1, -1));
morphologyEx(dst2, dst3, MORPH_OPEN, hkerne, Point(-1, -1), 1, 0);
namedWindow("H_MORPH_OPEN Pic", CV_WINDOW_AUTOSIZE);
imshow("H_MORPH_OPEN Pic", dst3);
morphologyEx(dst2, dst4, MORPH_OPEN, vkerne, Point(-1, -1), 1, 0);
namedWindow("VMORPH_OPEN Pic", CV_WINDOW_AUTOSIZE);
imshow("VMORPH_OPEN Pic", dst4);
waitKey(0);
return 0;
}
原图:
提取水平线:
提取垂直线: