matlab图像处理空间滤波和频域滤波代码
时间: 2024-04-14 21:08:29 浏览: 171
由于空间滤波和频域滤波的具体实现方式和算法多种多样,因此无法提供一份通用的代码。以下是一些常见的图像处理滤波算法的 MATLAB 代码示例:
1. 均值滤波
空间滤波:
```matlab
function output = meanFilter(input, maskSize)
[m, n] = size(input);
output = zeros(m, n);
mask = ones(maskSize) / maskSize^2;
padSize = floor(maskSize / 2);
padded = padarray(input, [padSize padSize], 'replicate');
for i = 1:m
for j = 1:n
window = padded(i:i+maskSize-1, j:j+maskSize-1);
output(i, j) = sum(sum(window .* mask));
end
end
end
```
频域滤波:
```matlab
function output = meanFilterFreq(input, maskSize)
[m, n] = size(input);
output = zeros(m, n);
mask = ones(maskSize) / maskSize^2;
padSize = floor(maskSize / 2);
padded = padarray(input, [padSize padSize], 'replicate');
paddedFreq = fft2(padded);
maskFreq = fft2(mask, m+padSize*2, n+padSize*2);
outputFreq = paddedFreq .* maskFreq;
output = real(ifft2(outputFreq));
output = output(padSize+1:end-padSize, padSize+1:end-padSize);
end
```
2. 中值滤波
空间滤波:
```matlab
function output = medianFilter(input, maskSize)
[m, n] = size(input);
output = zeros(m, n);
padSize = floor(maskSize / 2);
padded = padarray(input, [padSize padSize], 'replicate');
for i = 1:m
for j = 1:n
window = padded(i:i+maskSize-1, j:j+maskSize-1);
output(i, j) = median(window(:));
end
end
end
```
3. 高斯滤波
空间滤波:
```matlab
function output = gaussianFilter(input, sigma)
[m, n] = size(input);
output = zeros(m, n);
maskSize = ceil(sigma * 6);
if mod(maskSize, 2) == 0
maskSize = maskSize + 1;
end
padSize = floor(maskSize / 2);
mask = fspecial('gaussian', maskSize, sigma);
padded = padarray(input, [padSize padSize], 'replicate');
for i = 1:m
for j = 1:n
window = padded(i:i+maskSize-1, j:j+maskSize-1);
output(i, j) = sum(sum(window .* mask));
end
end
end
```
频域滤波:
```matlab
function output = gaussianFilterFreq(input, sigma)
[m, n] = size(input);
output = zeros(m, n);
maskSize = ceil(sigma * 6);
if mod(maskSize, 2) == 0
maskSize = maskSize + 1;
end
padSize = floor(maskSize / 2);
mask = fspecial('gaussian', maskSize, sigma);
padded = padarray(input, [padSize padSize], 'replicate');
paddedFreq = fft2(padded);
maskFreq = fft2(mask, m+padSize*2, n+padSize*2);
outputFreq = paddedFreq .* maskFreq;
output = real(ifft2(outputFreq));
output = output(padSize+1:end-padSize, padSize+1:end-padSize);
end
```
阅读全文