opencv实现图像DFT

#include 
#include 
#include 

using namespace cv;
using namespace std;

int main()
{
	Mat img = imread("city.jpg", 0);
	//转换为32位浮点型
	img.convertTo(img, CV_32F);
	//为了将傅里叶谱低频部分显示在频谱图的中心
	for (int x = 0; x != img.rows; ++x) {
		for (int y = 0; y != img.cols; ++y) {
			img.ptr<float>(x)[y] *= (float)pow(-1.0, x + y);
		}
	}
	//得到图像最佳的DFT尺寸
	int m = getOptimalDFTSize(img.rows);
	int n = getOptimalDFTSize(img.cols);
	//扩充边界432*360
	Mat img_padded;
	copyMakeBorder(img, img_padded, 0, m-img.rows, 0, n-img.cols, BORDER_CONSTANT, Scalar::all(0));
	//cout << img_padded.size() << endl;
	vector<Mat> img_complex{img_padded, Mat::zeros(img_padded.size(), CV_32F)};
	Mat complexI;
	//将多个图像数据混合在一个Mat中
	merge(img_complex, complexI);
	//离散傅里叶变换
	dft(complexI, complexI, DFT_COMPLEX_OUTPUT, complexI.rows);
	vector<Mat> img_complex_split;
	split(complexI, img_complex_split);
	img_complex.at(0) = img_complex_split.at(0);
	img_complex.at(1) = img_complex_split.at(1);
	Mat img_mag;
	magnitude(img_complex.at(0), img_complex.at(1), img_mag);
	img_mag += Scalar::all(1);
	log(img_mag, img_mag);
	normalize(img_mag, img_mag, 255.0, 0.0, NORM_INF);
	img_mag.convertTo(img_mag, CV_8U);
	//cout << img_mag.channels() << img_mag.size() << endl;
	//显示频谱图
	imshow("123", img_mag);
	//cout << complexI.channels() << endl;
	//傅里叶反变换
	dft(complexI, complexI, DFT_INVERSE + DFT_SCALE + DFT_REAL_OUTPUT, complexI.rows);
	//cout << complexI.channels() << complexI.size() << endl;
	for (int x = 0; x != complexI.rows; ++x) {
		for (int y = 0; y != complexI.cols; ++y) {
			complexI.ptr<float>(x)[y] *= (float)pow(-1.0, x + y);
		}
	}
	//转换为8位无符号整型
	complexI.convertTo(complexI, CV_8U);
	//显示原图像(经过尺寸扩展后的图像)
	imshow("456", complexI);
	//等待任意按键
	waitKey(0);
	//关闭所有图像窗口
	destroyAllWindows();
	
	system("pause");
	return 0;
}

你可能感兴趣的:(C++)