Skip to navigation

Pixel and Color Conversion

View as MarkdownOpen in Claude
You will learn
  • How pixel representation differs from color-space identity
  • How to compose GPU conversions for YUV, RGB(A), and HDR encodings
  • How to declare valid bits, chroma siting, alpha, and luminance
  • What conversion can and cannot do for previously tone-mapped images

PixelFormatConverterOp changes pixel representation while preserving the declared color space. ColorSpaceConverterOp changes transfer function and color primaries. Both belong to holoscan::vision, use Input<schema::ImageT> and Output<schema::ImageT>, and submit CUDA work on the HSDK stream using bounded runtime output pools. They perform no host pixel staging or host synchronization.

For a camera branch of the sensor-fusion pipeline, preserve the frame’s capture time and metadata through both operators. Their output carries the original header, ROI, exposure, gain, frame and trace identities, and sample flags. Pixel conversion changes the encoding, valid-bit count, planes, and applicable YUV metadata. Color conversion also updates color_space.

Pixel representation

Include <holoscan/vision/pixel_format_converter_op.hpp>. PixelFormat separates PixelLayout, PixelElementType, and significant_bits; YUV descriptors also carry schema::ColorRange and schema::ChromaLocation.

LayoutElement typeWire encoding
RGB, BGR, RGBA, BGRAU8, U16, F32Corresponding RGB8/RGB16/RGB32F family
GRAYU8, U16MONO8, MONO16
YUV444F32YUV32F
YUYV, UYVY, NV12, I420U8Matching named encoding
P010U16P010
RGBA1010102Packed32RGBA1010102

Every source/destination combination in this table is supported by the pixel converter. CUSTOM, Bayer, planar RGB, and signed components are rejected; unknown U16 or F32 precision is rejected unless the operator declares it (see Declaring metadata the producer left unset). significant_bits = 0 retains the schema convention of full component width. U16 also accepts 10 or 12 significant bits. P010 always resolves to 10; RGBA1010102 accepts zero or 10 for its fixed color fields, never 32.

The conversion operators interpret integer components as normalized codes. Generic U16 with 10/12 valid bits is MSB-aligned: shift 10-bit codes left by six and 12-bit codes left by four, including U16 alpha. Generated padding bits are zero. P010 stores its codes in bits 15–6. RGBA1010102 stores one little-endian 32-bit word, with R in bits 0–9, G in 10–19, B in 20–29, and alpha in 30–31. Its kPacked32 element type describes a whole word, not four U32 channels.

Repack LSB-aligned U16 sources before conversion by shifting codes left by 6 or 4; declaring full width instead leaves the same darkness. significant_bits cannot distinguish alignment, and the operators never infer it from values: an LSB-aligned 10- or 12-bit frame from an external producer such as V4L2 Y10/Y12, declared as 10 or 12 bits, decodes 64 or 16 times too dark instead of failing. An unscaled ConvertToOp widening cast to U16 publishes 8 bits, which the converters reject until the frame is rescaled. Storage type alone does not identify HDR: the transfer function comes from ImageT::color_space.

Image.significant_bits is coded precision: the valid-bit width a consumer uses to decode each component. The converters normalize every component into the requested width, so their output reports that width (zero for a full container, 10 for P010), which is what the next consumer needs to decode MSB-aligned codes. The field does not estimate the information carried from the source: an 8-bit NV12 frame converted to 12-bit RGBA16 reports 12 because those codes decode only as 12 bits. The scalar Vision operators publish unknown precision (255) after a value-changing transform because their unscaled casts leave no defined width. The converters accept that unknown value from 8-bit and fixed-field packed inputs, whose representation admits only one width, so a bilinear ResizeOp output still converts; U16 and F32 inputs with unknown precision are rejected because their code width or normalization cannot be recovered from storage, unless the operator’s input_significant_bits declares that width.

Each input is one frame. Single-plane input can use a contiguous flat tensor, a pitched rank-two row array, or a typed HWC tensor with exact width and channel axes. Components within rows are tightly packed. Multi-planar input uses plane_layouts to address nonoverlapping, possibly padded planes within one contiguous tensor backing. Offsets, alignment, row widths, plane sizes, and tensor containment are checked. Batches and separately allocated planes must be split or gathered upstream: the input port declares the same rank-4 tensor bound as the other Vision image operators, so ResizeOp and its peers connect directly, but a batched [N, H, W, C] frame is rejected when it arrives. Output is contiguous HWC, a rank-two U32 array for RGBA1010102, or a flat backing with explicit planes for NV12/I420/P010. YUYV/UYVY output uses U8 HWC shape {H, 2 * ceil(W / 2), 2}: two bytes per pixel, with an extra padded pixel for odd widths. Input also accepts the equivalent macropixel shape {H, ceil(W / 2), 4}.

YUV range and chroma

Every YUV input and destination requires FULL or LIMITED range. Subsampled YUV also requires CENTER, LEFT, or TOP_LEFT siting. These are separate from color primaries and transfer.

RangeLumaChroma
Full integerZero through the maximum component codeNeutral at half the code count: 128 for U8, 512 for P010
Limited integer16–235 for U8, 64–940 for P01016–240 for U8, 64–960 for P010; neutral 128 or 512
Full YUV444 F320–10–1, neutral 0.5
Limited YUV444 F3216/255–235/25516/255–240/255, neutral 128/255

Subsampled extents round up, including odd widths and heights. YUYV/UYVY’s final macropixel repeats the last luma sample when width is odd. For 4:2:0, chroma locations within a cell are CENTER = (0.5, 0.5), LEFT = (0, 0.5), and TOP_LEFT = (0, 0), measured from the first luma pixel center. For 4:2:2 the vertical coordinate is zero. Downsampling integrates a box one chroma cell wide (two luma pixels on each subsampled axis) centered at that location; upsampling uses linear interpolation. Both replicate edge samples. Conversions between identical chroma lattices preserve those chroma samples directly. Only an axis whose chroma spacing or siting changes is resampled. A siting change at the same spacing uses linear interpolation: shifting between centered and left-aligned chroma moves by a quarter of a chroma cell horizontally, and changing between LEFT and TOP_LEFT does the same vertically for 4:2:0.

RGB(A) → YUV/gray and YUV → RGB(A) conversion requires ImageT::color_space to declare encoded luma coefficients: REC601, SRGB, REC709, REC2020, REC2020_PQ, or REC2020_HLG. These operations preserve color-space identity and do not decode the transfer function. The matrix follows the tag: REC601 selects BT.601 coefficients (Kr 0.299, Kb 0.114), SRGB and REC709 select BT.709 (0.2126, 0.0722), and the REC2020 family selects BT.2020 (0.2627, 0.0593). sYCC (IEC 61966-2-1) and JPEG/JFIF encode sRGB primaries with the BT.601 matrix, which the schema cannot yet express: tag such YUV frames REC601 for the conversion, and when the RGB(A) result feeds ColorSpaceConverterOp (which rejects REC601), insert a custom operator that retags it SRGB. No shipped operator rewrites a tag the Image already carries. YUV → YUV, gray ↔ YUV, RGB channel swaps, and numeric representation changes do not use luma coefficients and accept an unspecified color space.

Declaring metadata the producer left unset

Ordinary pipelines produce frames that leave a required field unset: BayerDemosaicOp publishes unknown precision (255) and an unspecified color space for its U16 output, and external NV12 or YUYV producers written before color_range and chroma_location existed leave both unspecified. The declared-input parameters supply those facts on the converter itself:

ParameterOperatorsApplies when the Image has
input_color_spaceBothcolor_space == UNSPECIFIED
input_color_rangePixelFormatConverterOpcolor_range == UNSPECIFIED
input_chroma_locationPixelFormatConverterOpchroma_location == UNSPECIFIED
input_significant_bitsBothsignificant_bits == 255 (unknown)

A declaration never overrides a tagged frame. A frame whose tag disagrees with a declaration is rejected on that frame with a diagnostic naming the field and both values, for example input Image.color_range LIMITED disagrees with input_color_range FULL; zero and the container width are the same spelling of significant_bits, and a declared width that does not fit the frame’s storage is reported against the parameter. Nothing is inferred from pixel values. The output publishes the resolved color space, so a ColorSpaceConverterOp placed after a declared PixelFormatConverterOp needs no declaration of its own. input_significant_bits names the valid-bit width of the frame’s codes (8, 10, 12, 16 or 32), which the converters read MSB-aligned as described above; 0 declares nothing.

On PixelFormatConverterOp, a declared input_color_space also proves that color space for successful outputs during graph compilation. Changing it requires recompilation. Without a declaration, the output preserves the input color-space evidence; missing evidence remains unresolved rather than acquiring an inferred color space.

Alpha

Both parameter structs provide alpha, a finite normalized constant in [0, 1], defaulting to 1 (opaque). It is inserted only when a source without alpha gains an alpha channel. Existing alpha is preserved, with scaling and nearest-code quantization when representations change; removing alpha discards it. RGBA1010102 quantizes alpha to its two-bit field. Color transfer functions and gamut matrices never apply to alpha. A per-pixel mask input is deferred.

Color-space conversion

Include <holoscan/vision/color_space_converter_op.hpp>. Source encoding comes from ImageT::color_space; ColorSpaceConverterOpParams::output_color_space is required. Supported values in either direction are SRGB, REC709, REC2020, REC2020_PQ, and REC2020_HLG. UNSPECIFIED, Rec.601, and unsupported values are rejected by this operator.

The boundary contract is transfer-encoded RGB(A): RGB/BGR order, optional alpha, or packed RGBA1010102. Gray and every YUV representation are rejected. F32 does not mean linear RGB. In particular, encoded Rec.709 must be decoded before gamut conversion; its transfer function is different from sRGB. Rec.709 uses the BT.709 rounded constants, whose transfer curve is discontinuous at linear 0.018 (encoded 0.081 against 0.08125): conversions follow the standard exactly, so a round trip through Rec.709 can move a tone at that breakpoint by up to 2.5e-4, about 16 U16 codes. The default output preserves layout, element type, and valid-bit depth. An optional output_format uses the same descriptor and must also be RGB(A).

The fused kernel decodes the source transfer, transforms D65 primaries in linear light, and encodes the destination transfer. By default REC709 and REC2020 decode with the inverse BT.709/BT.2020 OETF, which yields scene light (ITU-R BT.2087’s first method), and reference_white_nits scales that scene light when crossing into PQ or HLG. The sdr_reference parameter selects the display-referred convention of ITU-R BT.2408 instead. Linear-light arithmetic uses compensated FP32 components to retain accuracy near gamut boundaries; source transfer decoding retains additional precision before rounding. Final encoding uses FP32 transcendental functions while preserving double-precision breakpoint decisions and PQ’s rational expression. There is no U8 intermediate. An explicitly requested U8 destination is quantized only when writing the output. Same-space conversion bypasses transfer and gamut processing.

Luminance conventions

Luminance parameters are never inferred from image content. Zero denotes an omitted parameter. All provided parameters must be finite and nonnegative; the required ones must be positive. When input_color_space is declared, the conversion is known before any frame arrives, so a missing required parameter fails when the operator starts rather than on the first frame; an undeclared source is checked frame by frame.

ParameterUnits and meaningRequired when
reference_white_nitscd/m² represented by SDR decoded RGB (1,1,1); maximum 10000Crossing SDR/HDR in either direction
hlg_peak_nitsHLG display peak in cd/m²; maximum 10000Changing to or from HLG
hlg_system_gammaPositive dimensionless HLG OOTF gammaChanging to or from HLG

PQ uses ST 2084 absolute luminance: encoded one is 10000 cd/m². SDR-to-SDR conversion uses relative linear light and needs no luminance parameter. BT.2100 defines the HLG system gamma as 1.2 for a 1000 cd/m² nominal peak and 1.2 + 0.42 * log10(peak / 1000) otherwise; the operator does not infer it, so pass that value as hlg_system_gamma. HLG uses the BT.2100 inverse OETF and zero-black OOTF: RGB_display = peak * Y_scene^(gamma - 1) * RGB_scene, where Y_scene = 0.2627 R + 0.6780 G + 0.0593 B. The reverse uses display luminance to undo that OOTF before applying the HLG OETF. Clipping occurs at the destination encoding boundary, after inverse OOTF. Same-space conversion requires none of these parameters.

Choosing the SDR luminance convention

Two conventions relate SDR code values to absolute luminance, and both are legitimate. ColorSpaceConverterOpParams::sdr_reference selects one for every conversion between an SDR source (SRGB, REC709, REC2020) and PQ or HLG:

sdr_referenceSDR decodeSDR encodeRec.709 code 0.5 at a 203 cd/m² white
scene (default)Inverse BT.709/BT.2020 OETF to scene light (ITU-R BT.2087, first method)BT.709/BT.2020 OETF52.7 cd/m²
displayBT.1886 display EOTF: a pure 2.4 power with black at zero (ITU-R BT.2408)Inverse BT.1886 EOTF (power 1/2.4)38.5 cd/m²

Choose display to match broadcast practice: BT.2408 converts SDR into PQ or HLG through the BT.1886 EOTF with 100% SDR white at the reference white (typically 203 cd/m²), and converts back through its inverse. Under either convention 100% Rec.709 white reaches the 203 cd/m² reference white (PQ 0.5806, HLG 0.75 at a 1000 cd/m² peak); the conventions differ in the midtones, where the implemented formulas above apply exactly. The option is symmetric, so PQ or HLG converted to Rec.709 under display is the inverse of Rec.709 converted to PQ or HLG under display. SRGB is defined by its display EOTF and decodes identically under both conventions. SDR-to-SDR conversion carries no absolute luminance and ignores the parameter, keeping the sRGB ↔ Rec.709 fast path unchanged.

Clipping and previously tone-mapped input

There is no tone mapping or gamut mapping. F32 source components are clipped to [0, 1] before conversion, with NaN mapping to zero. Out-of-range destination values also clip deterministically. Narrower gamut or SDR output can lose detail. Wider gamut or HDR output cannot recreate missing colors or highlight detail and is not automatic image enhancement.

The operator uses the declared current encoding. It cannot detect, reverse, or compensate for producer-side tone mapping, creative grading, or a custom transfer curve. For example, an HDR frame already tone-mapped and encoded to sRGB upstream must arrive tagged SRGB. The operator then converts that resulting sRGB image. Retaining the original PQ tag on those pixels would apply the wrong transfer decode. A plausible but incorrect supported tag cannot reliably be detected from pixel values. Convert unsupported custom curves upstream first. Standard transfer decoding is not inverse tone mapping, and lost information cannot be recovered.

Compose a camera conversion

This graph fragment assumes graph and an Image-producing camera already exist. Bind each output to a CUDA device when compiling, as shown in the shipped example.

The converters take every required field from the Image and never guess. A producer that leaves a field unset fails on the first frame unless the converter declares it: the input_* parameters below cover a camera whose NV12 frames carry no range or siting tag. For the Bayer path, place BayerDemosaicOp before to_rgb and declare input_significant_bits for its unknown U16 precision together with input_color_space.

using namespace holoscan;
using namespace holoscan::vision;
auto pixels = graph.op<PixelFormatConverterOp>("to_rgb");
pixels.set_params({.output_format = {PixelLayout::kRGBA, PixelElementType::kU16, 12},
.alpha = 0.5F,
.input_color_space = schema::ColorSpace_REC709,
.input_color_range = schema::ColorRange_LIMITED,
.input_chroma_location = schema::ChromaLocation_LEFT});
auto colors = graph.op<ColorSpaceConverterOp>("to_pq");
colors.set_params({.output_color_space = schema::ColorSpace_REC2020_PQ,
.reference_white_nits = 203.F});
auto packed = graph.op<PixelFormatConverterOp>("to_p010");
packed.set_params({.output_format = {PixelLayout::kP010, PixelElementType::kU16, 10,
schema::ColorRange_LIMITED, schema::ChromaLocation_LEFT}});
graph.add_flow(camera->output, pixels->input);
graph.add_flow(pixels->output, colors->input);
graph.add_flow(colors->output, packed->input);

A camera that tags its frames fully can omit the input_* declarations; to_rgb publishes REC709 either way, so to_pq needs none. Add .sdr_reference = SDRReference::kDisplay to to_pq for the BT.2408 display-referred mapping described above.

The complete source is modules/vision/examples/pixel_color_conversion, with C++ and Python variants that author the same graph. It demonstrates NV12 → U16 RGB(A) → PQ → P010, configurable alpha, and correctly tagged previously tone-mapped input. Its inspection sink performs the example’s host copy and wait.

Display and inference consumers

HolovizOp and TensorPreprocessorOp do not read ImageT::color_range. HolovizOp takes the YUV range from its image layer description and TensorPreprocessorOp from its yuv_range parameter, so configure that range to match the converter’s output_format. The preprocessor converts YUV through full-range NPP paths only, and its packed 4:2:2 path is BT.601 only.

HolovizOp RGB(A) image layers admit frames tagged UNSPECIFIED or SRGB; an SRGB tag needs an 8-bit layer configured with ColorSpace::kSRGBNonlinear. Any other tag is matched against the layer’s YUV model, so a REC709-tagged RGBA frame from the pixel converter is rejected and not rendered. For display, follow the pixel converter with ColorSpaceConverterOp configured with output_color_space = srgb and an 8-bit RGBA or BGRA output_format, and render into an sRGB layer.

Packed YUYV/UYVY output for an odd width carries the padded final pixel described above. Neither HolovizOp nor TensorPreprocessorOp accepts it: both require an even width for YUV input, so resize or crop to an even width before packing.

Python authoring

The module-owned holoscan_vision.operators facade exposes both converters through the same parameter schemas as C++. Pixel formats are nested dictionaries; enum fields accept the named values shown below or their numeric values. Omit output_format or pass None to preserve the color converter’s input representation.

from holoscan_vision import operators as vision_ops
# This fragment assumes an existing Holoscan graph and Image-producing camera handle.
pixels = vision_ops.PixelFormatConverterOp(
graph, "to_rgb",
output_format={"layout": "rgba", "element_type": "uint16", "significant_bits": 12},
alpha=0.5,
input_color_space="rec709", input_color_range="limited", input_chroma_location="left",
)
colors = vision_ops.ColorSpaceConverterOp(
graph, "to_pq", output_color_space="rec2020_pq", reference_white_nits=203.0,
sdr_reference="display",
)
graph.add_flow(camera.output, pixels.input)
graph.add_flow(pixels.output, colors.input)

The declared-input keywords (input_color_space, input_color_range, input_chroma_location, input_significant_bits) and sdr_reference take the same named or numeric values as C++.

Configure the output-device bindings before compiling, as for the C++ graph. The Python facade authors the native operators and uses their CUDA execution paths; the example’s python/pixel_color_conversion.py runs the complete NV12 → P010 graph this way.

Backend selection

Compatible U8 and full-width U16 channel reordering, opaque alpha insertion/removal, and gray → RGB/BGR expansion use CV-CUDA CvtColor. U8 grayscale conversion uses it when the image declares BT.601 coefficients. Same-layout full-width integer normalization uses CV-CUDA ConvertTo. Dispatch checks alignment, row pitch and address span before selecting these operations.

Fused CUDA kernels handle configurable alpha, floating-point clipping, partial-bit U16, packing and YUV range/siting. Frequently converted pairs, subsampled YUV to and from RGB(A) at U8 and U16 and same-element-type sRGB ↔ Rec.709, run as compile-time specializations of the same kernel that compute identical results. sRGB ↔ Rec.709 uses a separate FP32 transfer path with precise branch handling near breakpoints. Gamut conversion and HDR retain compensated linear-light arithmetic and higher-precision source transfer decoding. Backend choice preserves the numerical, metadata and asynchronous execution contracts and requires no additional library dependency.

Conversions involving PQ/HLG or a BT.2020 gamut change share one kernel that decodes source transfers and applies HLG luminance scaling in double precision and renormalizes integer source codes exactly. PQ or HLG sources feeding the BT.2020 → Rec.709/sRGB matrix need that precision to preserve the one-code contract near cancelling gamut boundaries. Final encoding reduces double-precision work, but the remaining cost is substantial on GPUs with reduced-rate FP64. On GB10 (Release build for SM120), Rec.709 → PQ costs about 4.8 ms per 1080p frame and 19.2 ms per 2160p frame. These figures illustrate cost structure and are not performance guarantees. See the benchmark provenance and caveats for the build, measurement method, and retained results.

Numerical and execution validation

Tests compare every supported pixel-format pair, including U16 valid-bit variants, with an independent CPU reference at 1×1, odd, and even dimensions and padded source strides. Separate cases cover siting, range, alpha, packing, invalid metadata, and runtime metadata/provenance. Color tests cover all 25 color-space pairs with black, white, primaries, midtones, HDR values, and gamut boundary cancellation. Dense ramps exercise every U16 code and F32 inputs through HDR and wide-gamut pairs under both SDR conventions, including encoding breakpoint neighbors after gamut conversion, and the display convention is checked against the BT.2408 reference-white and BT.1886 midtone values. Declared-input tests run a 12-bit Bayer mosaic through BayerDemosaicOp into both converters with only converter parameters set, convert an untagged NV12 producer, and check that agreeing declarations leave a tagged frame unchanged while a disagreement fails naming the field. The acceptance tolerance is one destination integer code or 1e-4 absolute normalized F32 component error (2e-5 for pixel-only conversion).

CUDA graph capture checks that BGRA8 color conversion consists of one kernel node. The same path writes final values directly, with no pixel workspace or intermediate quantization. Every compile-time kernel specialization is launched beside the generic instantiation over random source codes in both directions and must produce identical bytes. Installed-consumer tests exercise the public C++ headers and library exports. Additional tests cover all U8/U16 integer codes for backend normalization, exhaustive U16 SDR transfer ramps, neighboring floating-point breakpoint values, both CV-CUDA paths under graph capture, and resource reuse across runtime sessions.

The SDK’s vision_conversion_benchmark measures production dispatch at 720p, 1080p and 4K and labels each case with the backend it selected. GPU execution uses warmed CUDA graph replay; a separate measurement reports host submission. Allocations, uploads and synchronization are outside the measured conversion interval. See the benchmark’s source README for reproducible commands and measured results.

Recap

Use the pixel converter for packing, planes, subsampling, dtype and alpha, and the color converter for explicit RGB(A) transfer and gamut conversion. Carry accurate current color metadata, declare YUV range and siting, and supply luminance scales for HDR conversions. Preserve U16 precision through the graph and choose the final representation deliberately.