傅立叶变换与逆变换 下

上篇为傅立叶变换与逆变换,这里将频谱的一些频率过滤掉。

代码如下:

// opencv_dft.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <OpenCV245.h>

using namespace std;
using namespace cv;


int _tmain(int argc, _TCHAR* argv[])
{
	Mat src;
	Mat Image = imread("C:\\Users\\sony\\Desktop\\111.png", 0);
	if (Image.empty())
	  return -1;
	

	Mat padded;
	int m = getOptimalDFTSize(Image.rows);
	int n = getOptimalDFTSize(Image.cols);
	copyMakeBorder(Image, padded, 0, m - Image.rows, 0, n - Image.cols, BORDER_CONSTANT, Scalar::all(0));

	Mat planes[] = {Mat_<double>(padded),  Mat::zeros(padded.size(), CV_64F)};
	
	
	Mat iplanes[] = {Mat_<double>(padded),  Mat::zeros(padded.size(), CV_64F)};
	Mat complexI;
	merge(planes, 2, complexI);

	dft(complexI, complexI);

	int min = complexI.cols < complexI.rows ? complexI.cols : complexI.rows; 
	for (int j = 0; j < complexI.rows; j++)
	{
		for (int i = 0; i < complexI.cols; i++)
		{
			/*if ( (i - complexI.cols/2 - 1)*(i - complexI.cols/2 - 1) + (j - complexI.rows/2 - 1)*(j - complexI.rows/2 - 1) < min*min/4)
			{
				complexI.at<Vec2d>(i,j)[0] = 0;
				complexI.at<Vec2d>(i,j)[1] = 0;
			}*/
			int d = 500;
			if ( i*i + j*j < d || (i - complexI.cols - 1)*(i - complexI.cols - 1) + j*j < d ||
				i*i + (j - complexI.rows - 1)*(j - complexI.rows - 1) < d || 
				(i - complexI.cols - 1)*(i - complexI.cols - 1)+  (j - complexI.rows - 1)*(j - complexI.rows - 1) < d)
			{
				complexI.at<Vec2d>(i,j)[0] = 0;
				complexI.at<Vec2d>(i,j)[1] = 0;
				
			}else
			{
				
			}

		}
	}

	
	dft(complexI, src, DFT_SCALE|DFT_INVERSE);
	
	
	split(complexI, planes);
	
	magnitude(planes[0], planes[1], planes[0]);
	Mat magI = planes[0];

	split(src, iplanes);
	magnitude(iplanes[0], iplanes[1], iplanes[0]);
	Mat imagI = iplanes[0];

	magI += Scalar::all(1);
	log(magI, magI);

	magI = magI(Rect(0, 0, magI.cols & -2, magI.rows & -2));

	

	Mat O = magI.clone();

	int cx = magI.cols/2;
	int cy = magI.rows/2;

	Mat q0(magI, Rect(0, 0, cx, cy));   // Top-Left - Create a ROI per quadrant 
	Mat q1(magI, Rect(cx, 0, cx, cy));  // Top-Right
	Mat q2(magI, Rect(0, cy, cx, cy));  // Bottom-Left
	Mat q3(magI, Rect(cx, cy, cx, cy)); // Bottom-Right

	Mat tmp;                           // swap quadrants (Top-Left with Bottom-Right)
	q0.copyTo(tmp);
	q3.copyTo(q0);
	tmp.copyTo(q3);

	q1.copyTo(tmp);                    // swap quadrant (Top-Right with Bottom-Left)
	q2.copyTo(q1);
	tmp.copyTo(q2);

	normalize(magI, magI, 0, 1, CV_MINMAX);
	normalize(O, O, 0, 1, CV_MINMAX);
	normalize(imagI, imagI, 0, 1, CV_MINMAX);
	

	imshow("input Image", Image);
	imshow("spectrum magnitude", magI);
	imshow("0", O);
	/*cout<<src<<endl;*/
	imshow("src",imagI);
	waitKey(0);


	return 0;
}

傅立叶变换与逆变换 下_第1张图片

你可能感兴趣的:(傅立叶变换与逆变换 下)