写一个对图像进行二维离散傅立叶变换的C语言代码
时间: 2024-06-03 17:07:33 浏览: 143
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846
// 定义复数结构体
typedef struct {
double real;
double imag;
} complex;
// 二维离散傅立叶变换
void dft2d(complex **input, complex **output, int width, int height)
{
int i, j, u, v;
complex sum, tmp;
// 对每个像素进行变换
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
sum.real = 0.0;
sum.imag = 0.0;
// 对每个频率进行求和
for (u = 0; u < height; u++) {
for (v = 0; v < width; v++) {
tmp.real = input[u][v].real * cos(2 * PI * (j * v / (double)width + i * u / (double)height)) + input[u][v].imag * sin(2 * PI * (j * v / (double)width + i * u / (double)height));
tmp.imag = -input[u][v].real * sin(2 * PI * (j * v / (double)width + i * u / (double)height)) + input[u][v].imag * cos(2 * PI * (j * v / (double)width + i * u / (double)height));
sum.real += tmp.real;
sum.imag += tmp.imag;
}
}
output[i][j].real = sum.real / (width * height);
output[i][j].imag = sum.imag / (width * height);
}
}
}
int main()
{
int width = 512; // 图像宽度
int height = 512; // 图像高度
int i, j;
complex **input, **output;
// 分配内存
input = (complex **)malloc(height * sizeof(complex *));
output = (complex **)malloc(height * sizeof(complex *));
for (i = 0; i < height; i++) {
input[i] = (complex *)malloc(width * sizeof(complex));
output[i] = (complex *)malloc(width * sizeof(complex));
}
// 初始化输入图像
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
input[i][j].real = sin(2 * PI * i / 64) + sin(2 * PI * j / 64);
input[i][j].imag = 0.0;
}
}
// 进行二维离散傅立叶变换
dft2d(input, output, width, height);
// 输出结果
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
printf("(%f, %f) ", output[i][j].real, output[i][j].imag);
}
printf("\n");
}
// 释放内存
for (i = 0; i < height; i++) {
free(input[i]);
free(output[i]);
}
free(input);
free(output);
return 0;
}
阅读全文