1.源码实现
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main()
{
float maxValue = 0;
Mat image, image_gray;
image = imread("11.jpeg");
cvtColor(image, image_gray, CV_RGB2GRAY);
image_gray = ~image_gray; //取反
GaussianBlur(image_gray, image_gray, Size(5,5), 2); //滤波
threshold(image_gray, image_gray, 20, 300, CV_THRESH_BINARY); //阈值
imwrite("image_gray.jpg", image_gray);
Mat image_thin(image_gray.size(), CV_32FC1);
Mat dist_show = Mat::zeros(image_gray.size(), CV_8UC1);
distanceTransform(image_gray, image_thin, CV_DIST_L2, 3); //距离变换
for(int i=0; i<image_thin.rows; i++)
{
for(int j=0; j<image_thin.cols; j++)
{
if(image_thin.at<float>(i, j) > maxValue)
{
maxValue = image_thin.at<float>(i, j);
}
}
}
for(int i=0; i<image_thin.rows; i++)
{
for(int j=0; j<image_thin.cols; j++)
{
if(image_thin.at<float>(i, j) > maxValue / 3.5)
{
dist_show.at<uchar>(i, j) = 255;
}
}
}
imwrite("thin_image.jpg", dist_show);
return 0;
}
2.编译源码
$ g++ -o test test.cpp -std=c++11 -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -Wl,-rpath=/usr/local/lib
3.运行及其结果

11.jpeg

image_gray.jpg

thin_image.jpg
网友评论