1. 程式人生 > >Opencv3.3-distanceTransform用於查詢物體質心

Opencv3.3-distanceTransform用於查詢物體質心

定義void  FindCenterWithDistanceTransform(cv::Mat src, cv::Point &centerLoc, float &maxValue);

void  FindCenterWithDistanceTransform(cv::Mat src, cv::Point &centerLoc, float &maxValue)
{
	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);  //距離變換
	
	//查詢最大值位置
	double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc;
	minMaxLoc(imageThin, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());
	centerLoc.x = maxLoc.x;
	centerLoc.y = maxLoc.y;
	maxValue = maxVal;

	//Mat distShow;
	//distShow = Mat::zeros(imageGray.size(), CV_8UC1); //定義細化後的字元輪廓
	//for (int i = 0; i<imageThin.rows; i++)
	//{
	//	for (int j = 0; j<imageThin.cols; j++)
	//	{
	//		distShow.at<uchar>(i, j) = imageThin.at<float>(i, j);
	//		if (imageThin.at<float>(i, j)>maxValue)
	//		{
	//			maxValue = imageThin.at<float>(i, j);  //獲取距離變換的極大值
	//			centerLoc = Point(j, i);  //座標
	//		}
	//	}
	//}
	//normalize(distShow, distShow, 0, 255, CV_MINMAX); //為了顯示清晰,做了0~255歸一化

	return;
}

main:

int main()
{
	Mat src = imread("C:\\Users\\Administrator\\Desktop\\捕獲.JPG");

	cv::Point Pt;//定義質心點座標
	float maxValue = 0.f; //定義距離變換矩陣中的最大值
	FindCenterWithDistanceTransform(src, Pt, maxValue);

	circle(src, Pt, maxValue, Scalar(0, 0, 255), 3);
	circle(src, Pt, 3, Scalar(0, 255, 0), 3);

	//namedWindow("Show");
	//imshow("Show", src);
	//waitKey();

	return 0;
}

結果: