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:
| Group | Methods |
|---|---|
| Construction | from_f32, from_f32_batch, from_typed, from_i8, from_pixels, from_external |
| Sub views | channel, channel_range, depth, depth_range, column_range, row_range, batch, batch_range |
| Metadata | info, is_empty |
| Typed access | to_f32, to_f32_typed, to_i8, copy_to_f32, to_f32_into, as_f32_slice, channel_f32 |
| Layout | flatten, with_packing, deep_clone, reshape, into_reshape, reshape_view |
| Values in place | fill, normalized, normalize_in_place, into_normalized |
| Pixels | to_pixels, to_pixels_resize |
| Borders | copy_make_border, copy_cut_border, copy_make_border_3d, copy_cut_border_3d |
| Raw escape | as_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
impl Mat
Sourcepub fn from_f32(data: &[f32], dimensions: &[usize]) -> Result<Self>
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]);Sourcepub fn from_f32_batch(
data: &[f32],
dimensions: &[usize],
batch: usize,
) -> Result<Self>
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.
Sourcepub fn from_typed(
kind: ElementKind,
data: &[u8],
dimensions: &[usize],
) -> Result<Self>
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.
Sourcepub fn from_i8(data: &[i8], dimensions: &[usize]) -> Result<Self>
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.
Sourcepub fn from_pixels(
data: &[u8],
format: PixelFormat,
width: usize,
height: usize,
) -> Result<Self>
pub fn from_pixels( data: &[u8], format: PixelFormat, width: usize, height: usize, ) -> Result<Self>
Copies interleaved pixels into a new tensor.
Sourcepub unsafe fn from_external(data: &[f32], dimensions: &[usize]) -> Result<Self>
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.
Sourcepub fn channel(&self, channel: usize) -> Result<MatView<'_>>
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.
Sourcepub fn channel_range(
&self,
channel: usize,
channels: usize,
) -> Result<MatView<'_>>
pub fn channel_range( &self, channel: usize, channels: usize, ) -> Result<MatView<'_>>
Borrows a run of channels as a read-only alias.
Sourcepub fn depth(&self, depth: usize) -> Result<MatView<'_>>
pub fn depth(&self, depth: usize) -> Result<MatView<'_>>
Borrows one depth slice as a read-only alias.
Sourcepub fn depth_range(&self, depth: usize, depths: usize) -> Result<MatView<'_>>
pub fn depth_range(&self, depth: usize, depths: usize) -> Result<MatView<'_>>
Borrows a run of depth slices as a read-only alias.
Sourcepub fn column_range(&self, x: usize, width: usize) -> Result<MatView<'_>>
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.
Sourcepub fn row_range(&self, y: usize, rows: usize) -> Result<MatView<'_>>
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.
Sourcepub fn batch(&self, batch: usize) -> Result<MatView<'_>>
pub fn batch(&self, batch: usize) -> Result<MatView<'_>>
Borrows one batch item as a read-only alias.
Sourcepub fn batch_range(&self, batch: usize, batches: usize) -> Result<MatView<'_>>
pub fn batch_range(&self, batch: usize, batches: usize) -> Result<MatView<'_>>
Borrows batches batch items starting at batch as a read-only alias.
Sourcepub fn info(&self) -> TensorInfo
pub fn info(&self) -> TensorInfo
Returns the native shape and stride metadata.
Sourcepub fn is_empty(&self) -> bool
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.
Sourcepub fn to_f32(&self) -> Result<Vec<f32>>
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.
Sourcepub fn to_f32_typed(&self, kind: ElementKind) -> Result<Vec<f32>>
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.
Sourcepub fn to_i8(&self) -> Result<Vec<i8>>
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.
Sourcepub fn copy_to_f32(&self, out: &mut [f32]) -> Result<()>
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.
Sourcepub fn to_f32_into(&self, out: &mut Vec<f32>) -> Result<()>
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.
Sourcepub fn as_f32_slice(&self) -> Result<&[f32]>
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]);Sourcepub fn channel_f32(&self, channel: usize) -> Result<&[f32]>
pub fn channel_f32(&self, channel: usize) -> Result<&[f32]>
Borrows one logical channel, excluding native alignment padding.
Sourcepub fn flatten(&self) -> Result<Self>
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.
Sourcepub fn with_packing(&self, elempack: i32) -> Result<Self>
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.
Sourcepub fn deep_clone(&self) -> Result<Self>
pub fn deep_clone(&self) -> Result<Self>
Copies the tensor into independent native storage.
Sourcepub fn reshape(&self, dimensions: &[usize]) -> Result<Self>
pub fn reshape(&self, dimensions: &[usize]) -> Result<Self>
Returns independent storage, detaching only when native reshape aliases.
Sourcepub fn into_reshape(self, dimensions: &[usize]) -> Result<Self>
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.
Sourcepub fn reshape_view(&self, dimensions: &[usize]) -> Result<ReshapeView<'_>>
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.
Sourcepub fn fill(&mut self, value: f32) -> Result<()>
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.
Sourcepub fn normalized(&self, mean: &[f32], norm: &[f32]) -> Result<Self>
pub fn normalized(&self, mean: &[f32], norm: &[f32]) -> Result<Self>
Returns a copy with mean subtraction and scaling applied per channel.
Sourcepub fn normalize_in_place(&mut self, mean: &[f32], norm: &[f32]) -> Result<()>
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.
Sourcepub fn into_normalized(self, mean: &[f32], norm: &[f32]) -> Result<Self>
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.
Sourcepub fn to_pixels(
&self,
format: PixelFormat,
stride: usize,
out: &mut [u8],
) -> Result<()>
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.
Sourcepub fn to_pixels_resize(
&self,
format: PixelFormat,
target: (usize, usize),
stride: usize,
out: &mut [u8],
) -> Result<()>
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.
Sourcepub fn copy_make_border(
&self,
top: usize,
bottom: usize,
left: usize,
right: usize,
mode: BorderMode,
value: f32,
) -> Result<Self>
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.
Sourcepub fn copy_cut_border(
&self,
top: usize,
bottom: usize,
left: usize,
right: usize,
) -> Result<Self>
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.
Sourcepub fn copy_make_border_3d(
&self,
borders: Borders,
mode: BorderMode,
value: f32,
) -> Result<Self>
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.
Sourcepub fn copy_cut_border_3d(&self, borders: Borders) -> Result<Self>
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.
Sourcepub fn as_raw(&self) -> ncnn_mat_t
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.
Sourcepub fn into_raw(self) -> ncnn_mat_t
pub fn into_raw(self) -> ncnn_mat_t
Releases the Rust handle and transfers release responsibility to the caller.
Sourcepub unsafe fn from_raw_owned(raw: ncnn_mat_t, f32_known: bool) -> Result<Self>
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.