Implement a nonlinear filter — a median filter.

8 次查看(过去 30 天)
Implement a nonlinear filter — a median filter. While the Gaussian filter works by computing locally-weighted values of the signal, the median filter first sorts the signal values within a window and then takes the middle value (i.e., the median). Implement a function, simpleMedian, which takes as input an image, I, and the dimensions of the median filter, W and H, and returns a median filtered image. Zero-pad the image within the function to ensure that the filtered image is the same size as the original image. Apply a 12×12 median filter to the loaded images. Show the results.
CODE:
% load the input image
img = imread('Old_house.jpg');
% apply a 12x12 median filter to the image
filtered_img = simpleMedian(img, 12, 12);
% display the input and filtered images side by side
figure;
subplot(1,2,1);
imshow(img);
title('Input Image');
subplot(1,2,2);
imshow(filtered_img);
title('Filtered Image');
function filtered_img = simpleMedian(I, W, H)
% zero-pad the image
padded_img = padarray(I, [(H-1)/2 (W-1)/2], 'symmetric');
% initialize the filtered image
filtered_img = zeros(size(I), 'like', I);
% loop through each pixel in the image
for i = 1:size(I,1)
for j = 1:size(I,2)
% extract the window centered at (i,j)
window = padded_img(i:i+H-1, j:j+W-1);
% take the median of the window
filtered_img(i,j) = median(window(:));
end
end
end
ERROR:
Error using padarray
Expected input number 2, PADSIZE, to be integer-valued.
Error in padarray>ParseInputs (line 108)
validateattributes(padSize, {'double'}, {'real' 'vector' 'nonnan'
'nonnegative' ...
Error in padarray (line 75)
[a, method, padSize, padVal, direction, catConverter] =
ParseInputs(args{:});
Error in untitled1_12>simpleMedian (line 18)
padded_img = padarray(I, [(H-1)/2 (W-1)/2], 'symmetric');
Error in untitled1_12 (line 5)
filtered_img = simpleMedian(img, 12, 12);

回答(1 个)

Walter Roberson
Walter Roberson 2023-3-12
padded_img = padarray(I, [(H-1)/2 (W-1)/2], 'symmetric');
Suppose the height, H, is even, such as if H = 12. Then H-1 is 11, and 11/2 is not an integer. So you are asking to pad by 5 1/2 rows and columns on each side, which is not something that is permitted.

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by