License YOLO
Back to Ultralytics Glossary

Median Filter

A median filter replaces each pixel with the middle value in its neighborhood, removing isolated bright and dark specks while preserving many edges.

A median filter replaces each pixel with the median of the values in a window centered on it. The median is the middle value after ordering the samples from darkest to brightest. Also called median blur, this form of image preprocessing is especially useful for salt-and-pepper noise: isolated bright and dark specks. Sensor defects or transmission errors can introduce these specks, which can show up as false boundaries during edge detection.

John W. Tukey presented running medians for smoothing data series in 1974 and described them in his 1977 book Exploratory Data Analysis. In computer vision, the same rule operates on a two-dimensional pixel neighborhood.

How a Median Filter Works#

A 3 × 3 window contains nine samples, including the center pixel. If those samples are 48, 49, 49, 50, 51, 51, 52, 53, 255 in sorted order, the output is 51, the fifth value. A bright center pixel of 255 takes on a value close to those around it. The same window has a mean of about 73, which is brighter than every uncorrupted sample in this example. Each window reads from the original image, so pixels already written to the output do not affect their neighbors.

Square windows with odd side lengths, such as 3 × 3 and 5 × 5, have a single center and an odd number of samples. The median selects an existing value based on its position in the sorted window, making it a rank statistic. The operation is nonlinear: there is no fixed set of convolution weights that always selects the middle-ranked value.

At the image border, part of the window extends beyond the available pixels. SciPy's ndimage.median_filter reflects values at the boundary by default and supports custom footprints that include only selected positions within the window. For an array laid out as height × width × channels, size=(3, 3, 1) applies a spatial filter without mixing color channels.

Median Filter vs. Mean and Gaussian Filters#

A mean filter gives every sample in its window equal weight. Gaussian blur weights nearby samples more strongly and smooths small intensity fluctuations before operations such as Canny edge detection. Both averages can spread the influence of a bright outlier across several output pixels. A median filter can preserve a sharp brightness step because it selects a value from one side of the boundary.

That same rule can erase real detail. A one-pixel-wide dark line running through the middle column of a 3 × 3 window contributes three pixels. The six background pixels outvote it, so the center pixel becomes background. In optical character recognition (OCR), losing narrow strokes or punctuation can make text harder to recognize. Larger windows can remove bigger noise clusters, but they are also more likely to erase thin strokes or round corners.

Where Median Filtering Fits in a Vision Pipeline#

In OpenCV's photographed Sudoku example, a 5 × 5 median filter smooths the grayscale image before adaptive thresholding. The thresholding step then uses local brightness to separate the dark digits and grid lines from the unevenly lit paper.

As data augmentation, median blur changes pixel values while keeping bounding box coordinates fixed. When Albumentations is installed and its default transforms are active, the Ultralytics YOLO26 Albumentations integration applies MedianBlur with a 1% probability to one- or three-channel training images for object detection.

Applying a Median Filter in Python#

OpenCV provides cv2.medianBlur(image, 3) for a 3 × 3 filter. With opencv-python installed, this example saves the original and filtered views side by side.

from urllib.request import urlopen

import cv2
import numpy as np

with urlopen("https://ultralytics.com/images/bus.jpg") as response:
    encoded = np.frombuffer(response.read(), dtype=np.uint8)
image = cv2.imdecode(encoded, cv2.IMREAD_COLOR)

filtered = cv2.medianBlur(image, 3)
comparison = cv2.hconcat([image, filtered])
cv2.imwrite("median_filter_comparison.png", comparison)

Fine textures look smoother in the filtered image on the right. OpenCV repeats edge pixels to fill windows at the image border and computes each color channel's median separately, so the resulting blue, green, and red values can come from three different neighboring pixels.

Explore solutions

Computer vision in sports

Computer vision in sports

Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery

Computer vision for aerial imagery

Turn drone and aerial imagery into real-time insights for agriculture, aquaculture, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace

Computer vision in aerospace

Apply computer vision in aerospace with Ultralytics YOLO for aircraft inspection, runway FOD detection, airport ground operations, and composite defect detection.
Learn more
Computer vision in security

Computer vision in security

Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics

Computer vision in robotics

Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics

Computer vision in logistics

Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail

Computer vision in retail

Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare

Computer vision in healthcare

Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing

Computer vision in manufacturing

Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive

Computer vision in automotive

Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture

Computer vision in agriculture

Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning