引言:
Opencv中distanceTransform方法用于计算图像中每一个非零点距离离自己最近的零点的距离,distanceTransform的第二个Mat矩阵参数dst保存了每一个点与最近的零点的距离信息,图像上越亮的点,代表了离零点的距离越远。
可以根据距离变换的这个性质,经过简单的运算,用于细化字符的轮廓和查找物体质心(中心)。
API:
代码示例:
1.细化字符的轮廓:
#include "pch.h"
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("F:\\visual studio\\Image\\number.jpg");
if (src.empty())
{
cout << "Can't load the image" << endl;
}
//转化为灰度图
Mat graysrc;
cvtColor(src, graysrc, COLOR_BGR2GRAY);
//高斯模糊
Mat blursrc;
GaussianBlur(graysrc, blursrc, Size(3, 3), 0, 0);
//转化为二值图像
Mat bin;
threshold(~blursrc, bin,CV_THRESH_TRIANGLE, 255, CV_THRESH_BINARY);
imshow("bin", bin);
//距离变换
Mat dist = Mat::zeros(src.size(), CV_32FC1);
distanceTransform(bin, dist, CV_DIST_L1, 3);
//求取距离的最大值
double maxVal;
minMaxLoc(dist, 0, &maxVal, 0, 0, Mat());
//距离图像
Mat temp;
dist.convertTo(temp, CV_8UC1);
imshow("dist", temp/maxVal*255);
//细化字符的轮廓
Mat dst = Mat::zeros(src.size(), CV_8UC1);
for (int i = 0; i < dist.rows; i++)
{
for (int j = 0; j < dist.cols; j++)
{
if (dist.at<float>(i, j) > maxVal / 2)
dst.at<uchar>(i, j) = 255;
}
}
imshow("dst", dst);
waitKey(0);
}
效果展示:
2.寻找物体的中心:
#include "pch.h"
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("F:\\visual studio\\Image\\liujiao.jpg");
if (src.empty())
{
cout << "Can't load the image" << endl;
}
//转化为灰度图
Mat graysrc;
cvtColor(src, graysrc, COLOR_BGR2GRAY);
//高斯模糊
Mat blursrc;
GaussianBlur(graysrc, blursrc, Size(3, 3), 0, 0);
//转化为二值图像
Mat bin;
threshold(~blursrc, bin, CV_THRESH_TRIANGLE, 255, CV_THRESH_BINARY);
imshow("bin", bin);
//距离变换
Mat dist = Mat::zeros(src.size(), CV_32FC1);
distanceTransform(bin, dist, CV_DIST_L1, 3);
//求取距离的最大值
double maxVal;
Point Pt;
minMaxLoc(dist, 0, &maxVal, 0, &Pt, Mat());
//距离图像
dist.convertTo(dist, CV_8UC1);
normalize(dist, dist, 0, 255, CV_MINMAX);
imshow("dist", dist);
//绘制物体的中心
Mat dst;
src.copyTo(dst);
circle(dst, Pt, 2, Scalar(255, 0, 0), 2, LINE_AA);
circle(dst, Pt, maxVal, Scalar(0, 0, 255), 2, LINE_AA);
imshow("dst", dst);
waitKey(0);
}