Histogram Equalization

Overview

The Histogram Equalization sample demonstrates GPU-accelerated contrast enhancement using CV-CUDA’s histogrameq operator. The operator redistributes pixel intensities so the cumulative histogram of the output image is approximately uniform, improving global contrast without any parameter tuning.

Usage

Basic Usage

Equalize an image with the default input:

python3 histogrameq.py

Custom Input

Specify a custom input and output path:

python3 histogrameq.py -i input.jpg -o cat_histogrameq.jpg

Command-Line Arguments

Argument

Short Form

Default

Description

--input

-i

tabby_tiger_cat.jpg

Input image file path

--output

-o

cvcuda/.cache/cat_histogrameq.jpg

Output image file path

Implementation

Histogram Equalization

# Histogram equalization in CVCUDA works on single-channel (grayscale) or
# multi-channel tensors in HWC/NHWC layout with U8 dtype.
# We batch the HWC image into NHWC so we can use cvtcolor for RGB->GRAY conversion.
nhwc_image: cvcuda.Tensor = cvcuda.stack([input_image])
gray_image: cvcuda.Tensor = cvcuda.cvtcolor(
    nhwc_image, cvcuda.ColorConversion.RGB2GRAY
)

Key points:

  1. Grayscale conversion: cvcuda.cvtcolor with RGB2GRAY is applied first because histogram equalization is most meaningful on a single luminance channel.

  2. Batched NHWC layout: The HWC image is wrapped in a batch dimension via cvcuda.stack so the cvtcolor operator (which expects NHWC) can be used directly.

  3. dtype keyword: cvcuda.histogrameq requires an explicit dtype argument when operating on a Tensor; for image-batch inputs the argument is optional.

  4. Host-side channel replication: The equalized single-channel output is downloaded, tiled to three channels on the CPU, and re-uploaded as an HWC tensor so write_image can encode a standard JPEG.

  5. Zero-copy back-path: cuda_memcpy_h2d and cuda_memcpy_d2h avoid any Python-level buffer copies beyond the mandatory host round-trip needed for channel replication.

Expected Output

The output shows the original image converted to grayscale with equalized contrast:

../../_images/tabby_tiger_cat.jpg

Original Input Image

../../_images/cat_histogrameq.jpg

Output: Histogram-Equalized Grayscale

CV-CUDA Operators Used

Operator

Purpose

cvcuda.histogrameq()

Equalize pixel-intensity histogram to enhance global contrast

cvcuda.cvtcolor()

Convert RGB image to single-channel grayscale before equalization

cvcuda.stack()

Wrap a single HWC tensor into an NHWC batch for cvtcolor

Common Utilities Used

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

  • write_image() - Save equalized image

  • cuda_memcpy_d2h - Download equalized tensor to NumPy for channel replication

  • cuda_memcpy_h2d - Upload replicated RGB tensor back to GPU for encoding

See Also