Skip to main content

Mat

Struct Mat 

Source
pub struct Mat { /* private fields */ }
Expand description

An owned tensor handle released through the native allocator.

§Surface

The methods group by capability, and each group answers one question. The source order matches the table, so the rendered method list reads in the same groups:

GroupMethods
Constructionfrom_f32, from_f32_batch, from_typed, from_i8, from_pixels, from_external
Sub viewschannel, channel_range, depth, depth_range, column_range, row_range, batch, batch_range
Metadatainfo, is_empty
Typed accessto_f32, to_f32_typed, to_i8, copy_to_f32, to_f32_into, as_f32_slice, channel_f32
Layoutflatten, with_packing, deep_clone, reshape, into_reshape, reshape_view
Values in placefill, normalized, normalize_in_place, into_normalized
Pixelsto_pixels, to_pixels_resize
Borderscopy_make_border, copy_cut_border, copy_make_border_3d, copy_cut_border_3d
Raw escapeas_raw, into_raw, from_raw_owned

The extents themselves come from TensorInfo, which info returns: shape and total describe an existing tensor rather than build one.

The consuming forms (into_reshape, into_normalized) exist because they keep storage the caller already owns; the borrowing forms do the same work behind a copy.

§Thread affinity

A tensor belongs to the thread that created it: the handle is not Send or Sync because native allocation, packing and the allocator a tensor came from are thread-affine. Move the input bytes instead and build a tensor on the thread that runs inference.

Implementations§

Source§

impl Mat

Source

pub fn from_f32(data: &[f32], dimensions: &[usize]) -> Result<Self>

Copies FP32 values into a new tensor of the given rank and extents.

let tensor = ncnn_rust::Mat::from_f32(&[1.0, 2.0, 3.0, 4.0], &[2, 2])?;
assert_eq!(tensor.info().w, 2);
assert_eq!(tensor.to_f32()?, [1.0, 2.0, 3.0, 4.0]);
Source

pub fn from_f32_batch( data: &[f32], dimensions: &[usize], batch: usize, ) -> Result<Self>

Copies batched FP32 values into a new tensor.

data holds batch tensors one after another, each in channel-plane order. Layers that do not declare support_batch still run, because ncnn splits the batch and joins the result. TensorInfo::n reports the batch count, and to_f32 reads the batches back in the same order. The arithmetic helpers, normalization and reshape, stay single batch.

Source

pub fn from_typed( kind: ElementKind, data: &[u8], dimensions: &[usize], ) -> Result<Self>

Copies typed bytes into a new tensor of the given rank and extents.

data holds elements of kind.element_bytes() bytes in channel-plane order, the layout the native layers read and the typed readers expect. This is how a quantized or half-precision tensor enters a network.

Source

pub fn from_i8(data: &[i8], dimensions: &[usize]) -> Result<Self>

Copies signed 8-bit values into a new quantized tensor.

This is the signature Quantize produces; Mat::from_typed covers the unsigned format and every other element width.

Source

pub fn from_pixels( data: &[u8], format: PixelFormat, width: usize, height: usize, ) -> Result<Self>

Copies interleaved pixels into a new tensor.

Source

pub unsafe fn from_external(data: &[f32], dimensions: &[usize]) -> Result<Self>

Builds a tensor that borrows caller storage instead of copying it.

The native tensor keeps the pointer, so this is the zero-copy input path: a caller that already holds frame data avoids one copy per request. Reads through the returned tensor behave like any other tensor, and the tensor never frees the buffer.

§Safety

data must stay alive, keep its length and stay free of mutable aliases until this tensor and every native object that received it are dropped. An extractor that submitted it holds the pointer until it is dropped, so the borrow has to cover the extraction. Use Input::borrowed when the borrow only has to cover one request.

Source

pub fn channel(&self, channel: usize) -> Result<MatView<'_>>

Borrows one channel as a read-only alias.

The alias shares this tensor’s storage. It rejects a channel outside 0..c, and the source stays borrowed for as long as the view lives.

Source

pub fn channel_range( &self, channel: usize, channels: usize, ) -> Result<MatView<'_>>

Borrows a run of channels as a read-only alias.

Source

pub fn depth(&self, depth: usize) -> Result<MatView<'_>>

Borrows one depth slice as a read-only alias.

Source

pub fn depth_range(&self, depth: usize, depths: usize) -> Result<MatView<'_>>

Borrows a run of depth slices as a read-only alias.

Source

pub fn column_range(&self, x: usize, width: usize) -> Result<MatView<'_>>

Borrows width columns starting at x as a one-dimensional alias of the first row.

Source

pub fn row_range(&self, y: usize, rows: usize) -> Result<MatView<'_>>

Borrows rows rows starting at y as a read-only alias of the first channel plane.

Source

pub fn batch(&self, batch: usize) -> Result<MatView<'_>>

Borrows one batch item as a read-only alias.

Source

pub fn batch_range(&self, batch: usize, batches: usize) -> Result<MatView<'_>>

Borrows batches batch items starting at batch as a read-only alias.

Source

pub fn info(&self) -> TensorInfo

Returns the native shape and stride metadata.

Source

pub fn is_empty(&self) -> bool

Reports whether the tensor holds no elements.

A tensor is empty when native storage has not been created or a shape dimension leaves it without storage slots, which is what a failed allocation also reports.

Source

pub fn to_f32(&self) -> Result<Vec<f32>>

Copies 32-bit unpacked storage as FP32 values. The caller selects the interpretation for tensors whose scalar format is supplied by the model.

Source

pub fn to_f32_typed(&self, kind: ElementKind) -> Result<Vec<f32>>

Copies any scalar format into FP32 values.

Native tensors carry an element width but no format tag, so a 16-bit tensor needs the caller to say whether it stores IEEE half or bfloat16. Quantized outputs of Quantize and Requantize are signed 8-bit.

Source

pub fn to_i8(&self) -> Result<Vec<i8>>

Copies signed 8-bit quantized values without going through FP32 storage.

The tensor records one byte per element but not whether the byte is signed, so this reads the storage as I8: a stored 200 returns -56. Read unsigned one-byte storage with to_f32_typed(ElementKind::U8) instead.

Source

pub fn copy_to_f32(&self, out: &mut [f32]) -> Result<()>

Copies logical FP32 elements into an exact-sized initialized slice. Channel padding is omitted. A size/layout error leaves the slice unchanged.

Source

pub fn to_f32_into(&self, out: &mut Vec<f32>) -> Result<()>

Appends the logical FP32 values to a vector that keeps its capacity.

Existing values stay in place, so several tensors concatenate in call order. A layout error or a failed native copy leaves the vector exactly as it was, and the capacity survives, which is what makes a steady-state loop allocation-free. A caller that wants this tensor alone clears the vector first.

Source

pub fn as_f32_slice(&self) -> Result<&[f32]>

Borrows contiguous, unpacked 32-bit storage with an FP32 interpretation.

The borrow needs single-batch storage whose channels are adjacent, which is the layout a single-channel tensor or a network output without channel padding has. A packed, 16-bit or batched tensor returns Error::Invalid, and a multi-channel tensor with padded planes uses channel_f32 or to_f32.

ⓘ
let mat = ncnn_rust::Mat::from_f32(&[1.], &[1]).unwrap();
let values = mat.as_f32_slice().unwrap();
drop(mat);
println!("{}", values[0]);
Source

pub fn channel_f32(&self, channel: usize) -> Result<&[f32]>

Borrows one logical channel, excluding native alignment padding.

Source

pub fn flatten(&self) -> Result<Self>

Collapses the tensor into one unpacked dimension.

This is the shape a fully connected layer expects, and it runs on the native kernel. Packed or padded storage is expanded first, so the result is unpacked FP32.

Source

pub fn with_packing(&self, elempack: i32) -> Result<Self>

Returns a copy in another element packing.

Packing groups consecutive elements of the packing axis into one lane, which is the layout the packed SIMD kernels read. The request must divide the element count of that axis; a pack of one returns unpacked storage. The values keep their relative order inside a lane, so a packed tensor reads back in lane order rather than plane order; unpack it before comparing against plane-ordered values.

Source

pub fn deep_clone(&self) -> Result<Self>

Copies the tensor into independent native storage.

Source

pub fn reshape(&self, dimensions: &[usize]) -> Result<Self>

Returns independent storage, detaching only when native reshape aliases.

Source

pub fn into_reshape(self, dimensions: &[usize]) -> Result<Self>

Reshapes in place, keeping the storage this tensor already owns.

The native reshape only rewrites the header, so consuming the tensor is what makes the alias safe: no other reference to this storage exists afterwards. This is the form to use on the way into a network, and it costs no copy where reshape has to duplicate aliased storage.

Source

pub fn reshape_view(&self, dimensions: &[usize]) -> Result<ReshapeView<'_>>

Returns an explicitly read-only reshape that borrows this tensor. Native padding changes may allocate. No raw handle or mutable Mat escapes; the source borrow retains external allocator and adopted dependencies.

Source

pub fn fill(&mut self, value: f32) -> Result<()>

Fills owned unpacked FP32 storage with one value.

This is the allocation-free way to clear a reusable input buffer. The storage rules match normalize_in_place.

Source

pub fn normalized(&self, mean: &[f32], norm: &[f32]) -> Result<Self>

Returns a copy with mean subtraction and scaling applied per channel.

Source

pub fn normalize_in_place(&mut self, mean: &[f32], norm: &[f32]) -> Result<()>

Applies mean subtraction and scaling in place, without a second allocation.

The tensor must own its storage: a tensor adopted from a raw handle, or built over an external buffer, returns Error::Invalid because the write would reach memory the caller still manages. Lengths follow normalized.

Source

pub fn into_normalized(self, mean: &[f32], norm: &[f32]) -> Result<Self>

Applies mean subtraction and scaling while consuming the tensor.

Storage this crate owns is rewritten in place, so the call allocates nothing; any other provenance copies first, which is what normalized always does. Use this form when the tensor is the caller’s last reference and the request only needs the normalized values.

Source

pub fn to_pixels( &self, format: PixelFormat, stride: usize, out: &mut [u8], ) -> Result<()>

Converts unpacked FP32 planes into interleaved pixels.

stride is the destination distance between rows in bytes and must cover width * format.channels(). out must hold stride * height bytes; the remaining bytes of a wider stride stay untouched.

Source

pub fn to_pixels_resize( &self, format: PixelFormat, target: (usize, usize), stride: usize, out: &mut [u8], ) -> Result<()>

Converts unpacked FP32 planes into interleaved pixels of another size.

The resize uses the native bilinear path. Buffer requirements match to_pixels with the target width and height.

Source

pub fn copy_make_border( &self, top: usize, bottom: usize, left: usize, right: usize, mode: BorderMode, value: f32, ) -> Result<Self>

Adds a border around every plane with the native padding kernel.

This is the letterbox step: the native kernel writes the border instead of a Rust-side loop. The tensor must be a 2-D or 3-D unpacked single-batch tensor, and the result keeps the element width and the rank of self.

Source

pub fn copy_cut_border( &self, top: usize, bottom: usize, left: usize, right: usize, ) -> Result<Self>

Removes rows and columns from every plane.

The crop runs on the native kernel and keeps the remaining storage layout, which is the detection-side counterpart of copy_make_border. Requirements match that method, and the crop keeps at least one row and one column.

Source

pub fn copy_make_border_3d( &self, borders: Borders, mode: BorderMode, value: f32, ) -> Result<Self>

Adds a border around a 4-D tensor, including the depth sides.

The native 3-D padding kernel pads width, height and depth, which is what a 3-D convolution graph needs. Requirements match copy_make_border, and the tensor must carry all four axes.

Source

pub fn copy_cut_border_3d(&self, borders: Borders) -> Result<Self>

Removes rows, columns and depth slices from a 4-D tensor.

This is the depth counterpart of copy_cut_border and keeps at least one element on every axis.

Source

pub fn as_raw(&self) -> ncnn_mat_t

Borrows the native handle without transferring ownership.

Unsafe native writers must preserve Rust tensor borrows, including output guard borrows if this storage is later transferred with input_owned. Returns the native handle. The caller keeps it alive exactly as long as this Mat.

Source

pub fn into_raw(self) -> ncnn_mat_t

Releases the Rust handle and transfers release responsibility to the caller.

Source

pub unsafe fn from_raw_owned(raw: ncnn_mat_t, f32_known: bool) -> Result<Self>

Takes ownership of a native tensor with independent storage dependencies.

§Safety

The handle must be uniquely owned, valid and backed by initialized logical elements. Its allocator must outlive this object. Native writers respect Rust tensor-view borrows. f32_known asserts FP32 semantics. Consuming input methods copy adopted storage so borrowed native dependencies keep their original lifetime.

Trait Implementations§

Source§

impl Drop for Mat

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl From<Mat> for Input<'_>

Source§

fn from(mat: Mat) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !Send for Mat

§

impl !Sync for Mat

§

impl Freeze for Mat

§

impl RefUnwindSafe for Mat

§

impl Unpin for Mat

§

impl UnsafeUnpin for Mat

§

impl UnwindSafe for Mat

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.