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

OpenCV学习离散傅里叶变换(DFT)

2016-05-27 20:14 507 查看
int main(int argc, char ** argv)
{

const char* filename = argc >= 2 ? argv[1] : "C:/Users/dell/Desktop/1.jpg";

Mat I = imread(filename, IMREAD_GRAYSCALE);
if (I.empty())
return -1;

Mat padded; //expand input image to optimal size
/*
*getOptimalDFTSize(int vecsize)获得进行DFT计算的最佳尺寸.
*getOptimalDFTSize()函数就是为了获得满足分解成2,3,5的最小整数尺寸.
*如果是多维矩阵需要进行DFT,则每一维单独用这个函数获得最佳DFT尺寸.
*/
int m = getOptimalDFTSize(I.rows);
int n = getOptimalDFTSize(I.cols); // on the border add zero values

/*
void copyMakeBorder(InuptArray src, OutputArray dst, int top , int bottom, int left, int right, int borderType, const Scalar& value=Scalar())
该函数是用来扩展一个图像的边界的,第3~6个参数分别为原始图像的上下左右各扩展的像素点的个数,第7个参数表示边界的类型,
如果其为BORDER_CONSTANT,则扩充的边界像素值则用第8个参数来初始化。将src图像扩充边界后的结果保存在dst图像中。
*/
cout << I.size() << endl;
copyMakeBorder(I, padded, 0, m - I.rows, 0, n - I.cols, BORDER_CONSTANT, Scalar::all(0));//把灰度图像放在左上角,在右边和下边扩展图像,扩展部分填充为0;
cout << padded.size() << endl;

//新建一个两页的array,其中第一页用扩展后的图像初始化,第二页初始化为0
Mat planes[] = { Mat_<float>(padded), Mat::zeros(padded.size(), CV_32F) };
Mat complexI;
merge(planes, 2, complexI); // Add to the expanded another plane with zeros把两页合成一个2通道的mat

//对上边合成的mat进行傅里叶变换,支持原地操作,傅里叶变换结果为复数。通道1存的是实部,通道2存的是虚部。
dft(complexI, complexI); // this way the result may fit in the source matrix

// compute the magnitude and switch to logarithmic scale
// => log(1 + sqrt(Re(DFT(I))^2 + Im(DFT(I))^2))
//把变换后的结果分割到各个数组的两页中,方便后续操作
split(complexI, planes); // planes[0] = Re(DFT(I), planes[1] = Im(DFT(I))

//求傅里叶变换各频率的幅值,幅值放在第一页中。
magnitude(planes[0], planes[1], planes[0]);// planes[0] = magnitude
Mat magI = planes[0];
//傅立叶变换的幅度值范围大到不适合在屏幕上显示。高值在屏幕上显示为白点,
//而低值为黑点,高低值的变化无法有效分辨。为了在屏幕上凸显出高低变化的连续性,我们可以用对数尺度来替换线性尺度:
magI += Scalar::all(1); // switch to logarithmic scale
log(magI, magI);

// crop the spectrum, if it has an odd number of rows or columns
magI = magI(Rect(0, 0, magI.cols & -2, magI.rows & -2));////前面对原始图像进行了扩展,这里把对原始图像傅里叶变换取出,剔除扩展部分。

// rearrange the quadrants of Fourier image so that the origin is at the image center
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);

//这一步的目的仍然是为了显示。 现在我们有了重分布后的幅度图,
//但是幅度值仍然超过可显示范围[0,1] 。我们使用 normalize() 函数将幅度归一化到可显示范围。
//傅里叶图像进行归一化。
normalize(magI, magI, 0, 1, NORM_MINMAX); // Transform the matrix with float values into a
// viewable image form (float between values 0 and 1).

imshow("Input Image", I); // Show the result
imshow("spectrum magnitude", magI);
waitKey();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: