#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#ifdef _DEBUG
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")
#pragma comment(lib, "opencv_highgui247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#endif // DEBUG
int main()
{
// Read image from file
// Make sure that the image is in grayscale
cv::Mat img = cv::imread("lena.JPG",0);
cv::Mat planes[] = {cv::Mat_<float>(img), cv::Mat::zeros(img.size(), CV_32F)};
cv::Mat complexI; //Complex plane to contain the DFT coefficients {[0]-Real,[1]-Img}
cv::merge(planes, 2, complexI);
cv::dft(complexI, complexI); // Applying DFT
//这里可以对复数矩阵comlexI进行处理
// Reconstructing original imae from the DFT coefficients
cv::Mat invDFT, invDFTcvt;
cv::idft(complexI, invDFT, cv::DFT_SCALE | cv::DFT_REAL_OUTPUT ); // Applying IDFT
cv::invDFT.convertTo(invDFTcvt, CV_8U);
cv::imshow("Output", invDFTcvt);
//show the image
cv::imshow("Original Image", img);
// Wait until user press some key
cv::waitKey(0);
return 0;
}
代码意思很简单,dft之后再idft,注意参数额,必须有DFT_SCALE。代码中,先merge了个
复数矩阵,在例子2中可以看到,其实这一步可以去掉。
栗子2
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#ifdef _DEBUG
#pragma comment(lib, "opencv_core247d.lib")
#pragma comment(lib, "opencv_imgproc247d.lib")
#pragma comment(lib, "opencv_highgui247d.lib")
#else
#pragma comment(lib, "opencv_core247.lib")
#pragma comment(lib, "opencv_imgproc247.lib")
#pragma comment(lib, "opencv_highgui247.lib")
#endif // DEBUG
int main()
{
// Read image from file
// Make sure that the image is in grayscale
cv:;Mat img = cv::imread("lena.JPG",0);
cv::Mat dftInput1, dftImage1, inverseDFT, inverseDFTconverted;
cv::img.convertTo(dftInput1, CV_32F);
cv::dft(dftInput1, dftImage1, cv::DFT_COMPLEX_OUTPUT); // Applying DFT
// Reconstructing original imae from the DFT coefficients
cv::idft(dftImage1, inverseDFT, cv::DFT_SCALE | cv::DFT_REAL_OUTPUT ); // Applying IDFT
cv::inverseDFT.convertTo(inverseDFTconverted, CV_8U);
cv::imshow("Output", inverseDFTconverted);
//show the image
cv::imshow("Original Image", img);
// Wait until user press some key
waitKey(0);
return 0;
}
从代码中可以看到,dft时候添加参数DFT_COMPLEX_OUTPUT,就可以自动得到复数矩阵了,代码更加简洁。
注意,必须先将图片对应的uchar矩阵转换为float矩阵,再进行dft,idft,最后再转换回来。