Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An image filter replaces each pixel with a value computed from nearby pixels. A low-pass filter suppresses rapid intensity changes for smoothing or denoising; a high-pass or derivative filter emphasizes changes such as edges. The right choice depends on the noise model, how important boundaries are, how much detail can be lost, and how much parameter tuning your task permits.

This guide shows what each common filter does, how its response should look, and how to visualize the results with OpenCV or scikit-image.

How a filter changes an image

For a linear filter, a small matrix called a kernel slides across the image. Each output pixel is a weighted combination of the pixels under that kernel. In two-dimensional convolution, the kernel is applied at every location, including locations near the border where the library must decide how to supply pixels outside the image.

A simple 3×3 averaging kernel is:

1/9 1/9 1/9
1/9 1/9 1/9
1/9 1/9 1/9

Every neighbor contributes equally. A Gaussian kernel gives larger weights to nearby pixels, while a sharpening kernel can add the center pixel and subtract its neighbors. Median and bilateral filters are nonlinear: they do not simply multiply and add fixed kernel coefficients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
LAPGEAR Home Office Pro Lap Desk - Black Carbon, Fits 15.6” Laptops
  • Spacious Design: Measuring 21.1" wide and 14.1" deep, our lap desk comfortably fits most laptops up to 15.6". Extra room for accessories ensures convenience.
  • Enhanced Functionality: Packed with handy features, including a 5x9" precision tracking mouse pad and a built-in phone slot for seamless work or video calls. Plus, enjoy ergonomic support with the integrated cushioned wrist rest.
  • Cool Comfort: Enjoy a stable surface with our lap desk's dual bolster cushion, designed for comfort and airflow, keeping your lap cool during extended use.
  • Durable Surface: Work with confidence on our lap desk's solid surface, featuring a sleek black carbon color, ensuring optimal air circulation to prevent your laptop from overheating.
  • On-the-Go Convenience: With an integrated handle and lightweight design (2.8 lbs), our lap desk is portable for travel or moving around the house, offering flexibility in any space.

Low-pass versus high-pass behavior

  • Low-pass: reduces fine texture, noise, and abrupt intensity variation. Blur and denoising filters are low-pass operations.
  • High-pass or derivative: responds to rapid changes, making edges and fine detail more visible.

OpenCV summarizes the distinction this way: low-pass filters remove noise and blur images, while high-pass filters help find edges.

Build a visual test image first

Use separate examples for different noise models. Gaussian noise creates many small, random intensity deviations; salt-and-pepper noise creates isolated very bright and very dark pixels. A filter that performs well on one may perform poorly on the other.

import cv2 as cv
import numpy as np

print("OpenCV", cv.__version__)

gray = cv.imread("input.jpg", cv.IMREAD_GRAYSCALE)
if gray is None:
    raise FileNotFoundError("input.jpg")

rng = np.random.default_rng(7)
gaussian_noise = rng.normal(0, 20, gray.shape)
noisy_gaussian = np.clip(gray.astype(np.float32) + gaussian_noise, 0, 255).astype(np.uint8)

noisy_sp = gray.copy()
mask = rng.random(gray.shape)
noisy_sp[mask < 0.02] = 0
noisy_sp[mask > 0.98] = 255

cv.imwrite("original.png", gray)
cv.imwrite("gaussian_noise.png", noisy_gaussian)
cv.imwrite("salt_pepper_noise.png", noisy_sp)

Keep the original and both noisy images in your montage. That makes it possible to tell whether a filter removed the intended noise or merely erased legitimate texture.

Box (mean) filtering

A box filter gives every pixel in its neighborhood equal weight. It is simple and fast, but it softens edges and often looks less natural than a Gaussian blur because distant neighbors matter just as much as close ones.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
box_kernel = np.ones((5, 5), np.float32) / 25
box = cv.filter2D(noisy_gaussian, -1, box_kernel)
cv.imwrite("box_5x5.png", box)

What to look for

  • Large flat regions become smoother.
  • Thin lines and corners lose contrast.
  • A larger kernel increases blur and the amount of detail removed.

Use a box filter when speed and simplicity matter more than carefully controlled edge appearance.

Rank #2
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Gaussian filtering

A Gaussian filter weights nearby pixels more heavily than distant pixels. The sigma value is the standard deviation that controls the spatial scale: increasing it broadens the smoothing and removes progressively finer detail. The kernel size must be large enough to contain the useful part of that Gaussian.

gaussian_sigma1 = cv.GaussianBlur(noisy_gaussian, (0, 0), sigmaX=1)
gaussian_sigma3 = cv.GaussianBlur(noisy_gaussian, (0, 0), sigmaX=3)
cv.imwrite("gaussian_sigma1.png", gaussian_sigma1)
cv.imwrite("gaussian_sigma3.png", gaussian_sigma3)

Compare sigma 1 with sigma 3

Place the original, the sigma-1 result, and the sigma-3 result side by side. Sigma 1 should retain more texture while reducing small fluctuations; sigma 3 should look visibly softer and suppress more fine structure. These are visual tendencies, not a guarantee for every image or noise level.

When Gaussian blur is the better default

Choose it for general-purpose smoothing, for preparing an image for a derivative operator, or when the noise is spread throughout the image rather than concentrated in isolated pixels. It is also the smoothing stage used conceptually by Canny edge detection.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Median filtering for impulse noise

A median filter replaces the center pixel with the median of the values in its neighborhood. Because an isolated black or white impulse is an extreme value, it is often rejected while a real step edge survives better than it would under averaging.

median = cv.medianBlur(noisy_sp, 5)
cv.imwrite("median_5x5.png", median)

What the before-and-after image should reveal

  • Salt-and-pepper dots disappear when the neighborhood is large enough.
  • Step edges usually remain more distinct than with a same-sized mean filter.
  • Fine lines, small text, and tiny features can still vanish if the kernel is too large.

Median filtering is a nonlinear operation, so a single fixed convolution kernel cannot describe it. Use an odd kernel size supported by the implementation, such as 3 or 5, and increase it only when the impulses are large or dense enough to justify the extra loss of detail.

Rank #3
Sale
Yilador Webcam Cover 3 Pack, 0.03 inch Ultra Thin Laptop Camera Cover Slide
  • Note: Not suitable for MacBooks released after 2023 or devices with a protruding front camera; Not applicable to full-screen or notch-style tempered glass screen protectors; Do not use on the rear camera of the phone.
  • 💻 Why Do You Need a Webcam Cover Slide? — Safeguard your privacy by covering your webcam with our reliable webcam cover when not in use. Don't let anyone secretly watch you. Stay protected!
  • ✅ Thin & Stylish — Enhance your laptop's functionality and aesthetics with our 0.027" ultra-thin webcam covers. Seamlessly close your laptop while adding a touch of sophistication.
  • ✅ Fits Most Devices — Compatible with laptops, phones, tablets, desktops! Keep your privacy intact on Ap/ple, Mac/Book, iPh/one, iP/ad, H/P, L/novo, De/ll, Ac/er, As/us, Sa/msung devices.
  • ✅ 365 Days Protection — Our upgraded 3.0 adhesive ensures a strong hold that won't damage your equipment. Experience reliable, long-term privacy protection day in and day out.

Bilateral filtering when boundaries matter

A bilateral filter weights neighbors by two properties: spatial distance and intensity similarity. Pixels that are close and have similar brightness influence one another strongly; a nearby pixel across a strong boundary has less influence. This can smooth relatively uniform regions while retaining prominent edges better than ordinary blur.

bilateral = cv.bilateralFilter(noisy_gaussian, d=9, sigmaColor=50, sigmaSpace=50)
cv.imwrite("bilateral.png", bilateral)

Parameter trade-offs

  • d: the diameter of the neighborhood used for each pixel.
  • sigmaColor: how different two intensities may be and still be averaged together.
  • sigmaSpace: how far spatially the filter searches.

Large values can produce stronger smoothing and increase runtime. The three parameters interact, so inspect the result rather than assuming one setting transfers unchanged between images. Bilateral filtering preserves strong boundaries more deliberately than Gaussian blur, but it is not guaranteed to preserve every weak edge or texture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sharpening and custom high-pass kernels

Sharpening increases local contrast around transitions. A common 3×3 example is:

0 -1 0
-1 5 -1
0 -1 0
sharpen_kernel = np.array([
    [0, -1, 0],
    [-1, 5, -1],
    [0, -1, 0]
], dtype=np.float32)
sharpened = cv.filter2D(gray, -1, sharpen_kernel)
cv.imwrite("sharpened.png", sharpened)

The boosted center and negative neighbors make edges look crisper, but they can also amplify noise and create halos. Sharpen after suitable denoising when the source contains visible grain; do not treat sharpening as a noise-removal operation.

Sobel and Scharr derivatives

Sobel filters estimate first derivatives. The horizontal derivative, Gx, responds to changes across the x direction; the vertical derivative, Gy, responds to changes across y. Their combined magnitude shows edge strength without favoring one orientation.

Rank #4
AboveTEK Portable Laptop Lap Desk w/Retractable Left/Right Mouse Pad Tray, Non-Slip Heat Shield Tablet Notebook Computer Stand Table w/Sturdy Stable Work Surface for Bed Sofa Couch or Travel
  • Anti-Slip Surface - Transform your laptop into a mobile workstation with the AboveTEK portable laptop lap desk. The anti-slip surface provides a strong grip for laptops up to 15.6 inches(Diagonal), while the double rubber strip on the bottom ensures a stable display or typing experience on your lap, couch, or bed.
  • Retractable Mouse Pad - Retractable laptop mouse pad extends on both directions for the left/right handed with elevation along the edges for stopping mouse from falling off. The size of laptop tray is 14" X 9.7" and the size of mouse pad is 7.4" X 6.1".
  • Effective Heat Shield - The effective heat shield made of sturdy and thick material protects your laptop from overheating. Prioritizes your comfort and safety, an ideal lap pad or board for working anywhere.
  • EASY to Carry and Store - With an ergonomic and simplistic design, the lap desk is portable to store in a backpack. Only 15" in size, 2.2 lb of weight and with slim 0.6 inch thickness, it is ready to be easily carried around.
  • Widely Applicable - The smooth platform accommodates laptops and tablets up to 15.6 inches(Diagonal), making it a versatile accessory and one of the best gifts for mom, dad, students and professionals. Perfect for use as a laptop bed tray or tablet holder anywhere at home, library, or park.
gx = cv.Sobel(gray, cv.CV_64F, 1, 0, ksize=3)
gy = cv.Sobel(gray, cv.CV_64F, 0, 1, ksize=3)
magnitude = cv.magnitude(gx.astype(np.float32), gy.astype(np.float32))

# Convert signed derivatives to viewable 8-bit images.
gx_view = cv.convertScaleAbs(gx)
gy_view = cv.convertScaleAbs(gy)
mag_view = cv.convertScaleAbs(magnitude)
cv.imwrite("sobel_gx.png", gx_view)
cv.imwrite("sobel_gy.png", gy_view)
cv.imwrite("sobel_magnitude.png", mag_view)

How to read the three responses

  • Gx: bright responses mark strong changes in the horizontal derivative direction, commonly seen at vertical boundaries.
  • Gy: bright responses mark changes in the vertical derivative direction, commonly seen at horizontal boundaries.
  • Magnitude: combines both directions into a general edge-strength image.

Scharr derivatives use a different kernel designed to improve rotational behavior for a 3×3 derivative. Use Sobel when its scale and simplicity are sufficient; consider Scharr when a more accurate 3×3 derivative is important.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Canny: a consolidated thin-edge map

The Canny filter is a multi-stage edge detector. It first applies Gaussian-like smoothing to reduce noise, computes intensity gradients, removes non-maximum pixels to thin candidate edges, and then uses hysteresis thresholds to keep connected strong edges while accepting suitable weak pixels.

blurred = cv.GaussianBlur(gray, (0, 0), sigmaX=1.0)
edges_1 = cv.Canny(blurred, threshold1=50, threshold2=150)

blurred_wider = cv.GaussianBlur(gray, (0, 0), sigmaX=2.0)
edges_2 = cv.Canny(blurred_wider, threshold1=50, threshold2=150)

cv.imwrite("canny_sigma1.png", edges_1)
cv.imwrite("canny_sigma2.png", edges_2)

Threshold and sigma effects

A wider Gaussian suppresses more small variation before gradients are computed. That can reduce false edges in a noisy image, but it can also remove narrow or low-contrast boundaries. Raising thresholds generally rejects weaker responses and can create gaps; lowering them retains more candidates but can admit texture and noise. The useful settings depend on the image and the edge map your next algorithm needs.

OpenCV exposes the thresholds directly through cv.Canny; pre-blurring controls the practical smoothing width. Compare two sigma values or two threshold pairs in separate panels, and label them so a viewer can distinguish false edges from missed edges.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Visualize the same operations with scikit-image

scikit-image offers functional equivalents with a NumPy-friendly API. Print the installed version in notebooks and scripts because names, defaults, and accepted arguments can evolve.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
LAPGEAR Home Office Lap Desk – Pink, Fits 15.6” Laptops
  • Spacious Design: Measuring 21.1" wide and 12" deep, our lap desk comfortably fits most laptops up to 15.6". Extra room for accessories ensures convenience.
  • Enhanced Functionality: Packed with handy features, including a 5x9" precision tracking mouse pad and a built-in phone slot for seamless work or video calls. Plus, enjoy laptop support with the integrated device ledge.
  • Cool Comfort: Enjoy a stable surface with our lap desk's dual bolster cushion, designed for comfort and airflow, keeping your lap cool during extended use.
  • Durable Surface: Work with confidence on our lap desk's solid surface, featuring a blush pink color, ensuring optimal air circulation to prevent your laptop from overheating.
  • On-the-Go Convenience: With an integrated handle and lightweight design (2.14 lbs), our lap desk is portable for travel or moving around the house, offering flexibility in any space.
import skimage
from skimage import color, filters, feature, io

print("scikit-image", skimage.__version__)
image = io.imread("input.jpg")
if image.ndim == 3:
    image = color.rgb2gray(image)

smooth = filters.gaussian(image, sigma=2)
sobel_response = filters.sobel(image)
edge_map = feature.canny(image, sigma=2, low_threshold=0.1, high_threshold=0.2)

io.imsave("skimage_gaussian.png", (smooth * 255).astype("uint8"))
io.imsave("skimage_sobel.png", (sobel_response * 255).astype("uint8"))
io.imsave("skimage_canny.png", (edge_map * 255).astype("uint8"))

For a fair visual comparison, use the same source image, grayscale conversion, noise condition, and display range for every result. A derivative image is signed internally, so normalize or take an absolute value before displaying it.

Comparison: which filter should you start with?

Operation Best-matched problem Edge preservation Detail lost Computational cost Parameter sensitivity
Box/mean Simple, general smoothing Low Moderate to high as the kernel grows Low Mostly kernel-size driven
Gaussian Distributed noise and pre-smoothing Moderate Controlled by sigma and kernel size Low to moderate Moderate; sigma sets the scale
Median Salt-and-pepper (impulse) noise Often better than averaging at step edges Small features can disappear with large windows Moderate Kernel size and noise density matter
Bilateral Smoothing while retaining stronger boundaries Higher than ordinary blur for suitable settings Depends strongly on intensity and spatial sigmas Higher than basic blur High; parameters interact
Sobel/Scharr Directional gradients and edge strength Not a denoiser; noise can create responses Does not produce a smoothed image Low Kernel scale and pre-smoothing matter
Canny Thin, consolidated edge map Designed to localize selected boundaries Weak edges may be rejected Moderate Gaussian width and low/high thresholds interact

These are task-oriented defaults, not guarantees. If you know the noise is impulse-like, test median first; for broad random variation, test Gaussian; when preserving strong boundaries is central, test bilateral; use Sobel or Scharr when orientation matters; and use Canny when a thin binary edge map is the desired output.

Border handling is part of the result

A kernel extends beyond the image at the first and last rows and columns. OpenCV therefore has to extrapolate or reflect values at the boundary. Functions expose border-related options differently, and their documented defaults can differ. If edge pixels matter, set or record the border mode explicitly where the function permits it, and inspect the outer few pixels in your visual comparison rather than judging only the center of the image.

A practical visualization workflow

  1. Keep a reference: display the original grayscale image at the same scale as every response.
  2. Separate noise cases: create one Gaussian-noise example and one salt-and-pepper example.
  3. Label parameters: put kernel size, sigma, neighborhood diameter, or thresholds in each panel title.
  4. Show directional derivatives: include Sobel Gx, Gy, and magnitude, not just one edge-looking image.
  5. Compare Canny settings: vary smoothing width or threshold pairs and mark where texture becomes false edges or genuine boundaries disappear.
  6. Check borders: zoom into image boundaries to catch padding artifacts.

This sequence makes the input, filter response, and trade-off visible instead of reducing every method to a single “before and after” claim.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Further reading

For a broader treatment of image formation, filtering, geometry, recognition, and applications, Richard Szeliski’s Computer Vision: Algorithms and Applications, second edition, is a substantial reference. Springer’s 2022 description notes 1,500 new citations and 200 new figures in that edition. It is useful when you need the mathematical context behind the concise operations shown here.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.