本实验为计算机科学与技术学院计算机专业大四上限选课,2023-2024-1年度课程实验,较以往实验内容发生较大变化
本实验使用vs2019,c++语言,需要提前安装opencv,具体方法请自行搜索。
实验7:图像结构
快速距离变换
•
实现基于前向和逆向扫描的快速距离变换算法,并将距离场进行可视化显示,如下图所示。

#include <opencv2/opencv.hpp>
#include <iostream>
#include <cmath>
using namespace cv;
using namespace std;
Mat img, out;
double mmax = 0;
double Dmin(double a, double b)
{
return a < b ? a : b;
}
void quickDistance(Mat src, Mat& dis)
{
Mat tmp = src;
double result = 0.0;
double LeftTop = sqrt(2), Top = 1.0;
double RightTop = LeftTop, Left = Top ;
double LeftBottom = LeftTop, Bottom = Top;
double RightBottom = LeftTop, Right = Top;
for (int i = 1; i < src.rows - 1; i++)
{
for (int j = 1; j < src.cols - 1; j++)
{
result = Dmin((double)tmp.at<uchar>(i, j), LeftTop + (double)tmp.at<uchar>(i - 1, j - 1));
result = Dmin(result, Top + (double)tmp.at<uchar>(i - 1, j));
result = Dmin(result, Left + (double)tmp.at<uchar>(i, j - 1));
result = Dmin(result, LeftBottom + (double)tmp.at<uchar>(i + 1, j - 1));
tmp.at<uchar>(i, j) = (uchar)round(result);
}
}
for (int i = src.rows - 2; i > 0; i--)
{
for (int j = src.cols - 2; j > 0; j--)
{
result = Dmin((double)tmp.at<uchar>(i, j), RightTop + (double)tmp.at<uchar>(i - 1, j + 1));
result = Dmin(result, Right + (double)tmp.at<uchar>(i, j + 1));
result = Dmin(result, RightBottom + (double)tmp.at<uchar>(i + 1, j + 1));
result = Dmin(result, Bottom + (double)tmp.at<uchar>(i + 1, j));
tmp.at<uchar>(i, j) = (uchar)round(result);
mmax = max(mmax, result);
}
}
dis = tmp;
}
int main()
{
img = imread("C:/Users/13441/Desktop/数字图像/back8.png");
//img = 255 - img;
cvtColor(img, img, COLOR_RGB2GRAY);
threshold(img, img, 190, 255, THRESH_BINARY);
Mat vis = img;
imshow("input", img);
quickDistance(img, out);
for (int i = 0; i < out.rows; i++) {
for (int j = 0; j < out.cols; j++) {
double value = (double)out.at<uchar>(i, j);
int color_value = (int)(value*255 / mmax);
vis.at<uchar>(i, j) = (uchar)max(0, (int)color_value);
}
}
imshow("out2", vis);
waitKey();
return 0;
}
结果: