Adaptive Threshold

Overview

The Adaptive Threshold sample demonstrates locally-adaptive binarisation of a grayscale image using CV-CUDA’s GPU-accelerated adaptive threshold operator. Unlike a global threshold, adaptive thresholding computes a per-pixel threshold from a local neighbourhood, making it robust to uneven illumination. The sample converts the colour input to grayscale, runs cvcuda.adaptivethreshold(), then broadcasts the single-channel result back to RGB for saving as a viewable JPEG.

Usage

Basic Usage

Apply adaptive thresholding to the default cat image:

python3 adaptivethreshold.py

Custom Input

Supply your own image and output path:

python3 adaptivethreshold.py -i input.jpg -o cat_adaptivethreshold.jpg

Command-Line Arguments

Argument

Short Form

Default

Description

--input

-i

tabby_tiger_cat.jpg

Input image file path

--output

-o

cvcuda/.cache/cat_adaptivethreshold.jpg

Output image file path

Implementation

Adaptive Threshold Operation

# adaptivethreshold requires a single-channel (grayscale) U8 input.
# Stack the HWC image into a batch (NHWC) so cvtcolor can operate on it,
# then convert RGB to grayscale.
nhwc_image: cvcuda.Tensor = cvcuda.stack([input_image])
gray_nhwc: cvcuda.Tensor = cvcuda.cvtcolor(
    nhwc_image, cvcuda.ColorConversion.RGB2GRAY
)

Key points:

  1. Single-channel input: cvcuda.adaptivethreshold() requires a U8 single-channel (HWC with C=1 or NHWC with C=1) tensor; colour images must be converted to grayscale first.

  2. Adaptive method: GAUSSIAN_C uses a Gaussian-weighted neighbourhood average; MEAN_C uses a plain mean — both then subtract the constant c to produce the local threshold.

  3. block_size: Must be an odd integer ≥ 3; larger values consider a wider neighbourhood and produce smoother thresholds.

  4. c constant: A positive c makes the threshold stricter (fewer pixels exceed it), producing a sparser binary result; negative values do the opposite.

  5. Viewable output: The single-channel binary result is replicated to three channels on the host before writing so that standard JPEG viewers can display it correctly.

Expected Output

The output is a binary (black-and-white) image where pixel intensity reflects whether each pixel exceeded its local Gaussian-weighted neighbourhood threshold:

../../_images/tabby_tiger_cat.jpg

Original Input Image

../../_images/cat_adaptivethreshold.jpg

Output: Adaptive Threshold (GAUSSIAN_C, block=11, c=2)

CV-CUDA Operators Used

Operator

Purpose

cvcuda.cvtcolor()

Convert RGB input to single-channel grayscale

cvcuda.adaptivethreshold()

Apply locally-adaptive binarisation per pixel

Common Utilities Used

  • read_image() - Load input image as CV-CUDA tensor

  • write_image() - Save thresholded result as JPEG

  • cuda_memcpy_d2h / cuda_memcpy_h2d - Transfer binary result to host for channel replication, then back to device

See Also