Label

Overview

The Connected Components Labeling sample demonstrates how to identify and label distinct regions in binary images using CV-CUDA.

Usage

Basic Usage

python3 label.py -i input.jpg -o labeled.jpg

Command-Line Arguments

Argument

Short Form

Default

Description

--input

-i

tabby_tiger_cat.jpg

Input image file path

--output

-o

cvcuda/.cache/cat_labeled.jpg

Output image file path with color-coded labels

Implementation

Preprocessing

# 1. Grayscale and histogram equalize the image
nhwc_image: cvcuda.Tensor = cvcuda.stack([input_image])
gray_image: cvcuda.Tensor = cvcuda.cvtcolor(
    nhwc_image, cvcuda.ColorConversion.RGB2GRAY
)
histogram_image: cvcuda.Tensor = cvcuda.histogrameq(gray_image, cvcuda.Type.U8)

# 2. Compute threshold
tp_host = np.array([128], dtype=np.float64)
tp = cvcuda.Tensor((1,), dtype=np.float64, layout="N")
cuda_memcpy_h2d(tp_host, tp.cuda())

mp_host = np.array([255], dtype=np.float64)
mp = cvcuda.Tensor((1,), dtype=np.float64, layout="N")
cuda_memcpy_h2d(mp_host, mp.cuda())

threshold_image: cvcuda.Tensor = cvcuda.threshold(
    histogram_image, tp, mp, cvcuda.ThresholdType.BINARY
)

Steps: 1. Convert to grayscale 2. Histogram equalization for contrast 3. Threshold to create binary image

Connected Components

# 3. Connected components labeling
cc_labels, _, _ = cvcuda.label(threshold_image)

Output: * cc_labels: Integer label for each pixel (0=background, 1,2,3…=objects) * Second output: Number of components found * Third output: Statistics (not used in this sample)

../../_images/tabby_tiger_cat.jpg

Original Input Image

../../_images/cat_labeled.jpg

Output with Labeled Components

Visualization

# 4. Generate and save the visualization image
argb_image: cvcuda.Tensor = color_labels_nhwc(cc_labels)
argb_image = argb_image.reshape((*argb_image.shape[1:],), "HWC")
write_image(argb_image, args.output)

The output image shows each connected component in a unique random color.

CV-CUDA Operators Used

Operator

Purpose

cvcuda.cvtcolor()

Convert RGB to grayscale

cvcuda.histogrameq()

Enhance contrast

cvcuda.threshold()

Create binary image

cvcuda.label()

Find connected components

Common Utilities Used

See Also