1. 程式人生 > >Opencv3.3-distanceTransform用於細化字元輪廓

Opencv3.3-distanceTransform用於細化字元輪廓

void DoThinWithDistanceTransform(cv::Mat src, float thinScale, cv::Mat &distShow); 

//
void DoThinWithDistanceTransform(cv::Mat src, float thinScale, cv::Mat &distShow)
{
	float maxValue = 0;  //定義距離變換矩陣中的最大值
	Mat imageGray;

	if (src.channels() == 3)
		cvtColor(src, imageGray, CV_RGB2GRAY);
	else
		imageGray = src.clone();

	imageGray = ~imageGray;  //取反
	GaussianBlur(imageGray, imageGray, Size(5, 5), 2); //濾波
	threshold(imageGray, imageGray, 20, 200, CV_THRESH_BINARY); //閾值

	Mat imageThin(imageGray.size(), CV_32FC1); //定義儲存距離變換結果的Mat矩陣
	distanceTransform(imageGray, imageThin, CV_DIST_L2, 3);  //距離變換

	distShow = Mat::zeros(imageGray.size(), CV_8UC1); //定義細化後的字元輪廓
	for (int i = 0; i<imageThin.rows; i++)
	{
		for (int j = 0; j<imageThin.cols; j++)
		{
			if (imageThin.at<float>(i, j)>maxValue)
			{
				maxValue = imageThin.at<float>(i, j);  //獲取距離變換的極大值
			}
		}
	}
	for (int i = 0; i<imageThin.rows; i++)
	{
		for (int j = 0; j<imageThin.cols; j++)
		{
			if (imageThin.at<float>(i, j)>maxValue * thinScale)
			{
				distShow.at<uchar>(i, j) = 255;   //符合距離大於最大值一定比例條件的點設為255
			}
		}
	}

	return;
}

main函式:

int main()
{
	Mat src = imread("C:\\Users\\Administrator\\Desktop\\捕獲.JPG");
	float thinScale = 0.6;
	Mat distShow;
	distShow = Mat::zeros(src.size(), CV_8UC1); //定義細化後的字元輪廓

	DoThinWithDistanceTransform(src, thinScale, distShow);

	//namedWindow("show", 0);
	//imshow("show", distShow);
	//waitKey();

	return 0;
}

結果:

原圖:

結果圖: