# include<stdio.h>
# include<stdlib.h>
# include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat source = imread("C:\\Users\\93970\\Desktop\\马萨诸塞州影像成果\\本文算法成果挑选\\深度学习结果\\细化\\细化5.png", 0);
Mat road_location = Mat::zeros(source.size(), CV_8UC1);
for (int i = 0; i < source.rows; i++)
{
for (int j = 0; j < source.cols; j++)
{
if (source.ptr<uchar>(i)[j] > 0)
road_location.ptr<uchar>(i)[j] = 1;//道路部分为1;
}
}
int neighbor_x[8] = { -1,-1,-1,0,0,1,1,1 };
int neighbor_y[8] = { -1,0,1,-1,1,-1,0,1 };
vector<CvPoint> extrem_points;
//寻找非影像边界端点,边界范围控制在4
for (int i = 4; i < road_location.rows-4; i++)
{
for (int j = 4; j < road_location.cols-4; j++)
{
if (road_location.ptr<uchar>(i)[j] == 1)
{
int neighbor_num = 0;
for (int k = 0; k < 8; k++)
{
CvPoint site = CvPoint(i + neighbor_x[k], j + neighbor_y[k]);
if (road_location.ptr<uchar>(site.x)[site.y] == 1)
++neighbor_num;
}
if (neighbor_num == 1)
{
extrem_points.push_back(CvPoint(i,j));//非影像边界端点
}
}
}
}
for (auto &element : extrem_points)
road_location.ptr<uchar>(element.x)[element.y] = 3;//将端点设置为3
//创建含有端点的线段:线段终点为八邻域大于3的或者长度大于7的为
vector<vector<CvPoint>> extrem_lines;
CvPoint temp;
for (auto &element : extrem_points)
{
vector<CvPoint> grow_buff;
int line_length = 1;
grow_buff.push_back(CvPoint(element.x, element.y));
int flag = 0;
for (int z = 0; z < grow_buff.size(); z++)//******重要步骤****
{
for (int q = 0; q < 8; q++)
{
temp = CvPoint(grow_buff[z].x + neighbor_x[q], grow_buff[z].y + neighbor_y[q]);
if (road_location.ptr<uchar>(temp.x)[temp.y] == 1)
{
road_location.ptr<uchar>(temp.x)[temp.y] = 2; //使用过的点标记为2;
grow_buff.push_back(temp);
line_length++;
if (line_length ==8)//当长度等于8时,加入集合
{
extrem_lines.push_back(grow_buff);
flag = 1;
}
if (flag == 1)
{
flag = 2;
break;
}
}
}
if (flag == 2)
break;
}
}
//将单通道影像改为3通道
Mat three = Mat::zeros(source.size(), CV_8UC3);
vector<Mat> sigle;
for (int i = 0; i < 3; i++)
{
sigle.push_back(source);
}
merge(sigle, three);
imwrite("three.png", three);
//展示提取结果
for (auto &element : extrem_lines)
{
for (int i = 0; i < element.size(); i++)
{
three.ptr<Vec3b>(element[i].x)[element[i].y] = { 0,0,255 };
}
}
imwrite("extrem_line.png", three);
return 0;
}