Opencv3.3-distanceTransform用于查找物体质心
程序员文章站
2022-03-31 11:30:25
...
定义void FindCenterWithDistanceTransform(cv::Mat src, cv::Point ¢erLoc, float &maxValue);
void FindCenterWithDistanceTransform(cv::Mat src, cv::Point ¢erLoc, 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;
}