Opencv2 computer vision application programming cookbook<五>

来源:互联网 发布:js 动态 array的方法 编辑:程序博客网 时间:2024/06/06 01:22

第六章介绍图像滤波

主要介绍图像的laplace及利用laplace求图像边缘

#include "stdafx.h"
#include<iostream>  
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp> 
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;


class LaplacianZC
{
private:
//原图
Mat img;
//包含 Laplacian的32位浮点图像
Mat laplace;
//laplacian总积核的大小
int aperture;
public:
LaplacianZC():aperture(3){};
//设置卷积核的大小
void SetAperture(int a)
{
aperture=a;
}
//计算浮点数Laplacian
Mat ComputeLaplacian(const Mat & image)
{
//计算Laplacian
Laplacian(image,laplace,CV_32F,aperture);
//保留图像的局部备份(用于零点交叉)
img=image.clone();
return laplace;
}
//返回8位图像存储的laplacian结果
//零点交叉于灰度值128
//如果没有指定scale参数,那么最大值将缩放至强度255
//你必须在调用它之前调用computeLaplacian
Mat GetLaplaceianImage(double scale=-1.0)
{
if(scale<0)
{
double lapmin,lapmax;
minMaxLoc(laplace,&lapmin,&lapmax);
scale=127/max(-lapmin,lapmax);
}
Mat laplaceImage;
laplace.convertTo(laplaceImage,CV_8U,scale,128);
return laplaceImage;
}
//得到零点交叉的二值图像
//如果相邻像素的乘积小于threshold
//那么零点交叉将被忽略
Mat GetZeroCrossings(float threshold=1.0)
{
//创建迭代器
Mat_<float>::const_iterator it=laplace.begin<float>()+laplace.step1();
Mat_<float>::const_iterator itend=laplace.end<float>();
Mat_<float>::const_iterator itup=laplace.begin<float>();
//初始化为白色的二值图像
Mat binary(laplace.size(),CV_8U,Scalar(255));
Mat_<uchar>::iterator itout=binary.begin<uchar>()+binary.step1();
//对输入阈值取反
threshold*=-1.0;
for(;it!=itend;++it,++itup,++itout)
{
//如果相邻像素的乘积为负数,那么符号发生改变
if(*it**(it-1)<threshold)
*itout=0;//水平方向零点交叉
else if(*it**itup<threshold)
*itout=0;//垂直方向零点交叉


}
return binary;
}
};


int _tmain(int argc, _TCHAR* argv[])
{
Mat image=imread("lena512color.tiff",0);
Mat result;
//blur(image,result,Size(5,5));
GaussianBlur(image,result,Size(5,5),1.5);
Mat reducedImage;
pyrDown(image,reducedImage);
pyrUp(reducedImage,image);


Mat resizedImage;
resize(image,resizedImage,Size(image.cols/3,image.rows/3));


medianBlur(image,result,5);


Mat sobelX,sobelY;
Sobel(image,sobelX,CV_8U,1,0,3,0.4,128);
Sobel(image,sobelY,CV_8U,0,1,3,0.4,128);


//计算sobel范式
Sobel(image,sobelX,CV_16S,1,0);
Sobel(image,sobelY,CV_16S,0,1);
Mat sobel;
sobel=abs(sobelX)+abs(sobelY);


//搜索 Sobel极大值
double sobmin,sobmax;
minMaxLoc(sobel,&sobmin,&sobmax);
//变换为8位图像
//sobelImage=-alpha*sobel+255
Mat sobelImage;
sobel.convertTo(sobelImage,CV_8U,-255./sobmax,255);

threshold(sobelImage,sobelImage,200,255,THRESH_BINARY);


//图像的laplacian
LaplacianZC laplacian;
laplacian.SetAperture(7);
Mat flap=laplacian.ComputeLaplacian(image);
Mat laplace;
laplace=laplacian.GetLaplaceianImage();
//检查边缘
//laplace=laplacian.GetZeroCrossings();

imshow("lena",laplace);




waitKey();
return 0;
}


0 0
原创粉丝点击