Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

medfilt2 filter expects input to be two-dimensional

I want to apply filter medfilt2 to an image that has salt & pepper noise.

I have tried this code:

img = imread('4.02.04_salt&pepper.tif');
blur = medfilt2(img,[3 3]);
imshow(blur);

but I got an error:

`Error using medfilt2
 Expected input number 1, A, to be two-dimensional.

 Error in medfilt2>parse_inputs (line 106)
 validateattributes(a, {'numeric','logical'}, {'2d','real'},
 mfilename, 'A', 1);

 Error in medfilt2 (line 48)
 [a, mn, padopt] = parse_inputs(varargin{:});

 Error in codLab3 (line 87)
 blur = medfilt2(img,[3 3]);`

I don't know why this is happening.

like image 976
LFRC Avatar asked Dec 02 '22 15:12

LFRC


2 Answers

Your image is a very likely a color image with RGB frames. medfilt2 only works on 2D images of a single color. The easiest workaround is probably to apply it on each color separately.

See example:

% load an image
img = imread('peppers.png');

% add some noise
img_noisy = imnoise(img, 'salt & pepper', 0.02);
figure; imshow(img_noisy);

% apply medfilt2 on each color
img_filtered = img_noisy;
for c = 1 : 3
    img_filtered(:, :, c) = medfilt2(img_noisy(:, :, c), [3, 3]);
end
figure; imshow(img_filtered);

Looks like:

enter image description here

like image 125
Trilarion Avatar answered Dec 06 '22 21:12

Trilarion


try to convert rgb to gray (rgb2gray):

img = imread('4.02.04_salt&pepper.tif');
img = rgb2gray(img); % add this line
blur = medfilt2(img);
imshow(blur);
like image 23
CESAR NICOLINI RIVERO Avatar answered Dec 06 '22 21:12

CESAR NICOLINI RIVERO