distrans.c所用到的库函数如下:今天的主角:cvDistTransform
//二值化分割图像
void cvThreshold( const CvArr* src, CvArr* dst, double threshold,
double max_value, int threshold_type );
//计算输入图像的所有非零元素对其最近零元素的距离,输入8位二值图像
void cvDistTransform( const CvArr* src, CvArr* dst, int distance_type=CV_DIST_L2,
int mask_size=3, const float* mask=NULL );
函数说明参考:http://www.opencv.org.cn/index.php/Cv%E5%9B%BE%E5%83%8F%E5%A4%84%E7%90%86
//线性变换转换矩阵数组
void cvConvertScale( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
//对输入的矩阵数组的每个元素求幂
void cvPow( const CvArr* src, CvArr* dst, double power );
//计算数组中每个元素与数值之间的按位与
void cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );
//多通道合并
void cvMerge( const CvArr* src0, const CvArr* src1, const CvArr* src2, const CvArr* src3, CvArr* dst );
==========================================================================================
测试例程:
#include<iostream>
#include<cv.h>
#include<highgui.h>
using namespace std;
//打印8位无符号数据
void PrintImage8U(IplImage* image)
{
for(int j=0;j<image->height;j++)
{
unsigned char * ptr = (unsigned char * )(image->imageData+image->widthStep*j); //行首指针
for(int i=0;i<image->width;i++)
{
unsigned char v = ptr[i];
cout<<(int)v<<"\t";
}
cout<<endl;
}
}
//打印32位浮点数数据
void PrintImage32F(IplImage* image)
{
for(int j=0;j<image->height;j++)
{
float * ptr = (float * )(image->imageData+image->widthStep*j); //行首指针
for(int i=0;i<image->width;i++)
{
float v = ptr[i];
cout<<(float)v<<"\t";
}
cout<<endl;
}
}
//测试距离函数
void TestDist()
{
//创建矩阵
IplImage* src = cvCreateImage(cvSize(9,9),IPL_DEPTH_8U,1);
IplImage* dst = cvCreateImage(cvSize(9,9),IPL_DEPTH_32F,1);
unsigned char * ptr = (unsigned char * )(src->imageData); //数据指针
*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0; *ptr++ = 0;*ptr++ = 0;ptr +=3;
*ptr++ = 0;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 0;*ptr++ = 0; *ptr++ = 0;*ptr++ = 0;ptr +=3;
*ptr++ = 0;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255; *ptr++ = 0;*ptr++ = 0;ptr +=3;
*ptr++ = 0;*ptr++ = 0;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 0;*ptr++ = 0;ptr +=3;
*ptr++ = 0;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 0;ptr +=3;
*ptr++ = 0;*ptr++ = 0;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 0;*ptr++ = 0;ptr +=3;
*ptr++ = 0;*ptr++ = 0;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255;*ptr++ = 255; *ptr++ = 0;*ptr++ = 0;ptr +=3;
*ptr++ = 0;*ptr++ = 0;*ptr++ = 255;*ptr++ = 0;*ptr++ = 255;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0; ptr +=3;
*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;*ptr++ = 0;
//计算距离 CV_DIST_L1计算出来的距离是精确的
cvDistTransform( src, dst, CV_DIST_L1, 3, NULL, NULL );
cout<<"变换前"<<endl;
PrintImage8U(src);
cout<<"变换后"<<endl;
PrintImage32F(dst);
cvReleaseImage(&src); //释放数据
cvReleaseImage(&dst); //释放数据
}
int main()
{
TestDist();
return 0;
}
效果如下: