Python API#

nvImageCodec Python API reference

This is the Python API reference for the NVIDIA® nvImageCodec library.

Backend#

class nvidia.nvimgcodec.Backend#

Class representing the backend configuration for image processing tasks.

__init__() None#
(backend_kind: nvidia.nvimgcodec.BackendKind, load_hint: typing.SupportsFloat = 1.0, load_hint_policy: nvidia.nvimgcodec.LoadHintPolicy = <LoadHintPolicy.FIXED: 2>) -> None

Overload 1: __init__() -> None

Default constructor initializes the backend with GPU_ONLY backend kind and default parameters.

Overload 2: __init__(backend_kind: nvidia.nvimgcodec.BackendKind, load_hint: typing.SupportsFloat = 1.0, load_hint_policy: nvidia.nvimgcodec.LoadHintPolicy = <LoadHintPolicy.FIXED: 2>) -> None

Constructor with parameters.

Parameters:
  • backend_kind – Specifies the type of backend (e.g., GPU_ONLY, CPU_ONLY).

  • load_hint – Fraction of the batch samples that will be processed by this backend (default is 1.0). This is just a hint for performance balancing, so particular extension can ignore it and work on all images it recognizes.

  • load_hint_policy – Policy for using the load hint, affecting how processing is distributed.

property backend_kind#

The backend kind determines whether processing is done on GPU, CPU, or a hybrid of both.

property load_hint#

Load hint is a fraction representing the portion of the workload assigned to this backend. Adjusting this may optimize resource use across available backends.

property load_hint_policy#

The load hint policy defines how the load hint is interpreted, affecting dynamic load distribution.

BackendKind#

class nvidia.nvimgcodec.BackendKind#

Enum representing backend kinds used in nvImageCodec for decoding/encoding operations.

This enum helps specify where (CPU, GPU, both, or GPU hardware engine) the image processing tasks are executed.

Members:

CPU_ONLY :

Backend kind specifying that decoding/encoding is executed only on CPU.

GPU_ONLY :

Backend kind specifying that decoding/encoding is executed only on GPU.

HYBRID_CPU_GPU :

Backend kind specifying that decoding/encoding is executed on both CPU and GPU.

HW_GPU_ONLY :

Backend kind specifying that decoding/encoding is executed on GPU dedicated hardware engine.

LoadHintPolicy#

class nvidia.nvimgcodec.LoadHintPolicy#

Enum representing load hint policies for backend batch processing.

Load hint is used to calculate the fraction of the batch items that will be picked by this backend and the rest of the batch items would be passed to fallback codec. This is just a hint and a particular implementation can choose to ignore it.

Members:

IGNORE :

Ignore the load hint.

In this policy, the backend does not take the load hint into account when determining batch processing. It functions as if no hint was provided.

FIXED :

Use the load hint to determine a fixed batch size.

This policy calculates the backend batch size based on the provided load hint once, and uses this fixed batch size for processing.

ADAPTIVE_MINIMIZE_IDLE_TIME :

Adaptively use the load hint to minimize idle time.

This policy uses the load hint as an initial starting point and recalculates on each iteration to dynamically adjust and reduce the idle time of threads, optimizing overall resource utilization.

Metadata#

class nvidia.nvimgcodec.Metadata#

Class representing metadata associated with an image.

This class provides access to metadata information such as EXIF data, geographic information, or medical metadata.

__init__() None#
(kind: nvidia.nvimgcodec.MetadataKind, format: nvidia.nvimgcodec.MetadataFormat, buffer: bytes) -> None

Overload 1: __init__() -> None

Default constructor that initializes an empty Metadata object.

Overload 2: __init__(kind: nvidia.nvimgcodec.MetadataKind, format: nvidia.nvimgcodec.MetadataFormat, buffer: bytes) -> None

Constructor that initializes a Metadata object with specified kind, format and buffer.

Parameters:
  • kind – The kind of metadata (e.g. EXIF, GEO, medical formats).

  • format – The format of the metadata (e.g. RAW, JSON, XML).

  • buffer – The metadata content as bytes.

property buffer#

Property to get the metadata content.

Returns:

The metadata content as bytes.

property buffer_size#

Property to get the size of the metadata buffer in bytes.

Returns:

The size of the metadata buffer.

property format#

Property to get the format of the metadata.

Returns:

The metadata format (e.g. RAW, JSON, XML).

property id#

Property to get the ID of the metadata.

Returns:

The metadata ID. For TIFF tag metadata kind, this is the tag ID. For other metadata kinds, it is reserved for future use.

property kind#

Property to get the kind of metadata.

Returns:

The metadata kind (e.g. EXIF, GEO, medical formats).

property value#

Property to get the metadata value converted to a Python type.

Returns:

  • BYTE/UNDEFINED: byte or bytes

  • ASCII: string

  • SHORT: int or list of ints

  • LONG: int or list of ints

  • RATIONAL: tuple (numerator, denominator) or list of tuples

  • SBYTE: int or list of ints

  • SSHORT: int or list of ints

  • SLONG: int or list of ints

  • SRATIONAL: tuple (numerator, denominator) or list of tuples

  • FLOAT: float or list of floats

  • DOUBLE: float or list of floats

  • LONG8/IFD8: int or list of ints

  • SLONG8: int or list of ints

  • Unknown types: raw bytes

Returns None if buffer is empty.

Return type:

The metadata value converted to an appropriate Python type based on the metadata type

property value_count#

Property to get the number of values in the metadata.

Returns:

The number of values. For TIFF tag metadata, this represents the count of values for the tag.

property value_type#

Property to get the type of the metadata when format is RAW.

Returns:

The metadata type (e.g. BYTE, SHORT, LONG, etc.).

MetadataFormat#

class nvidia.nvimgcodec.MetadataFormat#

Enum representing different metadata formats.

The format specifies how the metadata is encoded (e.g. RAW, JSON, XML).

Members:

UNKNOWN :

Unknown metadata format.

RAW :

Raw binary metadata format.

JSON :

JSON metadata format.

XML :

XML metadata format.

XMP :

XMP metadata format.

MetadataKind#

class nvidia.nvimgcodec.MetadataKind#

Enum representing different metadata kinds.

The kind specifies the type of metadata (e.g. EXIF, GEO, medical formats).

Members:

UNKNOWN :

Unknown metadata kind.

TIFF_TAG :

TIFF tag metadata.

ICC_PROFILE :

ICC profile metadata.

EXIF :

EXIF metadata containing camera settings and image capture information. [Reserved for future use]

GEO :

Geographic metadata as in GeoTIFF.

MED_APERIO :

Medical metadata in Aperio format for whole slide imaging.

MED_PHILIPS :

Medical metadata in Philips format for whole slide imaging.

MED_VENTANA :

Medical metadata in Ventana format for whole slide imaging.

MED_LEICA :

Medical metadata in Leica format for whole slide imaging.

MED_TRESTLE :

Medical metadata in Trestle format for whole slide imaging.

TIFF_TAG_LIST :

List of available TIFF tag IDs in the image.

MetadataType#

class nvidia.nvimgcodec.MetadataType#

Enum representing different metadata types.

Metadata types as defined for TIFF tag types in TIFF specification.

Members:

UNKNOWN :

Unknown metadata type.

BYTE :

8-bit unsigned integer.

ASCII :

8-bit byte containing 7-bit ASCII code; last byte must be NUL.

SHORT :

16-bit (2-byte) unsigned integer.

LONG :

32-bit (4-byte) unsigned integer.

RATIONAL :

Two LONGs: numerator and denominator.

SBYTE :

8-bit signed (twos-complement) integer.

UNDEFINED :

8-bit byte, value depends on field definition.

SSHORT :

16-bit (2-byte) signed (twos-complement) integer.

SLONG :

32-bit (4-byte) signed (twos-complement) integer.

SRATIONAL :

Two SLONGs: numerator and denominator.

FLOAT :

4-byte IEEE floating point value.

DOUBLE :

8-byte IEEE floating point value.

IFD :

4-byte (32-bit) unsigned integer used for IFD offsets.

LONG8 :

8-byte (64-bit) unsigned integer (BigTIFF).

SLONG8 :

8-byte (64-bit) signed integer (BigTIFF).

IFD8 :

8-byte (64-bit) unsigned integer used for IFD offsets (BigTIFF).

CodeStream#

class nvidia.nvimgcodec.CodeStream#

Class representing a coded stream of image data.

This class provides access to image informations such as dimensions, codec, and tiling details. It supports initialization from bytes, numpy arrays, or file path.

__init__(
bytes: bytes,
bitstream_offset: SupportsInt | None = None,
) None#
(array: typing.Annotated[numpy.typing.ArrayLike, numpy.uint8], bitstream_offset: typing.SupportsInt | None = None) -> None
(filename: os.PathLike | str | bytes, bitstream_offset: typing.SupportsInt | None = None) -> None
(pre_allocated_size: typing.SupportsInt = 0, pin_memory: bool = True) -> None

Overload 1: __init__(bytes: bytes, bitstream_offset: typing.SupportsInt | None = None) -> None

Initialize a CodeStream using bytes as input.

Note: image_idx and region are not supported here. Use get_sub_code_stream() to select a specific image or region after creation.

Parameters:
  • bytes – The byte data representing the encoded stream.

  • bitstream_offset – For TIFF files, nonzero byte offset of one IFD to select. Defaults to None (parse from file header); 0 is equivalent to None. A nonzero bitstream_offset creates a one-image view and num_images reports 1. Query the root CodeStream for the total root page count.

Overload 2: __init__(array: typing.Annotated[numpy.typing.ArrayLike, numpy.uint8], bitstream_offset: typing.SupportsInt | None = None) -> None

Initialize a CodeStream using a numpy array of uint8 as input.

Note: image_idx and region are not supported here. Use get_sub_code_stream() to select a specific image or region after creation.

Parameters:
  • array – The numpy array containing the encoded stream.

  • bitstream_offset – For TIFF files, nonzero byte offset of one IFD to select. Defaults to None (parse from file header); 0 is equivalent to None. A nonzero bitstream_offset creates a one-image view and num_images reports 1. Query the root CodeStream for the total root page count.

Overload 3: __init__(filename: os.PathLike | str | bytes, bitstream_offset: typing.SupportsInt | None = None) -> None

Initialize a CodeStream using a file path as input.

Note: image_idx and region are not supported here. Use get_sub_code_stream() to select a specific image or region after creation.

Parameters:
  • filename – The file path to the encoded stream data.

  • bitstream_offset – For TIFF files, nonzero byte offset of one IFD to select. Use offsets from next_ifd_offset or subifd_offsets. Defaults to None (parse from file header); 0 is equivalent to None. A nonzero bitstream_offset creates a one-image view and num_images reports 1. Query the root CodeStream for the total root page count.

Overload 4: __init__(pre_allocated_size: typing.SupportsInt = 0, pin_memory: bool = True) -> None

Initialize a CodeStream for encoding output.

Parameters:
  • pre_allocated_size – The size of the pre-allocated memory. (default: 0)

  • pin_memory – If True, the output memory will be pinned. (default: True)

property capacity#

The capacity of the internal buffer in bytes.

property chroma_subsampling#

The chroma subsampling of the encoded image.

property codec_name#

Image format.

property color_spec#

Property to get the color specification for the code stream.

This determines the color space or color profile of the image data. For instance, sRGB is a common color specification.

Please notice that color specification of decoded Image depends of color_spec parameter used in decode function so can be different from the one of the code stream.

property dtype#

Data type of samples.

get_sub_code_stream(
image_idx: SupportsInt = 0,
region: nvidia.nvimgcodec.Region | None = None,
bitstream_offset: SupportsInt | None = None,
) nvidia.nvimgcodec.CodeStream#
(view: nvidia.nvimgcodec.CodeStreamView) -> nvidia.nvimgcodec.CodeStream

Overload 1: get_sub_code_stream(image_idx: typing.SupportsInt = 0, region: nvidia.nvimgcodec.Region | None = None, bitstream_offset: typing.SupportsInt | None = None) -> nvidia.nvimgcodec.CodeStream

Get a sub code stream for a specific image index, optional region, and TIFF-specific parameters.

Parameters:
  • image_idx – Index of the image in the code stream. Defaults to 0.

  • region – Optional region of interest within the image.

  • bitstream_offset – For TIFF files, nonzero byte offset of one IFD to select. Use offsets from next_ifd_offset or subifd_offsets. Defaults to None; 0 is equivalent to None. A nonzero bitstream_offset cannot be combined with a nonzero image_idx. A nonzero bitstream_offset creates a one-image view and num_images reports 1. Query the root CodeStream for the total root page count.

Returns:

A new CodeStream object representing the sub code stream.

Overload 2: get_sub_code_stream(view: nvidia.nvimgcodec.CodeStreamView) -> nvidia.nvimgcodec.CodeStream

Get a sub code stream using a CodeStreamView object.

Parameters:

view – A CodeStreamView object specifying the image index, optional region, or TIFF bitstream offset.

Returns:

A new CodeStream object representing the sub code stream.

property height#

The vertical dimension of the entire image in pixels.

property ifd_offset#

the byte offset of the selected image’s IFD.

Returns None for non-TIFF files or when the offset is not available.

Note: on a root CodeStream this triggers a one-time parse of the full root chain; use get_sub_code_stream(0).ifd_offset for lazy single-image access.

Type:

For TIFF files

property next_ifd_offset#

the byte offset of the next sibling IFD.

Returns None if there is no next sibling IFD or the file format is not TIFF.

Note: on a root CodeStream this triggers a one-time parse of the full root chain; use get_sub_code_stream(0).next_ifd_offset for lazy single-image access.

Type:

For TIFF files

property num_channels#

The overall number of channels in the image across all planes.

property num_images#

The number of images in the code stream.

For TIFF root streams, this counts the full root IFD chain on first access and caches the result. TIFF substreams created with image_idx or bitstream_offset are one-image views and report 1. Query the root CodeStream when the total root page count is needed.

property num_tiles_x#

The number of tiles arranged along the horizontal axis of the image.

property num_tiles_y#

The number of tiles arranged along the vertical axis of the image.

property pin_memory#

Whether the internal buffer is pinned.

property precision#

Number of significant bits per sample as declared by the encoded bitstream.

For formats that record a precision below the storage type’s bitdepth (e.g. a 12-bit JPEG 2000 image stored as uint16), this returns the bitstream’s declared precision. When the bitstream does not encode a separate precision, this returns the full bitdepth of the sample data type (8 for uint8, 16 for uint16, etc.).

property sample_format#

The sample format of the code stream indicating how color components are matched to channels and channels to planes.

property size#

The size of the compressed bitstream in bytes.

property subifd_offsets#

list of SubIFD byte offsets for the current image (Tag 330).

SubIFDs typically contain reduced-resolution versions (thumbnails) or other related images. Use these offsets with the bitstream_offset parameter to create a CodeStream for the SubIFD.

Returns an empty list if no SubIFDs exist or if the format is not TIFF.

Note: on a root CodeStream this triggers a one-time parse of the full root chain; use get_sub_code_stream(0) for lazy single-image access.

Example:

cs = nvimgcodec.CodeStream(path)
sub = cs.get_sub_code_stream(image_idx=0)
for offset in sub.subifd_offsets:
    subifd_cs = cs.get_sub_code_stream(bitstream_offset=offset)
Type:

For TIFF files

property tile_height#

The vertical dimension of each individual tile within the image.

property tile_offset_x#

The horizontal offset of the tile grid to the left of the image.

property tile_offset_y#

The vertical offset of the tile grid to the top of the image.

property tile_width#

The horizontal dimension of each individual tile within the image.

property view#

The view of this code stream, if it was created as a sub code stream. Contains the image index and optional region of interest.

Returns:

CodeStreamView object if this is a sub code stream, None otherwise.

property width#

The horizontal dimension of the entire image in pixels.

CodeStreamView#

class nvidia.nvimgcodec.CodeStreamView#

Class representing a view into a code stream, specifying which image and region to access.

A code stream view consists of an image index, optional region of interest, and optional TIFF-specific parameters for SubIFD and IFD-offset access.

__init__(
image_idx: SupportsInt = 0,
region: nvidia.nvimgcodec.Region | None = None,
bitstream_offset: SupportsInt | None = None,
) None#

Constructor that initializes a CodeStreamView with an image index, region, and TIFF-specific parameters.

Parameters:
  • image_idx – Index of the image in the code stream. Defaults to 0.

  • region – Optional region of interest within the image.

  • bitstream_offset – For TIFF files, nonzero byte offset of one IFD to select. Defaults to None (parse from file header); 0 is equivalent to None. A nonzero bitstream_offset combined with a nonzero image_idx is rejected when the view is applied to a CodeStream. A nonzero bitstream_offset creates a one-image view and num_images reports 1; query the root CodeStream for the total root page count.

property bitstream_offset#

Property to get the TIFF IFD bitstream offset.

Returns:

The selected IFD byte offset, or 0 for the default view.

property image_idx#

Property to get the image index in the code stream.

Returns:

The index of the image.

property region#

Property to get the region of interest.

Returns:

The Region object specifying the area of interest, or None if no region is set.

ChromaSubsampling#

class nvidia.nvimgcodec.ChromaSubsampling#

Enum representing different types of chroma subsampling.

Chroma subsampling is the practice of encoding images by implementing less resolution for chroma information than for luma information. This is based on the fact that the human eye is more sensitive to changes in brightness than color.

Members:

CSS_444 :

No chroma subsampling. Each pixel has a corresponding chroma value (full color resolution).

CSS_422 :

Chroma is subsampled by a factor of 2 in the horizontal direction. Each line has its chroma sampled at half the horizontal resolution of luma.

CSS_420 :

Chroma is subsampled by a factor of 2 both horizontally and vertically. Each block of 2x2 pixels shares a single chroma sample.

CSS_440 :

Chroma is subsampled by a factor of 2 in the vertical direction. Each column has its chroma sampled at half the vertical resolution of luma.

CSS_411 :

Chroma is subsampled by a factor of 4 in the horizontal direction. Each line has its chroma sampled at quarter the horizontal resolution of luma.

CSS_410 :

Chroma is subsampled by a factor of 4 horizontally and a factor of 2 vertically. Each line has its chroma sampled at quarter the horizontal and half of the vertical resolution of luma.

CSS_GRAY :

Grayscale image. No chroma information is present.

CSS_410V :

Chroma is subsampled by a factor of 4 horizontally and a factor of 2 vertically. Each line has its chroma sampled at quarter the horizontal and half of the vertical resolution of luma. Comparing to 4:1:0, this variation modifies how vertical sampling is handled. While it also has one chroma sample for every four luma samples horizontally, it introduces a vertical alternation in how chroma samples are placed between rows.

DecodeParams#

class nvidia.nvimgcodec.DecodeParams#

Class to define parameters for image decoding operations.

__init__() None#
(apply_exif_orientation: bool = True, color_spec: nvidia.nvimgcodec.ColorSpec = <ColorSpec.SRGB: 1>, allow_any_depth: bool = False, sample_format: nvidia.nvimgcodec.SampleFormat = <SampleFormat.I_AUTO_COMPONENTS: 2>) -> None

Overload 1: __init__() -> None

Default constructor that initializes the DecodeParams object with default settings.

Overload 2: __init__(apply_exif_orientation: bool = True, color_spec: nvidia.nvimgcodec.ColorSpec = <ColorSpec.SRGB: 1>, allow_any_depth: bool = False, sample_format: nvidia.nvimgcodec.SampleFormat = <SampleFormat.I_AUTO_COMPONENTS: 2>) -> None

Constructor with parameters to control the decoding process.

Parameters:
  • apply_exif_orientation – Boolean flag to apply EXIF orientation if available. Defaults to True.

  • color_spec – Desired color specification for decoding. Defaults to sRGB.

  • allow_any_depth – Boolean flag to allow any native bit depth. If not enabled, the dynamic range is scaled to uint8. Defaults to False.

  • sample_format – Desired output sample format. Selects layout (interleaved I_* vs planar P_*) and color components; see the sample_format property below for the full compatibility rules. Defaults to I_AUTO_COMPONENTS, which derives an interleaved output format from color_spec.

property allow_any_depth#

Boolean property to permit any native bit depth during decoding.

When set to True, it allows decoding of images with their native bit depth. If False, the pixel values are scaled to the 8-bit range (0-255). Defaults to False.

property apply_exif_orientation#

Boolean property to enable or disable applying EXIF orientation during decoding.

When set to True, the image is rotated and/or flipped according to its EXIF orientation metadata if present. Defaults to True.

property color_spec#

Property to get or set the color specification for the decoding process.

This determines the color space or color profile to use during decoding. For instance, sRGB is a common color specification. Defaults to sRGB.

When set to UNCHANGED (or UNKNOWN), the decoder derives the output color_spec from the source codestream..

property sample_format#

Desired output sample format.

Selects both the layout (interleaved I_* vs planar P_*) and the color components produced by the decoder. The value must be compatible with color_spec (matching family), or be I_AUTO_COMPONENTS / P_AUTO_COMPONENTS; otherwise a ValueError is raised when decode() / read() is called.

I_AUTO_COMPONENTS / P_AUTO_COMPONENTS pin only the channel interleaving and let color_spec choose the components; they are the preferred names whenever color_spec is concrete. I_UNCHANGED / P_UNCHANGED are kept as aliases and behave identically.

With *_AUTO_COMPONENTS the decoder picks the sample_format whose color family matches color_spec (e.g. color_spec=SRGB -> I_RGB); when color_spec is also UNCHANGED the source’s layout is preserved where possible, falling back to *_AUTO_COMPONENTS for non-natural source families (SYCC, CMYK, YCCK).

Decoder#

For the decoder options string format (global vs per-decoder, <decoder_id>:<option>=<value>) and the full list of options supported by each decoder (e.g. nvjpeg_cuda_decoder, nvjpeg2k_cuda_decoder, libjpeg_turbo_decoder), see Decoder options format.

class nvidia.nvimgcodec.Decoder#

Decoder for image decoding operations. It provides methods to decode images from various sources such as files or data streams. The decoding process can be configured with parameters like the applied backend or execution settings.

__init__(
device_id: SupportsInt = -1,
max_num_cpu_threads: SupportsInt = 0,
backends: collections.abc.Sequence[nvidia.nvimgcodec.Backend] | None = None,
options: str = '',
) None#

Initialize decoder.

Parameters:
  • device_id – Device id to execute decoding on.

  • max_num_cpu_threads – Max number of CPU threads in default executor (0 means default value equal to number of cpu cores).

  • backends – List of allowed backends. If empty, all backends are allowed with default parameters.

  • options – Optional space-separated decoder options. Use :<option>=<value> for global options (e.g. :num_cuda_streams=4) or options applied by any decoder that supports them (e.g. :fancy_upsampling=1). Use <decoder_id>:<option>=<value> for options that apply only to a specific decoder (e.g. nvjpeg_cuda_decoder:hybrid_huffman_threshold=0). See the documentation section “Decoder options format” for the full list of options per decoder. Default is "" which keeps each extension defaults.

decode(
src: nvidia.nvimgcodec.CodeStream,
*,
image: nvidia.nvimgcodec.Image | None = None,
params: nvidia.nvimgcodec.DecodeParams | None = None,
cuda_stream: SupportsInt = 0,
) object#
(srcs: collections.abc.Sequence[nvidia.nvimgcodec.CodeStream], *, images: collections.abc.Sequence[nvidia.nvimgcodec.Image] | None = None, params: nvidia.nvimgcodec.DecodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> list[object]

Overload 1: decode(src: nvidia.nvimgcodec.CodeStream, *, image: nvidia.nvimgcodec.Image | None = None, params: nvidia.nvimgcodec.DecodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> object

Executes decoding of data from a CodeStream handle.

Parameters:
  • src – CodeStream object.

  • image – Optional Image object to reuse for decoding. If provided, the Image’s buffer will be resized and reused instead of allocating a new Image. Only Images with internally managed buffers can be reused. Defaults to None (create new Image).

  • params – Decode parameters. Defaults to None (use default parameters).

  • cuda_stream – An optional cudaStream_t represented as a Python integer, upon which synchronization must take place. Defaults to 0.

Returns:

nvimgcodec.Image or None if the image cannot be decoded because of any reason.

Overload 2: decode(srcs: collections.abc.Sequence[nvidia.nvimgcodec.CodeStream], *, images: collections.abc.Sequence[nvidia.nvimgcodec.Image] | None = None, params: nvidia.nvimgcodec.DecodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> list[object]

Executes decoding from a batch of CodeStream handles.

Parameters:
  • srcs – List of CodeStream objects

  • images – Optional list of Image objects to reuse for decoding. If provided, the Images’ buffers will be resized and reused instead of allocating new Images. The list must have the same size as srcs. Only Images with internally managed buffers can be reused. Defaults to None (create new Images).

  • params – Decode parameters. Defaults to None (use default parameters).

  • cuda_stream – An optional cudaStream_t represented as a Python integer, upon which synchronization must take place. Defaults to 0.

Returns:

List of decoded nvimgcodec.Image’s. There is None in returned list on positions which could not be decoded.

property device_id#

The CUDA device id this decoder executes on.

get_metadata(
code_stream: nvidia.nvimgcodec.CodeStream,
*,
kind: nvidia.nvimgcodec.MetadataKind | None = None,
) object#
(code_stream: nvidia.nvimgcodec.CodeStream, *, id: typing.SupportsInt, kind: nvidia.nvimgcodec.MetadataKind = <MetadataKind.TIFF_TAG: 1>) -> nvidia.nvimgcodec.Metadata | None

Overload 1: get_metadata(code_stream: nvidia.nvimgcodec.CodeStream, *, kind: nvidia.nvimgcodec.MetadataKind | None = None) -> object

Retrieves metadata from a code stream.

Parameters:
  • code_stream – The code stream to get metadata from.

  • kind – Optional metadata kind to filter by. If specified, only metadata of that kind will be returned.

Returns:

A list of Metadata objects. If no metadata exists or no metadata matches the specified kind, returns an empty list.

Overload 2: get_metadata(code_stream: nvidia.nvimgcodec.CodeStream, *, id: typing.SupportsInt, kind: nvidia.nvimgcodec.MetadataKind = <MetadataKind.TIFF_TAG: 1>) -> nvidia.nvimgcodec.Metadata | None

Retrieves a specific metadata by ID from a code stream.

Parameters:
  • code_stream – The code stream to get metadata from.

  • id – The specific metadata ID to retrieve.

  • kind – Metadata kind. Defaults to TIFF tag kind if not specified.

Returns:

A Metadata object for the specified id, or None if the metadata is not found.

read(
path: nvidia.nvimgcodec.CodeStream,
*,
image: nvidia.nvimgcodec.Image | None = None,
params: nvidia.nvimgcodec.DecodeParams | None = None,
cuda_stream: SupportsInt = 0,
) object#
(paths: collections.abc.Sequence[nvidia.nvimgcodec.CodeStream], *, images: collections.abc.Sequence[nvidia.nvimgcodec.Image] | None = None, params: nvidia.nvimgcodec.DecodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> list[object]

Overload 1: read(path: nvidia.nvimgcodec.CodeStream, *, image: nvidia.nvimgcodec.Image | None = None, params: nvidia.nvimgcodec.DecodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> object

Executes decoding from a CodeStream (typically created from a file).

Parameters:
  • path – CodeStream object (typically from a file path).

  • image – Optional Image object to reuse for decoding. If provided, the Image’s buffer will be resized and reused instead of allocating a new Image. Only Images with internally managed buffers can be reused. Defaults to None (create new Image).

  • params – Decode parameters. Defaults to None (use default parameters).

  • cuda_stream – An optional cudaStream_t represented as a Python integer, upon which synchronization must take place. Defaults to 0.

Returns:

nvimgcodec.Image or None if the image cannot be decoded because of any reason.

Overload 2: read(paths: collections.abc.Sequence[nvidia.nvimgcodec.CodeStream], *, images: collections.abc.Sequence[nvidia.nvimgcodec.Image] | None = None, params: nvidia.nvimgcodec.DecodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> list[object]

Executes decoding from a batch of CodeStreams (typically created from file paths).

Parameters:
  • paths – List of CodeStream objects (typically from file paths).

  • images – Optional list of Image objects to reuse for decoding. If provided, the Images’ buffers will be resized and reused instead of allocating new Images. The list must have the same size as paths. Only Images with internally managed buffers can be reused. Defaults to None (create new Images).

  • params – Decode parameters. Defaults to None (use default parameters).

  • cuda_stream – An optional cudaStream_t represented as a Python integer, upon which synchronization must take place. Defaults to 0.

Returns:

List of decoded nvimgcodec.Image’s. There is None in returned list on positions which could not be decoded.

JpegEncodeParams#

class nvidia.nvimgcodec.JpegEncodeParams#

Class to define parameters for JPEG image encoding operations. It provides settings to configure JPEG encoding such as enabling progressive encoding and optimizing Huffman tables.

__init__() None#
(progressive: bool = False, optimized_huffman: bool = False) -> None

Overload 1: __init__() -> None

Default constructor that initializes the JpegEncodeParams object with default settings.

Overload 2: __init__(progressive: bool = False, optimized_huffman: bool = False) -> None

Constructor with parameters to control the JPEG encoding process.

Parameters:
  • progressive – Boolean flag to use progressive JPEG encoding. Defaults to False.

  • optimized_huffman – Boolean flag to use optimized Huffman tables for JPEG encoding. Defaults to False.

property optimized_huffman#

Boolean property to enable or disable the use of optimized Huffman tables in JPEG encoding.

When set to True, the JPEG encoding process will use optimized Huffman tables which produce smaller file sizes but may require more processing time. Defaults to False.

property progressive#

Boolean property to enable or disable progressive JPEG encoding.

When set to True, the encoded JPEG will be progressive, meaning it can be rendered in successive waves of detail. Defaults to False.

Jpeg2kEncodeParams#

class nvidia.nvimgcodec.Jpeg2kEncodeParams#

Class to define parameters for JPEG2000 image encoding operations.

__init__() None#
(code_block_size: tuple[typing.SupportsInt, typing.SupportsInt] = (64, 64), num_resolutions: typing.SupportsInt = 6, bitstream_type: nvidia.nvimgcodec.Jpeg2kBitstreamType = <Jpeg2kBitstreamType.JP2: 1>, prog_order: nvidia.nvimgcodec.Jpeg2kProgOrder = <Jpeg2kProgOrder.RPCL: 2>, mct_mode: typing.SupportsInt = 0, ht: bool = False) -> None

Overload 1: __init__() -> None

Default constructor that initializes the Jpeg2kEncodeParams object with default settings.

Overload 2: __init__(code_block_size: tuple[typing.SupportsInt, typing.SupportsInt] = (64, 64), num_resolutions: typing.SupportsInt = 6, bitstream_type: nvidia.nvimgcodec.Jpeg2kBitstreamType = <Jpeg2kBitstreamType.JP2: 1>, prog_order: nvidia.nvimgcodec.Jpeg2kProgOrder = <Jpeg2kProgOrder.RPCL: 2>, mct_mode: typing.SupportsInt = 0, ht: bool = False) -> None

Constructor with parameters to control the JPEG2000 encoding process.

Parameters:
  • code_block_size – Tuple representing the height and width of code blocks in the encoding. Defaults to (64, 64).

  • num_resolutions – Number of resolution levels for the image. Defaults to 6.

  • bitstream_type – Type of JPEG2000 bitstream, either raw codestream or JP2 container. Defaults to JP2.

  • prog_order – Progression order for the JPEG2000 encoding. Defaults to RPCL (Resolution-Position-Component-Layer).

  • mct_mode – Integer flag to use multiple component transform. Defaults to 0 (do not use MCT). Valid values are 0 or 1.

  • ht – Boolean flag to use High-Throughput JPEG2000 encoder. Defaults to False (do not use HT).

property bitstream_type#

Property to get or set the JPEG2000 bitstream type.

Determines the type of container or codestream for the encoded image. Defaults to JP2.

property code_block_size#

Property to get or set the code block width and height for encoding.

Defines the size of code blocks used in JPEG2000 encoding. Defaults to (64, 64).

property ht#

Boolean property to enable or disable the High-Throughput JPEG2000 encoder.

When set to True, uses the High-Throughput JPEG2000 encoder. Defaults to False.

property mct_mode#

Integer property to set the multiple component transform mode.

When set to 1, uses the multiple component transform (MCT). Defaults to 0.

It can be used to convert SRGB input color space to SYCC for coding efficiency. Irreversible component transformation used with the 9-7 irreversible filter (lossy compression). Reversible component transformation used with the 5-3 reversible filter (lossless compression).

Multiple component transformation can be used only with SRGB input color space and with chroma subsampling 444.

property num_resolutions#

Property to get or set the number of resolution levels.

Determines the number of levels for the image’s resolution pyramid. Each additional level represents a halving of the resolution. Defaults to 6.

property prog_order#

Property to get or set the progression order for the JPEG2000 encoding.

Specifies the order in which the encoded data is organized. It can affect decoding performance and streaming. Defaults to RPCL.

QualityType#

class nvidia.nvimgcodec.QualityType#

Supported quality types (algorithms), which determines how quality_value is interpreted..

Members:

DEFAULT :

Each plugin decides its default quality setting. quality_value is ignored in this case.

LOSSLESS :

Image encoding is reversible and keeps original image quality. quality_value is ignored, except for:

  • the CUDA TIFF encoder backend, for which quality_value = 0 means no compression, and quality_value = 1 means LZW compression,

  • the CPU PNG encoder backend, for which quality_value can be in range from 0 (lowest compression ratio, fastest) to 9 (highest compression ratio, slowest).

QUALITY :

quality_value is interpreted as JPEG-like quality in range from 1 (worst) to 100 (best).

QUANTIZATION_STEP :

quality_value is interpreted as quantization step (by how much pixel data will be divided). The higher the value, the worse quality image is produced.

PSNR :

quality_value is interpreted as desired Peak Signal-to-Noise Ratio (PSNR) target for the encoded image. The higher the value, the better quality image is produced. Value should be positive.

SIZE_RATIO :

quality_value is interpreted as desired encoded image size ratio compared to original size, should be floating point in range (0.0, 1.0). E.g. value 0.1 means target size of 10% of original image.

EncodeParams#

class nvidia.nvimgcodec.EncodeParams#

Class to define parameters for image encoding operations.

__init__() None#
(quality_type: nvidia.nvimgcodec.QualityType = <QualityType.DEFAULT: 0>, quality_value: typing.SupportsFloat = 0, color_spec: nvidia.nvimgcodec.ColorSpec = <ColorSpec.UNKNOWN: 0>, chroma_subsampling: nvidia.nvimgcodec.ChromaSubsampling | None = None, jpeg_encode_params: nvidia.nvimgcodec.JpegEncodeParams | None = None, jpeg2k_encode_params: nvidia.nvimgcodec.Jpeg2kEncodeParams | None = None, tile_width: typing.SupportsInt | None = None, tile_height: typing.SupportsInt | None = None) -> None

Overload 1: __init__() -> None

Default constructor that initializes the EncodeParams object with default settings.

Overload 2: __init__(quality_type: nvidia.nvimgcodec.QualityType = <QualityType.DEFAULT: 0>, quality_value: typing.SupportsFloat = 0, color_spec: nvidia.nvimgcodec.ColorSpec = <ColorSpec.UNKNOWN: 0>, chroma_subsampling: nvidia.nvimgcodec.ChromaSubsampling | None = None, jpeg_encode_params: nvidia.nvimgcodec.JpegEncodeParams | None = None, jpeg2k_encode_params: nvidia.nvimgcodec.Jpeg2kEncodeParams | None = None, tile_width: typing.SupportsInt | None = None, tile_height: typing.SupportsInt | None = None) -> None

Constructor with parameters to control the encoding process.

Parameters:
  • quality_type (QualityType) – Quality type (algorithm) that will be used to encode image.

  • quality_value (float) – Specifies how good encoded image should look like. Refer to the QualityType enum for the allowed values for each quality type.

  • color_spec (ColorSpec) – Output color specification. Defaults to UNCHANGED.

  • chroma_subsampling (ChromaSubsampling) – Chroma subsampling format. When not specified, the default is inferred from the image and codec at encode time: for images with at least 3 channels, CSS_420 for JPEG and CSS_444 for other codecs; CSS_GRAY otherwise (images with fewer than 3 channels).

  • jpeg_encode_params (JpegEncodeParams) – Optional JPEG specific encoding parameters.

  • jpeg2k_encode_params (Jpeg2kEncodeParams) – Optional JPEG2000 specific encoding parameters.

  • tile_width (int) – Optional tile width for tiled encoding. When set to a value greater than 0, enables tiled encoding.

  • tile_height (int) – Optional tile height for tiled encoding. When set to a value greater than 0, enables tiled encoding.

property chroma_subsampling#

for images with at least 3 channels, CSS_420 for JPEG and CSS_444 for other codecs; CSS_GRAY otherwise (images with fewer than 3 channels).

Type:

Specifies the chroma subsampling format for encoding. When not specified, the default is inferred from the image and codec at encode time

property color_spec#

Defines the expected color specification for the output. Defaults to ColorSpec.UNCHANGED.

property jpeg2k_params#

Optional, additional JPEG2000-specific encoding parameters.

property jpeg_params#

Optional, additional JPEG-specific encoding parameters.

property quality_type#

Quality type (algorithm) that will be used to encode image.

property quality_value#

Specifies how good encoded image should look like. Refer to the QualityType enum for the allowed values for each quality type.

property tile_height#

Height of tiles for tiled encoding.

When set to a value greater than 0, enables tiled encoding with the specified tile height.

property tile_width#

Width of tiles for tiled encoding.

When set to a value greater than 0, enables tiled encoding with the specified tile width.

Encoder#

For the encoder options string format (global and per-encoder), the global option num_cuda_streams, and the list of encoder IDs (e.g. nvjpeg_cuda_encoder, nvjpeg2k_encoder), see Encoder options format. Built-in encoders currently only apply global options.

class nvidia.nvimgcodec.Encoder#

Encoder for image encoding operations. It allows converting images to various compressed formats or save them to files. The encoding process can be customized with different parameters and options.

__init__(
device_id: SupportsInt = -1,
max_num_cpu_threads: SupportsInt = 0,
backends: collections.abc.Sequence[nvidia.nvimgcodec.Backend] | None = None,
options: str = '',
) None#

Initialize encoder.

Parameters:
  • device_id – Device id to execute encoding on.

  • max_num_cpu_threads – Max number of CPU threads in default executor (0 means default value equal to number of cpu cores)

  • backends – List of allowed backends. If empty, all backends are allowed with default parameters.

  • options – Optional space-separated encoder options. Use :<option>=<value> for global options (e.g. :num_cuda_streams=4) or <encoder_id>:<option>=<value> for encoder-specific options. Encoder IDs include nvjpeg_cuda_encoder, nvjpeg2k_encoder, nvtiff_cuda_encoder, nvpnm_encoder, nvbmp_encoder, and OpenCV encoders (e.g. opencv_jpeg_encoder). See the documentation section “Encoder options format” for the full list and details; built-in encoders currently only honor global options.

property device_id#

The CUDA device id this encoder executes on.

encode(
image_s: object,
codec: str,
*,
code_stream_s: object | None = None,
params: nvidia.nvimgcodec.EncodeParams | None = None,
cuda_stream: SupportsInt = 0,
) object#

Encode image(s) to CodeStream(s).

Parameters:
  • image_s – Image to encode or list of images to encode (can be any Python object that can be converted to Image, or a list of such objects)

  • codec – String that defines the output format e.g.’jpeg2k’. When it is file extension it must include a leading period e.g. ‘.jp2’.

  • code_stream_s – CodeStream or list of CodeStreams to encode image to. If None, a new CodeStream(s) will be created.

  • params – Encode parameters.

  • cuda_stream – An optional cudaStream_t represented as a Python integer, upon which synchronization must take place.

Returns:

CodeStream with encoded image, or None if the input cannot be converted to Image or if encoding failed. For list of images: List of CodeStreams with encoded images. If an input cannot be converted to Image or if encoding failed, the corresponding position will contain None.

Return type:

For single image

write(
file_name: str,
image: object,
codec: str = '',
params: nvidia.nvimgcodec.EncodeParams | None = None,
cuda_stream: SupportsInt = 0,
) object#
(file_names: collections.abc.Sequence[str], images: collections.abc.Sequence[object], codec: str = '', params: nvidia.nvimgcodec.EncodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> list[object]

Overload 1: write(file_name: str, image: object, codec: str = '', params: nvidia.nvimgcodec.EncodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> object

Encode image to file.

Parameters:
  • file_name – File name to save encoded code stream.

  • image – Image to encode (can be any Python object that can be converted to Image)

  • codec – String that defines the output format e.g.’jpeg2k’. When it is file extension it must include a leading period e.g. ‘.jp2’. If codec is not specified, it is deducted based on file extension. If there is no extension by default ‘jpeg’ is choosen.

  • params – Encode parameters.

  • cuda_stream – An optional cudaStream_t represented as a Python integer, upon which synchronization must take place.

Returns:

Encoded file name, or None if the input image could not be encoded for any reason.

Overload 2: write(file_names: collections.abc.Sequence[str], images: collections.abc.Sequence[object], codec: str = '', params: nvidia.nvimgcodec.EncodeParams | None = None, cuda_stream: typing.SupportsInt = 0) -> list[object]

Encode batch of images to files.

Parameters:
  • file_names – List of file names to save encoded code streams.

  • images – List of images to encode (can contain any Python objects that can be converted to Image)

  • codec – String that defines the output format e.g.’jpeg2k’. When it is file extension it must include a leading period e.g. ‘.jp2’. If codec is not specified, it is deducted based on file extension. If there is no extension by default ‘jpeg’ is choosen. (optional)

  • params – Encode parameters.

  • cuda_stream – An optional cudaStream_t represented as a Python integer, upon which synchronization must take place.

Returns:

List of encoded file names. If an image could not be encoded for any reason, the corresponding position in the list will contain None.

ImageBufferKind#

class nvidia.nvimgcodec.ImageBufferKind#

Enum representing buffer kind in which image data is stored.

Members:

STRIDED_DEVICE :

GPU-accessible with planes in pitch-linear layout.

STRIDED_HOST :

Host-accessible with planes in pitch-linear layout.

Image#

class nvidia.nvimgcodec.Image#

A pixel buffer with associated metadata. Holds either decoded pixels or pixels that are to be encoded.

The buffer’s layout is reflected in the image’s shape and sample_format:

  • Interleaved (I_* sample formats): 3-D shape (H, W, C).

  • Planar (P_* sample formats): 3-D shape (C, H, W).

The buffer is C-style contiguous along all axes except the row stride, which may include padding.

property __cuda_array_interface__#

The CUDA array interchange interface compatible with Numba v0.39.0 or later (see CUDA Array Interface for details)

__dlpack__(
stream: object = None,
) typing_extensions.CapsuleType#

Export the image as a DLPack tensor

__dlpack_device__() tuple#

Get the device associated with the buffer

property buffer_kind#

Buffer kind in which image data is stored. This indicates whether the data is stored as strided device or host memory.

property capacity#

The capacity of the image buffer in bytes.

property color_spec#

Color specification of the image indicating how the color information in image samples should be interpreted.

cpu() object#

Returns a copy of this image in CPU memory. If this image is already in CPU memory, than no copy is performed and the original object is returned.

Returns:

Image object with content in CPU memory or None if copy could not be done.

cuda(
synchronize: bool = True,
device_id: SupportsInt = -1,
cuda_stream: SupportsInt = 0,
) object#

Returns a copy of this image in device memory. If this image is already in device memory on the same device, no copy is performed and the original object is returned. If a different device_id is specified, a new image is created on the target device with the content copied via peer-to-peer transfer.

Parameters:
  • synchronize – If True (by default) it blocks and waits for copy to be finished, else no synchronization is executed and further synchronization needs to be done using cuda stream provided by e.g. __cuda_array_interface__.

  • device_id – Target device id. If equals to -1 (by default) the current device will be used. When the image is already on a GPU and a different device_id is specified, a device-to-device copy is performed.

  • cuda_stream

    An optional cudaStream_t represented as a Python integer, upon which synchronization must take place. The data transfer is enqueued on this stream. Must belong to the same device as device_id; passing a stream created on a different device raises ValueError. Defaults to 0, the legacy default stream, which is per-device: the copy runs under an internal device guard set to device_id, so the default stream of device_id is used. Ignored when the image is already on the target device (no copy is performed).

    Lifetime: the resulting Image’s internal buffer is detached from cuda_stream before this call returns, so the Image is safe to release (let it go out of scope, del, etc.) even after the caller destroys cuda_stream. Other Image methods that enqueue asynchronous work (notably Image.cpu(), which performs a device-to-host copy on cuda_stream) must still be called while cuda_stream is alive. If synchronize=False, the caller is also responsible for synchronizing cuda_stream (or a downstream consumer of it) before reading the resulting Image’s contents.

Returns:

Image object with content in device memory or None if copy could not be done.

property cuda_stream#

The CUDA stream associated with this image as a Python integer, or None if the image is in host (CPU) memory.

property device_id#

The CUDA device id associated with this image’s buffer, or None if the image is in host (CPU) memory.

property dtype#

The data type (dtype) of the image samples.

property height#

The height of the image in pixels.

property ndim#

The number of dimensions in the image.

property num_channels#

The overall number of channels in the image across all planes.

property precision#

Number of significant bits per sample.

For lower-precision data stored in a wider container (e.g. 12-bit values held in a uint16 buffer) this is the bitdepth set explicitly by the caller (e.g. via nvimgcodec.as_image(arr, precision=12)). When no explicit precision was provided, this returns the full bitdepth of the sample data type (8 for uint8, 16 for uint16, 32 for float32, etc.).

property sample_format#

The sample format of the image indicating how color components are matched to channels and channels to planes.

property shape#

The shape of the image.

property size#

The size of the image buffer in bytes.

property strides#

Strides of axes in bytes.

to_dlpack(
cuda_stream: object = None,
) typing_extensions.CapsuleType#

Export the image with zero-copy conversion to a DLPack tensor.

Parameters:

cuda_stream – An optional cudaStream_t represented as a Python integer, upon which synchronization must take place in created Image.

Returns:

DLPack tensor which is encapsulated in a PyCapsule object.

property width#

The width of the image in pixels.

Jpeg2kBitstreamType#

class nvidia.nvimgcodec.Jpeg2kBitstreamType#

Enum to define JPEG2000 bitstream types.

This enum identifies the bitstream type for JPEG2000, which may be either a raw J2K codestream or a JP2 container format that can include additional metadata.

Members:

J2K : JPEG2000 codestream format

JP2 : JPEG2000 JP2 container format

Jpeg2kProgOrder#

class nvidia.nvimgcodec.Jpeg2kProgOrder#

Enum representing progression orders in the JPEG2000 standard.

Members:

LRCP :

Layer-Resolution-Component-Position progression order.

This progression order encodes data by layer first, then by resolution, component, and position, optimizing for scalability in quality.

RLCP :

Resolution-Layer-Component-Position progression order.

This progression order encodes data by resolution first, followed by layer, component, and position, optimizing for scalability in resolution.

RPCL :

Resolution-Position-Component-Layer progression order.

This progression order encodes data by resolution first, then by position, component, and layer, which is useful for progressive transmission by resolution.

PCRL :

Position-Component-Resolution-Layer progression order.

This progression order encodes data by position first, followed by component, resolution, and layer. It is beneficial for progressive transmission by spatial area.

CPRL :

Component-Position-Resolution-Layer progression order.

This progression order encodes data by component first, then by position, resolution, and layer, optimizing for scalability in component access.

ColorSpec#

class nvidia.nvimgcodec.ColorSpec#

Enum representing color specification for image - how the color information in samples should be interpreted.

Members:

UNKNOWN : The color specification is unknown or not specified.

UNCHANGED : The color specification should be left unchanged from the source; equivalent to UNKNOWN.

SYCC : Specifies the sYCC color space (YCbCr with sRGB primaries).

SRGB : Specifies the standard RGB (sRGB) color space.

GRAY : Specifies grayscale (single channel, no color).

CMYK : Specifies the CMYK color space (Cyan, Magenta, Yellow, Black).

YCCK : Specifies the YCCK color space (YCbCr plus Black channel).

PALETTE : Sample data is represented using a palette color map.

ICC_PROFILE : Precise color space is provided in an ICC profile.

UNSUPPORTED : The color specification is unsupported by the library.

Region#

class nvidia.nvimgcodec.Region#

Class representing a region of interest within an image.

The dimensions are oriented such that the top-left corner is (0,0).

__init__() None#
(start_y: typing.SupportsInt, start_x: typing.SupportsInt, end_y: typing.SupportsInt, end_x: typing.SupportsInt, out_of_bounds_sample: typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat = 0) -> None
(start: collections.abc.Sequence[typing.SupportsInt], end: collections.abc.Sequence[typing.SupportsInt], out_of_bounds_sample: typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat = 0) -> None
(start: tuple, end: tuple, out_of_bounds_sample: typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat = 0) -> None
(start_y: typing.SupportsInt, start_x: typing.SupportsInt, end_y: typing.SupportsInt, end_x: typing.SupportsInt, out_of_bounds_samples: collections.abc.Sequence[typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat]) -> None
(start: collections.abc.Sequence[typing.SupportsInt], end: collections.abc.Sequence[typing.SupportsInt], out_of_bounds_samples: collections.abc.Sequence[typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat]) -> None
(start: tuple, end: tuple, out_of_bounds_samples: collections.abc.Sequence[typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat]) -> None

Overload 1: __init__() -> None

Default constructor that initializes an empty Region object.

Overload 2: __init__(start_y: typing.SupportsInt, start_x: typing.SupportsInt, end_y: typing.SupportsInt, end_x: typing.SupportsInt, out_of_bounds_sample: typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat = 0) -> None

Constructor that initializes a Region with specified start and end coordinates.

Parameters:
  • start_y – Starting Y coordinate.

  • start_x – Starting X coordinate.

  • end_y – Ending Y coordinate.

  • end_x – Ending X coordinate.

  • out_of_bounds_sample – The sample that will be set for out of bounds region pixels for all components. If not specified, sample value of 0 will be used.

Overload 3: __init__(start: collections.abc.Sequence[typing.SupportsInt], end: collections.abc.Sequence[typing.SupportsInt], out_of_bounds_sample: typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat = 0) -> None

Constructor that initializes a Region with start and end coordinate lists.

Parameters:
  • start – List of starting coordinates.

  • end – List of ending coordinates.

  • out_of_bounds_sample – The sample that will be set for out of bounds region pixels for all components If not specified, sample value of 0 will be used.

Overload 4: __init__(start: tuple, end: tuple, out_of_bounds_sample: typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat = 0) -> None

Constructor that initializes a Region with start and end coordinate tuples.

Parameters:
  • start – Tuple of starting coordinates.

  • end – Tuple of ending coordinates.

  • out_of_bounds_sample – The sample that will be set for out of bounds region pixels for all components If not specified, sample value of 0 will be used.

Overload 5: __init__(start_y: typing.SupportsInt, start_x: typing.SupportsInt, end_y: typing.SupportsInt, end_x: typing.SupportsInt, out_of_bounds_samples: collections.abc.Sequence[typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat]) -> None

Constructor that initializes a Region with specified start and end coordinates.

Parameters:
  • start_y – Starting Y coordinate.

  • start_x – Starting X coordinate.

  • end_y – Ending Y coordinate.

  • end_x – Ending X coordinate.

  • out_of_bounds_samples – The list of samples that will be set for out of bounds pixel. List length must be at most 5, for the rest of the channels fill sample of 5th channel will be used. If list is shorter than 5, then fill sample for missing channels will be set to 0.

Overload 6: __init__(start: collections.abc.Sequence[typing.SupportsInt], end: collections.abc.Sequence[typing.SupportsInt], out_of_bounds_samples: collections.abc.Sequence[typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat]) -> None

Constructor that initializes a Region with start and end coordinate lists.

Parameters:
  • start – List of starting coordinates.

  • end – List of ending coordinates.

  • out_of_bounds_samples – The list of samples that will be set for out of bounds pixel. List length must be at most 5, for the rest of the channels fill sample of 5th channel will be used. If list is shorter than 5, then fill sample for missing channels will be set to 0.

Overload 7: __init__(start: tuple, end: tuple, out_of_bounds_samples: collections.abc.Sequence[typing.SupportsInt | typing.SupportsInt | typing.SupportsFloat]) -> None

Constructor that initializes a Region with start and end coordinate tuples.

Parameters:
  • start – Tuple of starting coordinates.

  • end – Tuple of ending coordinates.

  • out_of_bounds_samples – The list of samples that will be set for out of bounds pixel. List length must be at most 5, for the rest of the channels fill sample of 5th channel will be used. If list is shorter than 5, then fill sample for missing channels will be set to 0.

property end#

Property to get the end coordinates of the Region.

Returns:

A list of ending coordinates.

property ndim#

Property to get the number of dimensions in the Region.

Returns:

The number of dimensions.

property out_of_bounds_samples#

Property to get the out of bounds samples.

Returns:

A list of out of bounds samples.

property start#

Property to get the start coordinates of the Region.

Returns:

A list of starting coordinates.

SampleFormat#

class nvidia.nvimgcodec.SampleFormat#

Enum representing sample format for image. Sample format describes how color components are matched to channels in given order and channels are matched to planes.

Members:

UNKNOWN : Unknown sample format.

P_AUTO_COMPONENTS : Planar layout; let color_spec choose the components. Preferred over P_UNCHANGED when color_spec is concrete.

I_AUTO_COMPONENTS : Interleaved layout; let color_spec choose the components. Preferred over I_UNCHANGED when color_spec is concrete.

P_UNCHANGED : Unchanged planar format (alias for P_AUTO_COMPONENTS).

I_UNCHANGED : Unchanged interleaved format (alias for I_AUTO_COMPONENTS).

P_Y : Y component only (grayscale). For 3-dimensional shape is defined as (1, H, W) and this is only difference with I_Y.

I_Y : Interleaved Y component only (grayscale). For 3-dimensional shape is defined as (H, W, 1) and this is only difference with P_Y.

P_YA : Planar Y component with alpha.

I_YA : Interleaved Y component with alpha.

P_RGB : Planar RGB format.

I_RGB : Interleaved RGB format.

P_BGR : Planar BGR format.

I_BGR : Interleaved BGR format.

P_YUV : YUV planar format.

P_YCC : YCC planar format (alias for P_YUV).

I_YUV : Interleaved YUV format.

I_YCC : Interleaved YCC format (alias for I_YUV).

P_RGBA : Planar RGBA format.

I_RGBA : Interleaved RGBA format.

P_YCCK : Planar YCCK format.

I_YCCK : Interleaved YCCK format.

P_CMYK : Planar CMYK format.

I_CMYK : Interleaved CMYK format.

UNSUPPORTED : Unsupported sample format.

as_image#

nvidia.nvimgcodec.as_image(
source: object,
cuda_stream: SupportsInt = 0,
*,
sample_format: nvidia.nvimgcodec.SampleFormat | None = None,
color_spec: nvidia.nvimgcodec.ColorSpec | None = None,
precision: SupportsInt | None = None,
) nvidia.nvimgcodec.Image#

Wraps an external buffer as an Image and ties the buffer lifetime to the Image.

The buffer must be C-style contiguous, but rows may have additional padding.

Parameters:
  • source – Input DLPack tensor encapsulated in a PyCapsule, or any object exposing __cuda_array_interface__, __array_interface__ or __dlpack__/__dlpack_device__.

  • cuda_stream – Optional cudaStream_t as a Python integer, used for any synchronization the created Image needs.

  • sample_format

    (keyword-only) nvimgcodec.SampleFormat selecting the output layout:

    • I_* (concrete interleaved) -> HWC; the last axis must have at least the format’s channel arity (2-D (H, W) only for I_Y).

    • P_* (concrete planar) -> CHW; the leading axis must have at least the format’s channel arity (2-D (H, W) only for P_Y).

    • I_UNCHANGED -> HWC, no arity check.

    • P_UNCHANGED -> CHW, no arity check.

    • UNKNOWN -> raises ValueError.

    Extra channels beyond the format’s arity are kept; too few raise ValueError.

    When omitted, the value is inferred from the channel count of the array using the HWC defaults:

    • 1 channel -> I_Y

    • 2 channels -> I_YA

    • 3 channels -> I_RGB

    • 4 channels -> I_RGBA

    • 5+ channels -> UNKNOWN

  • color_spec

    (keyword-only) nvimgcodec.ColorSpec override. When omitted the value is inferred from the channel count:

    • 1 / 2 channels -> GRAY

    • 3 / 4 channels -> SRGB

    • 5+ channels -> UNKNOWN

  • precision – (keyword-only) Optional integer giving the number of significant bits per sample. Use this to describe lower-precision data stored in a wider container, e.g. a 12-bit image held in a uint16 buffer (precision=12). Accepted values are 0 (or None, both meaning “use the full bitdepth of the sample data type”) and any integer in 1..bitdepth(dtype). For floating-point dtypes only 0/None or the dtype’s full bitdepth (e.g. 32 for float32) is accepted; sub-bitdepth values are an integer-image concept and have no meaningful interpretation for floats.

Returns:

nvimgcodec.Image

as_images#

nvidia.nvimgcodec.as_images(
sources: collections.abc.Sequence[object],
cuda_stream: SupportsInt = 0,
*,
sample_format: nvidia.nvimgcodec.SampleFormat | None = None,
color_spec: nvidia.nvimgcodec.ColorSpec | None = None,
precision: SupportsInt | None = None,
) list[object]#

Wrap a list of external buffers as Images and tie each buffer’s lifetime to the corresponding Image. Equivalent to calling as_image() on each element of sources with the same sample_format, color_spec and precision overrides.

Layout rules and sample_format / color_spec / precision inference are identical to as_image(). The same overrides are applied uniformly to every input - the elements of sources may otherwise differ in shape, dtype and channel count.

Parameters:
  • sources – List of input DLPack tensors (PyCapsules) or objects exposing __cuda_array_interface__, __array_interface__ or __dlpack__/__dlpack_device__.

  • cuda_stream – Optional cudaStream_t as a Python integer, used for any synchronization the created Images need.

  • sample_format

    (keyword-only) nvimgcodec.SampleFormat override applied to every Image, selecting the output layout:

    • I_* (concrete interleaved) -> HWC; the last axis must have at least the format’s channel arity (2-D (H, W) only for I_Y).

    • P_* (concrete planar) -> CHW; the leading axis must have at least the format’s channel arity (2-D (H, W) only for P_Y).

    • I_UNCHANGED -> HWC, no arity check.

    • P_UNCHANGED -> CHW, no arity check.

    • UNKNOWN -> raises ValueError.

    Extra channels beyond the format’s arity are kept; too few raise ValueError.

    When omitted, each Image’s value is inferred from its own channel count using the HWC defaults:

    • 1 channel -> I_Y

    • 2 channels -> I_YA

    • 3 channels -> I_RGB

    • 4 channels -> I_RGBA

    • 5+ channels -> UNKNOWN

  • color_spec

    (keyword-only) nvimgcodec.ColorSpec override applied to every Image. When omitted, each Image’s value is inferred from its own channel count:

    • 1 / 2 channels -> GRAY

    • 3 / 4 channels -> SRGB

    • 5+ channels -> UNKNOWN

  • precision – (keyword-only) Optional integer giving the number of significant bits per sample, applied uniformly to every Image. Use this to describe lower-precision data stored in a wider container, e.g. a 12-bit image held in a uint16 buffer (precision=12). Accepted values are 0 (or None, both meaning “use the full bitdepth of the sample data type”) and any integer in 1..bitdepth(dtype). For floating-point dtypes only 0/None or the dtype’s full bitdepth (e.g. 32 for float32) is accepted; sub-bitdepth values are an integer-image concept and have no meaningful interpretation for floats. The value is validated against each source’s dtype.

Returns:

List of nvimgcodec.Image objects.

from_dlpack#

nvidia.nvimgcodec.from_dlpack(
source: object,
cuda_stream: SupportsInt = 0,
*,
sample_format: nvidia.nvimgcodec.SampleFormat | None = None,
color_spec: nvidia.nvimgcodec.ColorSpec | None = None,
precision: SupportsInt | None = None,
) nvidia.nvimgcodec.Image#

Zero-copy conversion from a DLPack tensor to an Image.

The DLPack source must be a 3-dimensional, CUDA-accessible tensor (device or CUDA-host memory). Layout selection and sample_format / color_spec inference are identical to as_image(); see that function for the full rules.

Parameters:
  • source – Input DLPack tensor encapsulated in a PyCapsule, or any object exposing __dlpack__ and __dlpack_device__ methods.

  • cuda_stream – Optional cudaStream_t as a Python integer, used for any synchronization the created Image needs.

  • sample_format

    (keyword-only) nvimgcodec.SampleFormat selecting the output layout:

    • I_* (concrete interleaved) -> HWC; the last axis must have at least the format’s channel arity.

    • P_* (concrete planar) -> CHW; the leading axis must have at least the format’s channel arity.

    • I_UNCHANGED -> HWC, no arity check.

    • P_UNCHANGED -> CHW, no arity check.

    • UNKNOWN -> raises ValueError.

    Extra channels beyond the format’s arity are kept; too few raise ValueError.

    When omitted, the value is inferred from the channel count of the tensor using the HWC defaults:

    • 1 channel -> I_Y

    • 2 channels -> I_YA

    • 3 channels -> I_RGB

    • 4 channels -> I_RGBA

    • 5+ channels -> UNKNOWN

  • color_spec

    (keyword-only) nvimgcodec.ColorSpec override. When omitted the value is inferred from the channel count:

    • 1 / 2 channels -> GRAY

    • 3 / 4 channels -> SRGB

    • 5+ channels -> UNKNOWN

  • precision – (keyword-only) Optional integer giving the number of significant bits per sample. Use this to describe lower-precision data stored in a wider container, e.g. a 12-bit image held in a uint16 buffer (precision=12). Accepted values are 0 (or None, both meaning “use the full bitdepth of the sample data type”) and any integer in 1..bitdepth(dtype). See as_image() for details.

Returns:

nvimgcodec.Image