由端點找出部分線段+單通道融合爲RGB影像

# 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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章