Class Net
- Namespace
- OpenCvSharp.Dnn
- Assembly
- OpenCvSharp.dll
Base class for objects that own a single native OpenCV pointer through an OpenCvSafeHandle. The SafeHandle is the single source of truth for the native handle value and is responsible for releasing it (including from its own finalizer when the managed object is dropped without Dispose()).
[SuppressMessage("Microsoft.Design", "CA1724: Type names should not match namespaces")]
public class Net : CvObject, IDisposable
- Inheritance
-
Net
- Implements
- Inherited Members
Remarks
Neural network is presented as directed acyclic graph(DAG), where vertices are Layer instances, and edges specify relationships between layers inputs and outputs.
Each network layer has unique integer id and unique string name inside its network. LayerId can store either layer name or layer id. This class supports reference counting of its instances, i.e.copies point to the same instance.
Constructors
Net()
Default constructor
public Net()
Net(nint)
Constructor (backward compatibility). Wraps the pointer in a non-owning SafeHandle. Derived classes that own the native resource should call SetSafeHandle(OpenCvSafeHandle) to replace it with an owning handle.
protected Net(nint ptr)
Parameters
ptrnint
Properties
ProfilingMode
Gets or sets the profiling mode of the new DNN engine (OpenCV 5).
public ProfilingMode ProfilingMode { get; set; }
Property Value
TracingMode
Gets or sets the tracing mode of the new DNN engine (OpenCV 5).
public TracingMode TracingMode { get; set; }
Property Value
Methods
Connect(int, int, int, int)
Connects #@p outNum output of the first layer to #@p inNum input of the second layer.
public void Connect(int outLayerId, int outNum, int inpLayerId, int inpNum)
Parameters
outLayerIdintidentifier of the first layer
outNumintidentifier of the second layer
inpLayerIdintnumber of the first layer output
inpNumintnumber of the second layer input
Connect(string, string)
Connects output of the first layer to input of the second layer.
public void Connect(string outPin, string inpPin)
Parameters
outPinstringdescriptor of the first layer output.
inpPinstringdescriptor of the second layer input.
DisableKVCache()
Disables the Key-Value (KV) cache.
public void DisableKVCache()
Dump()
Dump net to String. Call method after setInput(). To see correct backend, target and fusion run after forward().
public string Dump()
Returns
- string
String with structure, hyperparameters, backend, target and fusion
DumpToFile(string)
Dump net structure, hyperparameters, backend, target and fusion to dot file
public void DumpToFile(string path)
Parameters
pathstringpath to output file with .dot extension
DumpToPbtxt(string)
Dump net structure, hyperparameters, backend, target and fusion to a pbtxt file.
public void DumpToPbtxt(string path)
Parameters
pathstringpath to output file with .pbtxt extension.
Remarks
Requires the network's output blobs to be allocated (e.g. after the input shape is known and the net has been set up); otherwise OpenCV raises an exception.
Empty()
Returns true if there are no layers in the network.
public bool Empty()
Returns
EnableFusion(bool)
Enables or disables layer fusion in the network.
public void EnableFusion(bool fusion)
Parameters
fusionbooltrue to enable the fusion, false to disable. The fusion is enabled by default.
EnableKVCache()
Enables the Key-Value (KV) cache, used to accelerate inference of transformer / LLM models.
public void EnableKVCache()
EnableWinograd(bool)
Enables or disables the Winograd convolution optimization.
public void EnableWinograd(bool useWinograd)
Parameters
useWinogradbooltrue to enable, false to disable.
FinalizeNet()
Finalizes the network (new DNN engine, OpenCV 5). The first forward() does this automatically; calling it early pays the one-time setup cost at a predictable point and surfaces configuration errors before inference.
public void FinalizeNet()
Forward(IEnumerable<Mat>, IEnumerable<string>)
Runs forward pass to compute outputs of layers listed in @p outBlobNames.
public void Forward(IEnumerable<Mat> outputBlobs, IEnumerable<string> outBlobNames)
Parameters
outputBlobsIEnumerable<Mat>contains blobs for first outputs of specified layers.
outBlobNamesIEnumerable<string>names for layers which outputs are needed to get
Forward(IEnumerable<Mat>, string?)
Runs forward pass to compute output of layer with name @p outputName.
public void Forward(IEnumerable<Mat> outputBlobs, string? outputName = null)
Parameters
outputBlobsIEnumerable<Mat>contains all output blobs for specified layer.
outputNamestringname for layer which output is needed to get. If outputName is empty, runs forward pass for the whole network.
Forward(string?)
Runs forward pass to compute output of layer with name @p outputName. By default runs forward pass for the whole network.
public Mat Forward(string? outputName = null)
Parameters
outputNamestringname for layer which output is needed to get
Returns
- Mat
blob for first output of specified layer.
ForwardAndRetrieve(IEnumerable<string>)
Runs forward pass to compute outputs of layers listed in @p outBlobNames, retrieving all output blobs for each layer specified in @p outBlobNames.
public Mat[][] ForwardAndRetrieve(IEnumerable<string> outBlobNames)
Parameters
outBlobNamesIEnumerable<string>names for layers which outputs are needed to get
Returns
- Mat[][]
for each requested layer, an array containing all of that layer's output blobs.
GetFLOPS(MatShape, MatType)
Computes FLOP for whole loaded model with the specified single input shape and type (OpenCV 5).
public long GetFLOPS(MatShape netInputShape, MatType netInputType)
Parameters
netInputShapeMatShapeshape for the net input.
netInputTypeMatTypeelement type for the net input.
Returns
- long
computed FLOP.
GetFLOPS(IEnumerable<MatShape>, IEnumerable<MatType>)
Computes FLOP for whole loaded model with specified input shapes (OpenCV 5).
public long GetFLOPS(IEnumerable<MatShape> netInputShapes, IEnumerable<MatType> netInputTypes)
Parameters
netInputShapesIEnumerable<MatShape>shapes for all net inputs.
netInputTypesIEnumerable<MatType>element types for all net inputs (parallel to
netInputShapes).
Returns
- long
computed FLOP.
GetFLOPS(int, IEnumerable<MatShape>, IEnumerable<MatType>)
Computes FLOP for a specific layer with specified input shapes (OpenCV 5).
public long GetFLOPS(int layerId, IEnumerable<MatShape> netInputShapes, IEnumerable<MatType> netInputTypes)
Parameters
layerIdintid of the layer.
netInputShapesIEnumerable<MatShape>shapes for all net inputs.
netInputTypesIEnumerable<MatType>element types for all net inputs (parallel to
netInputShapes).
Returns
- long
computed FLOP.
GetLayer(int)
Returns pointer to layer with specified id which the network use.
public Layer GetLayer(int layerId)
Parameters
layerIdint
Returns
GetLayer(string)
Returns pointer to layer with specified name which the network use.
public Layer GetLayer(string layerName)
Parameters
layerNamestring
Returns
GetLayerId(string)
Converts string name of the layer to the integer identifier.
public int GetLayerId(string layer)
Parameters
layerstring
Returns
- int
id of the layer, or -1 if the layer wasn't found.
GetLayerNames()
public string?[] GetLayerNames()
Returns
- string[]
GetLayerShapes(IEnumerable<MatShape>, IEnumerable<MatType>, int, out MatShape[], out MatShape[])
Returns input and output shapes for the layer with the specified id; preliminary inferencing isn't necessary (OpenCV 5).
public void GetLayerShapes(IEnumerable<MatShape> netInputShapes, IEnumerable<MatType> netInputTypes, int layerId, out MatShape[] inLayerShapes, out MatShape[] outLayerShapes)
Parameters
netInputShapesIEnumerable<MatShape>shapes for all net inputs.
netInputTypesIEnumerable<MatType>element types for all net inputs (parallel to
netInputShapes).layerIdintid of the layer.
inLayerShapesMatShape[]output: input shapes of the layer.
outLayerShapesMatShape[]output: output shapes of the layer.
Remarks
When the model is backed by OpenCV 5's new dnn engine, only layerId 0
is supported (it infers the whole graph); other ids throw. Use GetLayersShapes(IEnumerable<MatShape>, IEnumerable<MatType>, out int[], out MatShape[][], out MatShape[][]) to
enumerate every layer, or pass one of the ids it reports.
GetLayerTypes()
Returns list of types for layer used in model.
public string?[] GetLayerTypes()
Returns
- string[]
GetLayersCount(string)
Returns count of layers of specified type.
public int GetLayersCount(string layerType)
Parameters
layerTypestringtype.
Returns
- int
count of layers
GetLayersShapes(IEnumerable<MatShape>, IEnumerable<MatType>, out int[], out MatShape[][], out MatShape[][])
Returns input and output shapes for all layers in the loaded model; preliminary inferencing isn't necessary (OpenCV 5).
public void GetLayersShapes(IEnumerable<MatShape> netInputShapes, IEnumerable<MatType> netInputTypes, out int[] layerIds, out MatShape[][] inLayersShapes, out MatShape[][] outLayersShapes)
Parameters
netInputShapesIEnumerable<MatShape>shapes for all net inputs.
netInputTypesIEnumerable<MatType>element types for all net inputs (parallel to
netInputShapes).layerIdsint[]output: layer IDs.
inLayersShapesMatShape[][]output: input shapes per layer (order matches
layerIds).outLayersShapesMatShape[][]output: output shapes per layer (order matches
layerIds).
GetMemoryConsumption(IEnumerable<MatShape>, IEnumerable<MatType>, out int[], out long[], out long[])
Computes the number of bytes required to store all weights and intermediate blobs for each layer (OpenCV 5).
public void GetMemoryConsumption(IEnumerable<MatShape> netInputShapes, IEnumerable<MatType> netInputTypes, out int[] layerIds, out long[] weights, out long[] blobs)
Parameters
netInputShapesIEnumerable<MatShape>shapes for all net inputs.
netInputTypesIEnumerable<MatType>element types for all net inputs (parallel to
netInputShapes).layerIdsint[]output: layer IDs.
weightslong[]output: bytes for weights per layer (order matches
layerIds).blobslong[]output: bytes for intermediate blobs per layer (order matches
layerIds).
GetMemoryConsumption(IEnumerable<MatShape>, IEnumerable<MatType>, out long, out long)
Computes the number of bytes required to store all weights and intermediate blobs for the model (OpenCV 5).
public void GetMemoryConsumption(IEnumerable<MatShape> netInputShapes, IEnumerable<MatType> netInputTypes, out long weights, out long blobs)
Parameters
netInputShapesIEnumerable<MatShape>shapes for all net inputs.
netInputTypesIEnumerable<MatType>element types for all net inputs (parallel to
netInputShapes).weightslongoutput: bytes for weights.
blobslongoutput: bytes for intermediate blobs.
GetModelFormat()
Returns the original framework format the network was loaded from.
public ModelFormat GetModelFormat()
Returns
GetParam(int, int)
Returns parameter blob of the layer.
public Mat GetParam(int layer, int numParam = 0)
Parameters
Returns
GetParam(string, int)
Returns parameter blob of the layer.
public Mat GetParam(string layerName, int numParam = 0)
Parameters
layerNamestringname of the layer.
numParamintindex of the layer parameter in the Layer::blobs array.
Returns
GetPerfProfile(out double[])
Returns overall time for inference and timings (in ticks) for layers. Indexes in returned vector correspond to layers ids.Some layers can be fused with others, in this case zero ticks count will be return for that skipped layers.
public long GetPerfProfile(out double[] timings)
Parameters
timingsdouble[]vector for tick timings for all layers.
Returns
- long
overall ticks for model inference.
GetPerfProfileDetailed(out string[], out string[], out string[])
Returns the detailed per-layer performance profile (new DNN engine, OpenCV 5): for each reported layer, its name, execution time and call count (all as strings).
public void GetPerfProfileDetailed(out string[] names, out string[] timems, out string[] counts)
Parameters
namesstring[]Output layer names.
timemsstring[]Output per-layer execution times (ms), as strings.
countsstring[]Output per-layer call counts, as strings.
GetUnconnectedOutLayers()
Returns indexes of layers with unconnected outputs.
public int[] GetUnconnectedOutLayers()
Returns
- int[]
GetUnconnectedOutLayersNames()
Returns names of layers with unconnected outputs.
public string?[] GetUnconnectedOutLayersNames()
Returns
- string[]
PrintPerfProfile()
Prints per-layer performance profile to the standard output.
public void PrintPerfProfile()
ReadFromModelOptimizer(string, string)
Create a network from Intel's Model Optimizer intermediate representation (IR). Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine backend.
public static Net? ReadFromModelOptimizer(string xml, string bin)
Parameters
xmlstringXML configuration file with network's topology.
binstringBinary file with trained weights.
Returns
ReadNet(string, string, string, EngineType)
Read deep learning network represented in one of the supported formats.
This function automatically detects an origin framework of trained model and calls an appropriate function such @ref readNetFromTensorflow, @ref readNetFromONNX, or @ref readNetFromModelOptimizer. The Caffe, Darknet and Torch parsers were removed in OpenCV 5.
public static Net ReadNet(string model, string config = "", string framework = "", EngineType engine = EngineType.Auto)
Parameters
modelstringBinary file contains trained weights. The following file * extensions are expected for models from different frameworks: * *
*.pb(TensorFlow, https://www.tensorflow.org/) * **.onnx(ONNX, https://onnx.ai/) * **.bin(OpenVINO, https://software.intel.com/openvino-toolkit)configstringText file contains network configuration. It could be a * file with the following extensions: * *
*.pbtxt(TensorFlow, https://www.tensorflow.org/) * **.xml(OpenVINO, https://software.intel.com/openvino-toolkit)frameworkstringExplicit framework name tag to determine a format.
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
ReadNetFromModelOptimizer(string, string)
Load a network from Intel's Model Optimizer intermediate representation. Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine backend.
public static Net? ReadNetFromModelOptimizer(string xml, string bin)
Parameters
xmlstringXML configuration file with network's topology.
binstringBinary file with trained weights.
Returns
ReadNetFromONNX(byte[], EngineType)
Reads a network model ONNX https://onnx.ai/ from memory
public static Net? ReadNetFromONNX(byte[] onnxFileData, EngineType engine = EngineType.Auto)
Parameters
onnxFileDatabyte[]memory of the first byte of the buffer.
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
- Net
Network object that ready to do forward, throw an exception in failure cases.
ReadNetFromONNX(ReadOnlySpan<byte>, EngineType)
Reads a network model ONNX https://onnx.ai/ from memory
public static Net? ReadNetFromONNX(ReadOnlySpan<byte> onnxFileData, EngineType engine = EngineType.Auto)
Parameters
onnxFileDataReadOnlySpan<byte>memory of the first byte of the buffer.
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
- Net
Network object that ready to do forward, throw an exception in failure cases.
ReadNetFromONNX(string, EngineType)
Reads a network model ONNX https://onnx.ai/
public static Net? ReadNetFromONNX(string onnxFile, EngineType engine = EngineType.Auto)
Parameters
onnxFilestringpath to the .onnx file with text description of the network architecture.
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
- Net
Network object that ready to do forward, throw an exception in failure cases.
ReadNetFromTFLite(byte[], EngineType)
Reads a network model stored in TFLite framework's format from memory.
public static Net? ReadNetFromTFLite(byte[] bufferModel, EngineType engine = EngineType.Auto)
Parameters
bufferModelbyte[]buffer containing the content of the tflite file.
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
- Net
Network object that ready to do forward, throw an exception in failure cases.
ReadNetFromTFLite(ReadOnlySpan<byte>, EngineType)
Reads a network model stored in TFLite framework's format from memory.
public static Net? ReadNetFromTFLite(ReadOnlySpan<byte> bufferModel, EngineType engine = EngineType.Auto)
Parameters
bufferModelReadOnlySpan<byte>buffer containing the content of the tflite file.
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
- Net
Network object that ready to do forward, throw an exception in failure cases.
ReadNetFromTFLite(string, EngineType)
Reads a network model stored in TFLite (https://www.tensorflow.org/lite) framework's format.
public static Net? ReadNetFromTFLite(string model, EngineType engine = EngineType.Auto)
Parameters
modelstringpath to the .tflite file with binary flatbuffers description of the network architecture.
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
- Net
Network object that ready to do forward, throw an exception in failure cases.
ReadNetFromTensorflow(byte[], byte[]?, EngineType)
Reads a network model stored in Tensorflow model from memory.
public static Net? ReadNetFromTensorflow(byte[] bufferModel, byte[]? bufferConfig = null, EngineType engine = EngineType.Auto)
Parameters
bufferModelbyte[]buffer containing the content of the pb file
bufferConfigbyte[]buffer containing the content of the pbtxt file (optional)
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
Remarks
This is shortcut consisting from createTensorflowImporter and Net::populateNet calls.
ReadNetFromTensorflow(ReadOnlySpan<byte>, ReadOnlySpan<byte>, EngineType)
Reads a network model stored in Tensorflow model from memory.
public static Net? ReadNetFromTensorflow(ReadOnlySpan<byte> bufferModel, ReadOnlySpan<byte> bufferConfig = default, EngineType engine = EngineType.Auto)
Parameters
bufferModelReadOnlySpan<byte>buffer containing the content of the pb file
bufferConfigReadOnlySpan<byte>buffer containing the content of the pbtxt file (optional)
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
Remarks
This is shortcut consisting from createTensorflowImporter and Net::populateNet calls.
ReadNetFromTensorflow(string, string?, EngineType)
Reads a network model stored in Tensorflow model file.
public static Net? ReadNetFromTensorflow(string model, string? config = null, EngineType engine = EngineType.Auto)
Parameters
modelstringpath to the .pb file with binary protobuf description of the network architecture
configstringpath to the .pbtxt file that contains text graph definition in protobuf format.
engineEngineTypeDNN engine to use. Auto tries the new engine first and falls back to the classic one.
Returns
- Net
Resulting Net object is built by text graph using weights from a binary one that let us make it more flexible.
Remarks
This is shortcut consisting from createTensorflowImporter and Net::populateNet calls.
RegisterOutput(string, int, int)
Registers a network output by name (new DNN engine, OpenCV 5).
public int RegisterOutput(string outputName, int layerId, int outputPort)
Parameters
outputNamestringName to register the output under.
layerIdintId of the producing layer.
outputPortintOutput port of the producing layer.
Returns
- int
The index of the registered output.
ResetKVCache()
Resets the Key-Value (KV) cache contents.
public void ResetKVCache()
SetInput(Mat, string)
Sets the new value for the layer output blob
public void SetInput(Mat blob, string name = "")
Parameters
Remarks
connect(String, String) to know format of the descriptor. If updating blob is not empty then @p blob must have the same shape, because network reshaping is not implemented yet.
SetInputShape(string, IEnumerable<int>)
Specify shape of network input.
public void SetInputShape(string inputName, IEnumerable<int> shape)
Parameters
inputNamestringname of the input layer.
shapeIEnumerable<int>the shape of the input blob.
SetInputsNames(IEnumerable<string>)
Sets outputs names of the network input pseudo layer.
public void SetInputsNames(IEnumerable<string> inputBlobNames)
Parameters
inputBlobNamesIEnumerable<string>
Remarks
- Each net always has special own the network input pseudo layer with id=0.
- This layer stores the user blobs only and don't make any computations.
- In fact, this layer provides the only way to pass user data into the network.
- As any other layer, this layer can label its outputs and this function provides an easy way to do this.
SetParam(int, int, Mat)
Sets the new value for the learned param of the layer.
public void SetParam(int layer, int numParam, Mat blob)
Parameters
layerintid of the layer.
numParamintindex of the layer parameter in the Layer::blobs array.
blobMatthe new value.
SetParam(string, int, Mat)
Sets the new value for the learned param of the layer.
public void SetParam(string layerName, int numParam, Mat blob)
Parameters
layerNamestringname of the layer.
numParamintindex of the layer parameter in the Layer::blobs array.
blobMatthe new value.
SetPreferableBackend(Backend)
Ask network to use specific computation backend where it supported.
public void SetPreferableBackend(Backend backendId)
Parameters
backendIdBackendbackend identifier.
SetPreferableTarget(Target)
Ask network to make computations on specific target device.
public void SetPreferableTarget(Target targetId)
Parameters
targetIdTargettarget identifier.