You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决MATLAB中FFT图像滤波时的“数组尺寸不兼容”错误?

解决Matlab中FFT滤波的“Arrays have incompatible sizes”错误

错误原因

你的代码里,mask是3×3的小矩阵,执行fftshift(mask)后尺寸依然是3×3,但F是原图像经过fft2得到的数组,尺寸和原图像完全一致(比如原图像是512×512,F就是512×512)。Matlab的逐元素乘法(.*)要求两个操作数的尺寸完全匹配,因此触发“数组尺寸不兼容”的错误。

解决方案

需要将3×3的掩码扩展为和原图像(及FFT结果)同尺寸的矩阵,并把原掩码放在这个大矩阵的中心(对应频域的直流分量区域)。同时如果原图像是彩色图,需要先转成灰度图,避免多通道带来的尺寸问题。

修改后的完整代码:

% Read the image
im = imread('image2.jpg');

% Convert to grayscale if the image is color
im = rgb2gray(im);

% Convert the image to double precision
im = im2double(im);

% Get the dimensions of the image
[rows, cols] = size(im);

% Compute FFT of the image and shift DC component to center
F = fft2(im);
F_shifted = fftshift(F);

% Define the 3x3 high-pass filter mask
mask = [-1 -1 -1; -1 8 -1; -1 -1 -1];

% Create a full-size mask with the 3x3 filter at the center
mask_full = zeros(rows, cols);
center_row = floor(rows / 2);
center_col = floor(cols / 2);
% Place the small mask in the center of the full-size matrix
mask_full(center_row-1:center_row+1, center_col-1:center_col+1) = mask;

% Apply the filter to the shifted FFT
F_filtered_shifted = F_shifted .* mask_full;

% Display the magnitude of the filtered FFT
imshow(log(abs(F_filtered_shifted)), []); 

关键说明

  • 尺寸匹配:通过zeros(rows, cols)创建和图像同尺寸的空掩码,再把3×3的滤波核放到中心区域,保证和FFT结果尺寸一致。
  • 彩色图像处理:用rgb2gray将彩色图转为灰度图,避免多通道数组和2D掩码相乘的尺寸冲突。
  • 频域移位:先对FFT结果执行fftshift,把直流分量移到中心,再和中心放置的掩码相乘,符合频域滤波的逻辑。

内容的提问来源于stack exchange,提问作者user21920857

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 19:23:09