OpenCV——八邻域断点检测由CSDN点云侠原创,爬虫自重。如果你不是在点云侠的博客中看到该文章,那么此处便是不要脸的爬虫。
??首先将图像进行二值化,然后检测以 P 1 P_1 P1?为中心的它的八个领域,
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
vector<Point> breakImage(Mat& src);
int main()
{ // 加载RGB图片
Mat colorImage, grayImage, binImage;
colorImage = imread("2.png");
// 显示图片
namedWindow("原始图像", cv::WINDOW_NORMAL); // 图像窗口函数
imshow("原始图像", colorImage);
// 图像二值化
cvtColor(colorImage, grayImage, COLOR_BGR2GRAY);
threshold(grayImage, binImage, 1, 255, THRESH_BINARY);
vector<Point>P;
P = breakImage(binImage);
int nsize = P.size();
Mat temp = Mat::zeros(binImage.size(), CV_8UC3);
// 用圆圈出端点
for (int i = 0; i < nsize; i++)
{
circle(temp, P[i], 10, Scalar(0, 255, 0));
}
Mat circleadd;
addWeighted(temp, 1, colorImage, 1, 0, circleadd);
imwrite("端点.png",circleadd);
namedWindow("circleadd", cv::WINDOW_NORMAL);
imshow("circleadd", circleadd);
waitKey(0);
}
#pragma region//8邻域提取端点
vector<Point> breakImage(Mat& src)
{
vector<Point> pointxy;
Point ptPoint;
Size size = src.size();
int nSize;
for (int i = 1; i < size.height - 1; i++)
{
uchar* dataPre = src.ptr<uchar>(i - 1);
uchar* dataCurr = src.ptr<uchar>(i);
uchar* dataNext = src.ptr<uchar>(i + 1);
for (int j = 1; j < size.width - 1; j++)
{
// p9 p2 p3
// p8 p1 p4
// p7 p6 p5
int p1 = dataCurr[j];
if (p1 != 255) continue;
int p2 = dataPre[j];
int p3 = dataPre[j + 1];
int p4 = dataCurr[j + 1];
int p5 = dataNext[j + 1];
int p6 = dataNext[j];
int p7 = dataNext[j - 1];
int p8 = dataCurr[j - 1];
int p9 = dataPre[j - 1];
if (p1 == 255)
{
if ((p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) == 255)
{
ptPoint.x = j;
ptPoint.y = i;
pointxy.push_back(ptPoint);
printf("端点的坐标为:x:%d y:%d\n", j, i);
}
}
}
}
nSize = (int)pointxy.size();
printf("提取端点个数:%d\n", nSize);
return pointxy;
}
#pragma endregion
[1] 八邻域断点检测
[2] OpenCV 八领域断点检测+断点缺陷修补