| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → Image Processing Toolbox |
| Contents | Index |
| Learn more about Image Processing Toolbox |
B = medfilt2(A, [m n])
B = medfilt2(A)
B = medfilt2(A, 'indexed', ...)
B = medfilt2(..., padopt)
Median filtering is a nonlinear operation often used in image processing to reduce "salt and pepper" noise. A median filter is more effective than convolution when the goal is to simultaneously reduce noise and preserve edges.
B = medfilt2(A, [m n]) performs median filtering of the matrix A in two dimensions. Each output pixel contains the median value in the m-by-n neighborhood around the corresponding pixel in the input image. medfilt2 pads the image with 0s on the edges, so the median values for the points within [m n]/2 of the edges might appear distorted.
B = medfilt2(A) performs median filtering of the matrix A using the default 3-by-3 neighborhood.
B = medfilt2(A, 'indexed', ...) processes A as an indexed image, padding with 0s if the class of A is uint8, or 1s if the class of A is double.
B = medfilt2(..., padopt) controls how the matrix boundaries are padded. padopt may be 'zeros' (the default), 'symmetric', or 'indexed'. If padopt is 'symmetric', A is symmetrically extended at the boundaries. If padopt is 'indexed', A is padded with ones if it is double; otherwise it is padded with zeros.
The input image A can be of class logical or numeric (unless the 'indexed' syntax is used, in which case A cannot be of class uint16). The output image B is of the same class as A.
If the input image A is of an integer class, all the output values are returned as integers. If the number of pixels in the neighborhood (i.e., m*n) is even, some of the median values might not be integers. In these cases, the fractional parts are discarded. Logical input is treated similarly.
For example, suppose you call medfilt2 using 2-by-2 neighborhoods, and the input image is a uint8 array that includes this neighborhood.
1 5 4 8
medfilt2 returns an output value of 4 for this neighborhood, although the true median is 4.5.
Add salt and pepper noise to an image and then restore the image using medfilt2.
I = imread('eight.tif');
J = imnoise(I,'salt & pepper',0.02);
K = medfilt2(J);
imshow(J), figure, imshow(K)

medfilt2 uses ordfilt2 to perform the filtering.
[1] Lim, Jae S., Two-Dimensional Signal and Image Processing, Englewood Cliffs, NJ, Prentice Hall, 1990, pp. 469-476.
![]() | mean2 | montage | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2010- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |