需要注意的地方
图像格式
- JPG: 有损压缩,24bit真彩色,不支持动画,不支持透明色。
- PNG 无损压缩,PNG格式有8bit,24bit,32bit三种形式,32位PNG在24位基础上增加了8位透明通道,因此可展现256级透明度;
- BMP ,是一种与硬件格式无关的图像文件格式,适用非常广;无压缩,因此所占用的空间很大;
- 频谱图与图像格式有关,一般需要先将彩色图转换为灰度图,然后再做傅里叶变换。
im2gray() 作用:将彩色图或灰度图转换为灰度图
代码
处理单个图像
img = imread("Homework+1\1.png");
% 用来将彩色图转换为灰图,因为彩色图的数值比起灰度图处理起来非常不方便
img=im2gray(img);
% FFT
f = fft2(img);
% FFT频谱中心化
f = fftshift(f);
% magnitude
mag = abs(f);
% phase
phase = angle(f);
% plot
% 参数'[]'是为了将其值线性拉伸,log是为了更好显示图,加1是为了让图更亮(将所有值映射为正数)
% 对数转换的目的:经过log(X)变换后会变成负数,而log(X+1)则将所有的x值,映射成正数,数值范围也更小一些。
subplot(311);imshow(img);title("Original image");axis on;
subplot(312);imshow(log(mag+1),[]);title("Magnitude spectrum");axis on;
subplot(313);imshow(phase,[]);title("Phase spectrum");axis on;
批量处理
clc;close all;
dir_path = '\';
img_list = dir(dir_path);
% matlab读取文件夹下的文件时,前两个是空文件
for i=3:length(img_list)
% 带后缀的文件名
img_name = img_list(i).name;
% 不带后缀的文件名,用于保存文件
point = strfind(img_name,'.');
name = img_name(1:point-1);
% read image
original_img = imread(strcat(dir_path,img_name));
% 将图像转换为灰度图
img = im2gray(original_img);
% FFT
f = fft2(img);
% FFT频谱中心化
f = fftshift(f);
% magnitude
mag = abs(f);
% phase
phase = angle(f);
% plot
% 参数'[]'是为了将其值线性拉伸,log是为了更好显示图,加1是为了让图更亮(将所有值映射为正数)
figure(1)
subplot(131);imshow(original_img,[]);title('Original image');axis on;
subplot(132);imshow(log(mag+1),[]);title('Magnitude spectrum');axis on;
subplot(133);imshow(phase,[]);title('Phase spectrum');axis on;
saveas(gcf,strcat('result\',name),'jpg');
end