#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main(){
//1.以灰度读取图像,并显示
Mat srcImage = imread("靶标原图.png",0);
if (!srcImage.data){
printf("读取图片失败,请检查路径是否正确\n");
return false;
}
imshow("原始图像", srcImage);
//2.将图像扩大到合适尺寸,边界用0填充
int m = getOptimalDFTSize(srcImage.rows);
int n = getOptimalDFTSize(srcImage.cols);
//将填充的像素初始化为0;
Mat padded;
copyMakeBorder(srcImage, padded, 0, m - srcImage.rows, 0, n - srcImage.cols, BORDER_CONSTANT, Scalar::all(0));
//3.为傅里叶变换结果分配存储空间
//傅里叶变换结果是复数,频域值范围远超空间值范围,因此需用float格式存储,另加一个通道存储复数部分
Mat planes[] = { Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F) };
Mat complexI;
merge(planes, 2, complexI);
//4.进行傅里叶变换
dft(complexI, complexI);
//5.将复数转化为幅值
split(complexI, planes);//多通道分离
magnitude(planes[0], planes[1], planes[0]);
Mat magnitudeImage = planes[0];
//6.进行对数尺寸缩放,用对数尺度替换线型尺度M1=log(M+1)
magnitudeImage += Scalar::all(1);
log(magnitudeImage, magnitudeImage);
//7.剪切并重分布幅度象限
magnitudeImage = magnitudeImage(Rect(0, 0, magnitudeImage.cols&-2, magnitudeImage.rows&-2));
//重新排列象限点
int cx = magnitudeImage.cols / 2;
int cy = magnitudeImage.rows / 2;
//重新划分傅里叶图像中的象限
Mat q0(magnitudeImage, Rect(0, 0, cx, cy));
Mat q1(magnitudeImage, Rect(cx, 0, cx, cy));
Mat q2(magnitudeImage, Rect(0, cy, cx, cy));
Mat q3(magnitudeImage, Rect(cx, cy, cx, cy));
//交换象限(上左与右下,上右与下左)
Mat tmp;
q0.copyTo(tmp);
q3.copyTo(q0);
tmp.copyTo(q3);
q1.copyTo(tmp);
q2.copyTo(q1);
tmp.copyTo(q2);
//8.归一化,用0~1之间的浮点值将矩阵变化为可视的图像格式
normalize(magnitudeImage, magnitudeImage, 0, 1, NORM_MINMAX);
imshow("频谱幅值", magnitudeImage);
dft(magnitudeImage, magnitudeImage, DFT_INVERSE, 0);
imshow("反傅里叶变换", magnitudeImage);
waitKey(0);
return 0;
}
OpenCV3 vs2013 图像处理——傅里叶变换(亲测可用)
最新推荐文章于 2019-10-09 17:00:13 发布