pub fn image_dims_from_shape(
format: PixelFormat,
shape: &[usize],
) -> Result<(usize, usize)>Expand description
The logical (width, height) an allocation shape describes for
format – the inverse of PixelFormat::allocation_shape.
Used wherever a tensor arrives carrying a shape and a format but not its dimensions: the C constructors, the Python bindings and the cross-package protocol import.
§The input is the allocation shape, not the addressing shape
PixelFormat::allocation_shape is what Tensor::image allocates from
and what descriptor_pinned emits from shape(), so that is what this
inverts. PixelFormat::addressing_shape is a different, smaller grid,
and for a semi-planar format the two collide: NV12’s addressing shape is
[h, w] and its allocation shape is [combined_h, w], both rank 2. Handed
an addressing shape this cannot tell – NV12 [480, 640] reads as a
combined height of 480 and answers (640, 320), silently. Nothing in the
shape distinguishes them, so callers must pass the allocation shape.
A D3D11 import is the one place this cannot bite: the constructors check
the derived size against the texture description, so a mismatch fails with
Error::InvalidArgument naming both. On Windows, prefer
d3d11_texture_geometry and d3d11_shared_handle_geometry, which read the
dimensions off the texture itself and leave the shape as a consistency
check – except for a semi-planar texture, whose width is its row stride
rather than the image width, so those helpers take the width from the shape
they are given and refuse to answer without one.
The rank is part of the format’s contract, so a shape of the wrong rank is an error rather than an interpretation of whatever dimensions are present:
| Layout | Shape | Result |
|---|---|---|
| Packed | [h, w, c] | (shape[1], shape[0]) |
| Planar | [c, h, w] | (shape[2], shape[1]) |
| SemiPlanar | [combined_h, w] | (shape[1], image height) |
A semi-planar shape carries the combined plane height, so the logical
height is recovered through
PixelFormat::image_height_from_combined, which rejects a combined
height no image height produces (721 for NV12, say) instead of rounding to
a nearby one.
§Errors
Error::InvalidShape for a shape of the wrong rank, or a semi-planar
combined height with no image height behind it.
§Example
use edgefirst_tensor::{image_dims_from_shape, PixelFormat};
assert_eq!(image_dims_from_shape(PixelFormat::Rgba, &[480, 640, 4]).unwrap(), (640, 480));
assert_eq!(image_dims_from_shape(PixelFormat::PlanarRgb, &[3, 480, 640]).unwrap(), (640, 480));
assert_eq!(image_dims_from_shape(PixelFormat::Nv12, &[722, 640]).unwrap(), (640, 481));
assert!(image_dims_from_shape(PixelFormat::Nv12, &[721, 640]).is_err());