Table of Contents

Class SAM2<T>

Namespace
AiDotNet.Video.Segmentation
Assembly
AiDotNet.dll

Segment Anything Model 2 (SAM2) for video object segmentation.

public class SAM2<T> : NeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable

Type Parameters

T

The numeric type used for calculations (e.g., float, double).

Inheritance
SAM2<T>
Implements
IFullModel<T, Tensor<T>, Tensor<T>>
IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>
IParameterizable<T, Tensor<T>, Tensor<T>>
ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>
IGradientComputable<T, Tensor<T>, Tensor<T>>
Inherited Members
Extension Methods

Remarks

For Beginners: SAM2 is a powerful model that can segment any object in video. You can interact with it by: - Clicking on an object in the first frame to select it - Drawing a bounding box around objects - Providing text prompts describing what to segment

Once you identify an object, SAM2 automatically tracks and segments it across all frames in the video, even when the object moves, rotates, or is partially occluded.

Common use cases:

  • Video editing (isolating subjects for effects)
  • Object tracking and analysis
  • Video annotation and labeling
  • Interactive video manipulation

Technical Details: - Memory attention mechanism for temporal consistency - Hierarchical image encoder (similar to MAE/ViT) - Prompt encoder for points, boxes, and masks - Mask decoder with occlusion prediction - Memory bank for efficient object tracking

Reference: Ravi et al., "SAM 2: Segment Anything in Images and Videos" Meta AI, 2024.

Constructors

SAM2(NeuralNetworkArchitecture<T>, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?, SAM2ModelSize, int)

Initializes a new instance of the SAM2 class in native (trainable) mode.

public SAM2(NeuralNetworkArchitecture<T> architecture, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null, SAM2ModelSize modelSize = SAM2ModelSize.Base, int memoryBankSize = 7)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture configuration.

optimizer IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>

Optional optimizer for training (default: null uses layer-wise learning).

lossFunction ILossFunction<T>

Optional loss function (default: BinaryCrossEntropyLoss).

modelSize SAM2ModelSize

The model size variant (Tiny, Small, Base, Large).

memoryBankSize int

Maximum number of frames to keep in memory.

Remarks

For Beginners: This constructor creates a trainable SAM2 model. Use this when you want to fine-tune the model on your own video data.

SAM2(NeuralNetworkArchitecture<T>, string, SAM2ModelSize, int)

Initializes a new instance of the SAM2 class in ONNX (inference-only) mode.

public SAM2(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, SAM2ModelSize modelSize = SAM2ModelSize.Base, int memoryBankSize = 7)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture configuration.

onnxModelPath string

Path to the ONNX model file.

modelSize SAM2ModelSize

The model size variant for configuration.

memoryBankSize int

Maximum number of frames to keep in memory.

Remarks

For Beginners: This constructor loads a pre-trained SAM2 model from ONNX format. Use this for fast inference when you don't need to train the model. Download pre-trained models from Meta's SAM2 repository.

Exceptions

FileNotFoundException

Thrown if the ONNX model file is not found.

InvalidOperationException

Thrown if the ONNX model fails to load.

Properties

SupportsTraining

Gets whether training is supported.

public override bool SupportsTraining { get; }

Property Value

bool

Methods

ClearMemory()

Clears the memory bank for starting a new video.

public void ClearMemory()

CreateNewInstance()

Creates a new instance of the same type as this neural network.

protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()

Returns

IFullModel<T, Tensor<T>, Tensor<T>>

A new instance of the same neural network type.

Remarks

For Beginners: This creates a blank version of the same type of neural network.

It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.

DeserializeNetworkSpecificData(BinaryReader)

Deserializes network-specific data that was not covered by the general deserialization process.

protected override void DeserializeNetworkSpecificData(BinaryReader reader)

Parameters

reader BinaryReader

The BinaryReader to read the data from.

Remarks

This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.

For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.

GetModelMetadata()

Gets the metadata for this neural network model.

public override ModelMetadata<T> GetModelMetadata()

Returns

ModelMetadata<T>

A ModelMetaData object containing information about the model.

GetOcclusionScore(Tensor<T>, float[,], int[])

Gets the occlusion score for the current segmentation.

public double GetOcclusionScore(Tensor<T> image, float[,] points, int[] pointLabels)

Parameters

image Tensor<T>

The input image tensor.

points float[,]

Point prompts.

pointLabels int[]

Point labels.

Returns

double

Occlusion score in [0, 1] where 1 means fully occluded.

InitializeLayers()

Initializes the layers of the neural network based on the architecture.

protected override void InitializeLayers()

Remarks

For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.

InteractiveVideoSegmentation(List<Tensor<T>>, Dictionary<int, (float[,] Points, int[] Labels)>)

Performs interactive video segmentation with refinement.

public List<Tensor<T>> InteractiveVideoSegmentation(List<Tensor<T>> frames, Dictionary<int, (float[,] Points, int[] Labels)> framePrompts)

Parameters

frames List<Tensor<T>>

List of video frames.

framePrompts Dictionary<int, (float[,] Points, int[] Labels)>

Dictionary of frame index to prompts for refinement.

Returns

List<Tensor<T>>

List of refined segmentation masks.

Predict(Tensor<T>)

Makes a prediction using the neural network.

public override Tensor<T> Predict(Tensor<T> input)

Parameters

input Tensor<T>

The input data to process.

Returns

Tensor<T>

The network's prediction.

Remarks

For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).

SegmentWithBox(Tensor<T>, float[])

Segments objects in an image given a bounding box.

public Tensor<T> SegmentWithBox(Tensor<T> image, float[] box)

Parameters

image Tensor<T>

The input image tensor.

box float[]

Bounding box [x1, y1, x2, y2] in pixel coordinates.

Returns

Tensor<T>

Segmentation mask tensor.

SegmentWithMask(Tensor<T>, Tensor<T>)

Segments objects using a mask prompt (for refinement).

public Tensor<T> SegmentWithMask(Tensor<T> image, Tensor<T> maskPrompt)

Parameters

image Tensor<T>

The input image tensor.

maskPrompt Tensor<T>

Low-resolution mask prompt [H/4, W/4].

Returns

Tensor<T>

Refined segmentation mask tensor.

SegmentWithPoints(Tensor<T>, float[,], int[])

Segments objects in an image given point prompts.

public Tensor<T> SegmentWithPoints(Tensor<T> image, float[,] points, int[] pointLabels)

Parameters

image Tensor<T>

The input image tensor [C, H, W] or [B, C, H, W].

points float[,]

Point coordinates [[x, y], ...] for foreground/background.

pointLabels int[]

Label for each point: 1 for foreground, 0 for background.

Returns

Tensor<T>

Segmentation mask tensor [H, W] or [B, H, W] with values in [0, 1].

SerializeNetworkSpecificData(BinaryWriter)

Serializes network-specific data that is not covered by the general serialization process.

protected override void SerializeNetworkSpecificData(BinaryWriter writer)

Parameters

writer BinaryWriter

The BinaryWriter to write the data to.

Remarks

This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.

For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.

TrackObject(List<Tensor<T>>, float[,], int[])

Tracks and segments an object across video frames.

public List<Tensor<T>> TrackObject(List<Tensor<T>> frames, float[,] initialPoints, int[] pointLabels)

Parameters

frames List<Tensor<T>>

List of video frames.

initialPoints float[,]

Point prompts for the first frame.

pointLabels int[]

Labels for initial points.

Returns

List<Tensor<T>>

List of segmentation masks for each frame.

Remarks

For Beginners: This is the main video tracking method. Simply provide the initial frame with point clicks to identify objects, and SAM2 will automatically track and segment those objects in all subsequent frames.

Train(Tensor<T>, Tensor<T>)

Trains the neural network on a single input-output pair.

public override void Train(Tensor<T> input, Tensor<T> expectedOutput)

Parameters

input Tensor<T>

The input data.

expectedOutput Tensor<T>

The expected output for the given input.

Remarks

This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.

For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)

The network then:

  1. Makes a prediction based on the input
  2. Compares its prediction to the expected output
  3. Calculates how wrong it was (the loss)
  4. Adjusts its internal values to do better next time

After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.

UpdateParameters(Vector<T>)

Updates the network's parameters with new values.

public override void UpdateParameters(Vector<T> parameters)

Parameters

parameters Vector<T>

The new parameter values to set.

Remarks

For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.

This is typically used by optimization algorithms that calculate better parameter values based on training data.