您的位置:首页 > 运维架构

opencv 傅里叶变换与反变换

2015-10-12 13:04 387 查看
http://www.xpc-yx.com/2014/11/07/opencv%E5%AE%9E%E7%8E%B0%E5%BF%AB%E9%80%9F%E5%82%85%E7%AB%8B%E5%8F%B6%E5%8F%98%E6%8D%A2%E5%92%8C%E9%80%86%E5%8F%98%E6%8D%A2/?utm_source=tuicool

栗子1

#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,最后再转换回来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  opencv