### File Organization Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/README.md Illustrates the directory structure of the opencvsharp repository, showing the location of README, quick start guides, type definitions, error handling, configuration, and API reference files for different modules. ```text output/ ├── README.md # This file ├── QUICK_START.md # Practical getting started guide ├── types.md # Type definitions reference ├── errors.md # Error handling guide └── configuration.md # Setup and configuration └── api-reference/ ├── 01-mat.md # Mat class reference ├── 02-cv2-core.md # Core operations ├── 03-cv2-imgproc.md # Image processing ├── 04-cv2-imgcodecs-highgui.md # File I/O and UI ├── 05-cv2-features2d-ml.md # Features and ML ├── 06-cv2-calib3d-video-object-detect.md └── 07-additional-modules.md # Advanced modules ``` -------------------------------- ### Load and Run ONNX Model Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/07-additional-modules.md Demonstrates loading an ONNX model, preparing an input image into a blob, setting it as input to the network, and performing a forward pass to get the results. ```csharp // Load ONNX model using var net = Net.ReadNetFromONNX("model.onnx"); // Prepare input blob using var img = Cv2.Imread("input.jpg"); using var blob = CvDnn.BlobFromImage(img, 1.0, new Size(224, 224), new Scalar(104, 117, 123), false, false); net.SetInput(blob); using var result = net.Forward(); // Process output // ... extract predictions from result Mat ``` -------------------------------- ### Configuration Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/INDEX.md Guide to setting up and tuning OpenCVSharp, including memory management, platform-specific setup, and performance tuning. ```APIDOC ## Configuration ### Description Details on how to configure and tune OpenCVSharp for different environments and performance needs. ### Memory Management - **ResourcesTracker**: Configuration and usage for managing native resources. ### Platform-Specific Setup - **Windows DLL**: Instructions for setting up on Windows. - **Linux SO**: Instructions for setting up on Linux. - **macOS dylib**: Instructions for setting up on macOS. ### Runtime Package Selection - Options for selecting the appropriate runtime package for each platform. ### Module Selection - Information on choosing between full and slim builds. ### Performance Tuning - **thread count**: Adjusting the number of threads used for processing. - **memory allocation**: Configuring memory allocation strategies. ### NuGet Package Configuration - Guidance on configuring OpenCVSharp via NuGet packages. ### Extension Packages - Information on integrating with GDI+ and WPF. ### Build-time CMake Options - Details on CMake options available during the build process. ### Debugging Configuration - Settings and tips for debugging OpenCVSharp applications. ### Recommended Settings - Suggestions for optimal settings based on common scenarios. ``` -------------------------------- ### Install OpenCvSharp Core Library Source: https://github.com/shimat/opencvsharp/blob/main/docs/docfx/articles/intro.md Install the core OpenCvSharp library using the .NET CLI. ```bash dotnet add package OpenCvSharp4 ``` -------------------------------- ### Install OpenCvSharp Source: https://github.com/shimat/opencvsharp/wiki/Tutorial-for-Ubuntu-14.04 Builds and installs OpenCvSharp from its GitHub repository. This involves cloning the repository and using CMake and Make. ```bash cd git clone https://github.com/shimat/opencvsharp.git cd opencvsharp/src cmake . make -j 4 sudo make install ``` -------------------------------- ### Install OpenCvSharp4 Runtime for Windows x64 Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Install the main package and the Windows x64 runtime package for OpenCvSharp. ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.win ``` -------------------------------- ### Install OpenCvSharp NuGet Packages Source: https://github.com/shimat/opencvsharp/blob/main/docs/docfx/index.md Install the core OpenCvSharp package and the Windows runtime package using the .NET CLI. ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.win # For Windows ``` -------------------------------- ### Install OpenCvSharp Native Bindings for Windows Source: https://github.com/shimat/opencvsharp/blob/main/docs/docfx/articles/intro.md Install the native runtime bindings for OpenCvSharp on Windows. ```bash dotnet add package OpenCvSharp4.runtime.win ``` -------------------------------- ### Install OpenCvSharp4 Runtime for Windows ARM64 Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Install the main package and the Windows ARM64 runtime package for OpenCvSharp. ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.win-arm64 ``` -------------------------------- ### Build and Install OpenCV Source: https://github.com/shimat/opencvsharp/blob/main/docs/embedded-builds.md Compile the OpenCV libraries using multiple processor cores and install them to the specified prefix. This step can take a significant amount of time. ```bash make -j$(nproc) sudo make install ``` -------------------------------- ### Install Mono Source: https://github.com/shimat/opencvsharp/wiki/Tutorial-for-Ubuntu-14.04 Installs the Mono development environment, which is required for OpenCvSharp. ```bash sudo apt-get install mono-complete ``` -------------------------------- ### Install Media Foundation on Windows Server Source: https://github.com/shimat/opencvsharp/blob/main/nuget/README.managed.md On Windows Server, Media Foundation is required. Use this PowerShell command to install it. ```powershell Install-WindowsFeature Server-Media-Foundation ``` -------------------------------- ### Panorama Creation Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/07-additional-modules.md Demonstrates how to use the Stitcher to create a panorama from multiple images. ```csharp var images = new Mat[] { Cv2.Imread("img1.jpg"), Cv2.Imread("img2.jpg"), Cv2.Imread("img3.jpg") }; using var stitcher = Stitcher.CreateDefault(); var status = stitcher.Stitch(images, out var panorama); if (status == Stitcher.Status.Ok) { Cv2.Imwrite("panorama.jpg", panorama); } ``` -------------------------------- ### Install OpenCvSharp Native Bindings for Linux x64 Source: https://github.com/shimat/opencvsharp/blob/main/docs/docfx/articles/intro.md Install the native runtime bindings for OpenCvSharp on Linux x64. ```bash dotnet add package OpenCvSharp4.official.runtime.linux-x64 ``` -------------------------------- ### Install OpenCvSharp4 Runtime for Linux x64 (Slim) Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Install the main package and the official Linux x64 slim runtime package for OpenCvSharp. ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.official.runtime.linux-x64.slim ``` -------------------------------- ### Install OpenCvSharp4 Runtime for macOS x64 Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Install the main package and the macOS x64 runtime package for OpenCvSharp. ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.osx.x64 ``` -------------------------------- ### Install Build Dependencies Source: https://github.com/shimat/opencvsharp/blob/main/docs/embedded-builds.md Install essential development tools and libraries required for building OpenCV on Debian-based systems. ```bash sudo apt update sudo apt install -y \ build-essential \ cmake \ git \ pkg-config \ libgtk-3-dev \ libavcodec-dev \ libavformat-dev \ libswscale-dev \ libv4l-dev ``` -------------------------------- ### Install system packages on Ubuntu Source: https://github.com/shimat/opencvsharp/blob/main/README.md Installs necessary development libraries for building OpenCV and its dependencies using the system package manager (apt). ```bash sudo apt-get install -y g++ cmake libtesseract-dev \ libjpeg-dev libpng-dev libtiff-dev libwebp-dev \ libavcodec-dev libavformat-dev libswscale-dev ``` -------------------------------- ### Install OpenCvSharp4 Runtime for Linux x64 Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Install the main package and the official Linux x64 runtime package for OpenCvSharp. ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.official.runtime.linux-x64 ``` -------------------------------- ### Install OpenCvSharp Packages Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/QUICK_START.md Add the appropriate OpenCvSharp and runtime packages for your specific platform using the dotnet CLI. ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.win ``` ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.win-arm64 ``` ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.official.runtime.linux-x64 ``` ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.osx.x64 ``` ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.osx.arm64 ``` -------------------------------- ### Example: Erosion and Structuring Element Creation Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/03-cv2-imgproc.md Demonstrates how to create an elliptical structuring element and then apply erosion to a source image. ```csharp using var element = Cv2.GetStructuringElement(MorphShapes.Ellipse, new Size(5, 5)); using var result = new Mat(); Cv2.Erode(src, result, element); ``` -------------------------------- ### Install GTK3 on RHEL/AlmaLinux Source: https://github.com/shimat/opencvsharp/blob/main/nuget/README.managed.md For RHEL/AlmaLinux systems, use 'dnf' to install the GTK3 dependency if needed for GUI functionalities. ```bash dnf install gtk3 ``` -------------------------------- ### Install OpenCvSharp Native Bindings for macOS x64 Source: https://github.com/shimat/opencvsharp/blob/main/docs/docfx/articles/intro.md Install the native runtime bindings for OpenCvSharp on macOS x64. ```bash dotnet add package OpenCvSharp4.runtime.osx.x64 ``` -------------------------------- ### macOS Native Library Installation via NuGet (x64) Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Provides the command to add the OpenCvSharp4.runtime.osx.x64 NuGet package for macOS on Intel processors. This installs the necessary native library. ```bash # For Intel (x64) dotnet add package OpenCvSharp4.runtime.osx.x64 ``` -------------------------------- ### TermCriteria Initialization Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/05-cv2-features2d-ml.md Demonstrates how to initialize a TermCriteria object for an iterative algorithm. It combines epsilon and count criteria for convergence. ```csharp var criteria = new TermCriteria( CriteriaTypes.Eps | CriteriaTypes.Count, 100, // Max 100 iterations 0.001 // Or until change < 0.001 ); ``` -------------------------------- ### RTrees Example Usage Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/05-cv2-features2d-ml.md Example of creating and training a Random Forest classifier. ```csharp using var forest = RTrees.Create(); forest.Train(trainData, SampleTypes.RowSample, responses); ``` -------------------------------- ### macOS Native Library Installation via NuGet (arm64) Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Provides the command to add the OpenCvSharp4.runtime.osx.arm64 NuGet package for macOS on Apple Silicon (arm64) processors. This installs the necessary native library. ```bash # For Apple Silicon (arm64) dotnet add package OpenCvSharp4.runtime.osx.arm64 ``` -------------------------------- ### Basic Image Processing with OpenCvSharp Source: https://github.com/shimat/opencvsharp/blob/main/docs/docfx/articles/intro.md A quick example demonstrating loading an image, converting it to grayscale, applying a Gaussian blur, and saving the result using OpenCvSharp. ```csharp using OpenCvSharp; // Load an image using var src = Cv2.ImRead("sample.jpg"); // Convert to grayscale using var gray = new Mat(); Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY); // Apply Gaussian blur using var blurred = new Mat(); Cv2.GaussianBlur(gray, blurred, new Size(5, 5), 0); // Save the result Cv2.ImWrite("output.jpg", blurred); ``` -------------------------------- ### Install OpenCvSharp4 Runtime for macOS ARM64 Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Install the main package and the macOS ARM64 (Apple Silicon) runtime package for OpenCvSharp. ```bash dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.runtime.osx.arm64 ``` -------------------------------- ### Create Range Instances Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/types.md Examples of creating Range instances for slicing operations. `Range.All` represents all elements. ```csharp var firstHalf = new Range(0, mat.Rows / 2); var allRows = Range.All; ``` -------------------------------- ### Install vcpkg dependencies on Ubuntu Source: https://github.com/shimat/opencvsharp/blob/main/README.md Installs vcpkg dependencies for building OpenCV on Ubuntu. Replace '/path/to/vcpkg' with your actual vcpkg path. ```bash # Install dependencies via vcpkg /path/to/vcpkg/vcpkg install \ --triplet x64-linux-static \ --overlay-triplets cmake/triplets ``` -------------------------------- ### Install OpenCvSharp-AnyCPU via Package Manager Console Source: https://github.com/shimat/opencvsharp/wiki/How to Install via NuGet Use this command in the Package Manager Console to install the OpenCvSharp NuGet package. This package includes all necessary native OpenCV libraries. ```powershell PM> Install-Package OpenCvSharp-AnyCPU ``` -------------------------------- ### Common Workflow Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/04-cv2-imgcodecs-highgui.md Demonstrates a typical workflow for image processing using OpenCVSharp, including reading, converting color, blurring, saving, and displaying images. ```APIDOC ## Common Workflow ### Description This example illustrates a common sequence of operations for image manipulation: 1. Reading an image from a file. 2. Converting the image to grayscale. 3. Applying a Gaussian blur. 4. Saving the processed image. 5. Displaying the original and processed images. ### Code Example ```csharp using OpenCvSharp; // Read image using var img = Cv2.Imread("input.jpg", ImreadModes.Color); if (img.Empty()) { Console.WriteLine("Cannot load image"); return; } // Process using var gray = new Mat(); Cv2.CvtColor(img, gray, ColorConversionCodes.BGR2GRAY); using var blurred = new Mat(); Cv2.GaussianBlur(gray, blurred, new Size(5, 5), 1.0); // Save result bool success = Cv2.Imwrite("output.jpg", blurred); // Display (with debugging) Cv2.ImShow("Original", img); Cv2.ImShow("Result", blurred); Cv2.WaitKey(0); Cv2.DestroyAllWindows(); ``` ``` -------------------------------- ### Install GTK3 on Linux Source: https://github.com/shimat/opencvsharp/blob/main/nuget/README.managed.md If GTK3 is not pre-installed on your Linux environment and you need GUI support (e.g., Cv2.ImShow), use this command. ```bash apt-get install libgtk-3-0 ``` -------------------------------- ### Example: Opening Morphological Operation Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/03-cv2-imgproc.md Illustrates how to perform an 'opening' morphological operation, which is defined as an erosion followed by a dilation, using MorphologyEx. ```csharp using var element = Cv2.GetStructuringElement(MorphShapes.Ellipse, new Size(5, 5)); using var result = new Mat(); // Opening = erosion followed by dilation Cv2.MorphologyEx(src, result, MorphTypes.Open, element); ``` -------------------------------- ### Install vcpkg dependencies on Windows Source: https://github.com/shimat/opencvsharp/blob/main/README.md Installs vcpkg dependencies for building OpenCV. This command is typically needed only once or after changes to vcpkg.json. ```powershell C:\vcpkg\vcpkg.exe install --triplet x64-windows-static --overlay-triplets cmake\triplets --x-install-root vcpkg_installed ``` -------------------------------- ### KNearest Example Usage Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/05-cv2-features2d-ml.md Example of creating, training, and using a KNearest classifier to predict a label for a test sample. ```csharp using var knn = KNearest.Create(); knn.Train(trainingSamples, SampleTypes.RowSample, labels); float prediction = knn.Predict(testSample); ``` -------------------------------- ### Install OpenCvSharp Native Bindings for macOS arm64 Source: https://github.com/shimat/opencvsharp/blob/main/docs/docfx/articles/intro.md Install the native runtime bindings for OpenCvSharp on macOS arm64 (Apple Silicon). ```bash dotnet add package OpenCvSharp4.runtime.osx.arm64 ``` -------------------------------- ### Create Scalar Instances Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/types.md Examples of creating Scalar instances for common use cases like white, red, and transparent black. ```csharp var white = new Scalar(255); // Grayscale white var red = new Scalar(0, 0, 255); // BGR red var transparent = new Scalar(0, 0, 0, 0); // Transparent black ``` -------------------------------- ### Barcode Detection and Decoding Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/07-additional-modules.md Demonstrates how to use the BarcodeDetector to detect and decode a barcode from an image. Ensure 'barcode.jpg' is in the execution directory. ```csharp using var detector = new BarcodeDetector(); using var img = Cv2.Imread("barcode.jpg"); if (detector.DetectAndDecode(img, out string data)) { Console.WriteLine($"Barcode: {data}"); } ``` -------------------------------- ### SIFT Feature Detection and Computation Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/05-cv2-features2d-ml.md Demonstrates how to use the SIFT detector to find keypoints and compute their descriptors from a grayscale image. Ensure the image file exists and is accessible. ```csharp using var sift = SIFT.Create(); using var img = Cv2.Imread("image.jpg", ImreadModes.Grayscale); sift.Detect(img, out var keypoints); using var descriptors = new Mat(); sift.Compute(img, ref keypoints, descriptors); ``` -------------------------------- ### Accessing Pixels with Get/Set Source: https://github.com/shimat/opencvsharp/wiki/Accessing-Pixel Use Get/Set for simple pixel access when performance is not critical. This method involves overhead for each pixel access. ```csharp Mat mat = new Mat("lenna.png", LoadMode.Color); for (int y = 0; y < mat.Height; y++) { for (int x = 0; x < mat.Width; x++) { Vec3b color = mat.Get(y, x); byte temp = color.Item0; color.Item0 = color.Item2; // B <- R color.Item2 = temp; // R <- B mat.Set(y, x, color); } } ``` -------------------------------- ### Indexing & Data Access Examples Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Demonstrates various ways to access and manipulate matrix elements and rows/columns using different methods provided by the Mat class. ```APIDOC ## Indexing & Data Access ### Description The Mat class supports various indexing patterns: ### Code Examples ```csharp // Element access by index byte value = mat.Get(i, j); mat.Set(i, j, 255); // Row/Column access (returns Mat headers) using var row = mat.Row(i); using var col = mat.Col(j); // Indexer for 1D access using var element = mat.At(index); ``` ``` -------------------------------- ### Configure and build native wrapper OpenCvSharpExtern on Windows Source: https://github.com/shimat/opencvsharp/blob/main/README.md Configures the native wrapper using CMake with specified paths and toolchain, then builds it in Release mode. Ensure CMAKE_TOOLCHAIN_FILE points to your vcpkg installation. ```powershell cmake -S src -B src\build -G "Visual Studio 17 2022" -A x64 \ -D "CMAKE_PREFIX_PATH=$PWD\opencv_artifacts" \ -D CMAKE_TOOLCHAIN_FILE="C:\vcpkg\scripts\buildsystems\vcpkg.cmake" \ -D VCPKG_TARGET_TRIPLET=x64-windows-static \ -D "VCPKG_INSTALLED_DIR=$PWD\vcpkg_installed" \ -D "VCPKG_OVERLAY_TRIPLETS=$PWD\cmake\triplets" ``` ```powershell cmake --build src\build --config Release ``` -------------------------------- ### Install OpenCvSharp4 on Linux Source: https://github.com/shimat/opencvsharp/blob/main/README.md Use these commands to add the OpenCvSharp4 package and the official Linux runtime to your .NET console project. The slim profile option is also shown. ```bash dotnet new console -n ConsoleApp01 cd ConsoleApp01 dotnet add package OpenCvSharp4 dotnet add package OpenCvSharp4.official.runtime.linux-x64 # or slim profile: # dotnet add package OpenCvSharp4.official.runtime.linux-x64.slim # -- edit Program.cs -- # dotnet run ``` -------------------------------- ### Build native wrapper using system OpenCV path on Ubuntu Source: https://github.com/shimat/opencvsharp/blob/main/README.md Builds the native wrapper OpenCvSharpExtern using CMake. Ensure CMAKE_PREFIX_PATH is set to your OpenCV installation directory. ```bash cmake -S src -B src/build \ -D CMAKE_BUILD_TYPE=Release \ -D CMAKE_PREFIX_PATH=${YOUR_OPENCV_INSTALL_PATH} ``` ```bash cmake --build src/build -j$(nproc) ``` -------------------------------- ### Get Matrix Channels Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Returns the number of channels per element in the matrix. For example, a grayscale image has 1 channel, and an RGB image has 3. ```csharp public int Channels { get; } ``` -------------------------------- ### Get Tick Count for Performance Timing Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/04-cv2-imgcodecs-highgui.md Returns the number of clock cycles since the system was started. This is used in conjunction with GetTickFrequency for precise performance measurements. ```csharp public static long GetTickCount() ``` -------------------------------- ### Configure CMake for Windows Build Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Example CMake configuration for building OpenCVSharp on Windows using Visual Studio and vcpkg. Specifies build artifacts path and toolchain file. ```bash # Windows cmake -S src -B src/build -G "Visual Studio 17 2022" ^ -D CMAKE_PREFIX_PATH=%cd%\opencv_artifacts ^ -D CMAKE_TOOLCHAIN_FILE=C:\vcpkg\scripts\buildsystems\vcpkg.cmake ``` -------------------------------- ### Install OpenCV 2.4.10 Source: https://github.com/shimat/opencvsharp/wiki/Tutorial-for-Ubuntu-14.04 Installs OpenCV version 2.4.10 and its development dependencies. This specific version is required. ```bash sudo apt-get install cmake libgtk2.0-dev libv4l-dev libavcodec-dev libavformat-dev libswscale-dev cd wget http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.10/opencv-2.4.10.zip unzip opencv-2.4.10.zip cd opencv-2.4.10 cmake . make -j 4 sudo make install ``` -------------------------------- ### Creating Custom Channel Counts for MatType Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/types.md Demonstrates how to create MatType instances with custom channel counts using static helper methods. ```csharp var type8ChannelByte = MatType.CV_8UC(8); var type3ChannelFloat = MatType.CV_32FC(3); ``` -------------------------------- ### BFMatcher Example Usage Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/05-cv2-features2d-ml.md Example of using BFMatcher to find matches between two sets of descriptors and filtering them by distance. ```csharp using var matcher = BFMatcher.Create(NormTypes.Hamming, false); DMatch[] matches; matcher.Match(descriptors1, descriptors2, out matches); // Filter matches by distance var goodMatches = matches.Where(m => m.Distance < 50).ToArray(); ``` -------------------------------- ### Basic Image Processing Example Source: https://github.com/shimat/opencvsharp/wiki/How to Install via NuGet This C# code demonstrates loading an image, applying an inverse operation to a region of interest, and displaying the result in a window. Ensure you have a 'C:\Lenna.png' file for this to run. ```csharp using System; using OpenCvSharp; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { using (var img = new IplImage(@"C:\Lenna.png")) { Cv.SetImageROI(img, new CvRect(200, 200, 180, 200)); Cv.Not(img, img); Cv.ResetImageROI(img); using (new CvWindow(img)) { Cv.WaitKey(); } } } } } ``` -------------------------------- ### Clone and Build OpenCVSharp Minimal Source: https://github.com/shimat/opencvsharp/blob/main/docs/embedded-builds.md Steps to clone the necessary OpenCVSharp and OpenCV repositories, checkout a specific version, and run the minimal build script for ARM64. This is recommended for basic camera capture functionality. ```bash cd ~ git clone https://github.com/opencv/opencv.git git clone https://github.com/opencv/opencv_contrib.git # only needed for full build git clone https://github.com/shimat/opencvsharp.git cd ~/opencv git fetch --tags git checkout 4.10.0 # Only for full build: cd ~/opencv_contrib git fetch --tags git checkout 4.10.0 # Run the desired build script cd ~ chmod +x ~/opencvsharp/src/tools/build-opencvsharp-minimal-arm64.sh ~/opencvsharp/src/tools/build-opencvsharp-minimal-arm64.sh ``` -------------------------------- ### Detect BRISK Keypoints and Draw on Image Source: https://github.com/shimat/opencvsharp/wiki/BRISK This snippet shows how to load a grayscale image, initialize the BRISK detector, detect keypoints, and draw circles and lines representing these keypoints on a destination image. ```csharp var gray = new Mat("lena.png", LoadMode.GrayScale); var brisk = new BRISK(); KeyPoint[] keypoints = brisk.Detect(gray); foreach (KeyPoint kpt in keypoints) { var color = new Scalar(0, 255, 0); float r = kpt.Size / 2; Cv2.Circle(dst, kpt.Pt, (int)r, color, 1, LineType.Link8, 0); Cv2.Line(dst, new Point2f(kpt.Pt.X + r, kpt.Pt.Y + r), new Point2f(kpt.Pt.X - r, kpt.Pt.Y - r), color, 1, LineType.Link8, 0); Cv2.Line(dst, new Point2f(kpt.Pt.X - r, kpt.Pt.Y + r), new Point2f(kpt.Pt.X + r, kpt.Pt.Y - r), color, 1, LineType.Link8, 0); } } ``` -------------------------------- ### Create and Load Mat Objects Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/README.md Demonstrates various ways to create and initialize Mat objects, including empty, from file, with specific dimensions, from a scalar value, and as a submatrix (ROI). Always use `using` for automatic disposal. ```csharp using var mat = new Mat(); ``` ```csharp using var img = new Mat("image.jpg", ImreadModes.Color); ``` ```csharp using var zeros = new Mat(480, 640, MatType.CV_8UC3); ``` ```csharp using var ones = new Mat(480, 640, MatType.CV_8UC3, new Scalar(255)); ``` ```csharp using var roi = new Mat(img, new Rect(0, 0, 100, 100)); ``` -------------------------------- ### Add OpenCvSharp4.Windows Package Source: https://github.com/shimat/opencvsharp/blob/main/nuget/README.managed.md Use this command to add the OpenCvSharp4.Windows package for Windows installations. ```bash dotnet add package OpenCvSharp4.Windows ``` -------------------------------- ### Get Total Number of Elements Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Calculates and returns the total number of elements in the matrix across all dimensions. ```csharp public long Total { get; } ``` -------------------------------- ### Get Matrix Columns Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Access the number of columns in the matrix. This property indicates the matrix's width. ```csharp public int Cols { get; } ``` -------------------------------- ### Get Matrix Rows Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Access the number of rows in the matrix. This property indicates the matrix's height. ```csharp public int Rows { get; } ``` -------------------------------- ### Get or Set Element by Type Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Accesses or modifies an element at a specific row and column, specifying the data type. ```csharp public T Get(int i0, int i1) where T : struct public void Set(int i0, int i1, T value) where T : struct ``` -------------------------------- ### Get Matrix Size Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Returns the 2D size of the matrix as a `Size` struct, typically represented as (width, height). ```csharp public Size Size { get; } ``` -------------------------------- ### Get Matrix Type Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Obtain the data type and channel count of the matrix elements. This is represented by the `MatType` enum. ```csharp public MatType Type { get; } ``` -------------------------------- ### Advanced Resource Management with ResourcesTracker Source: https://github.com/shimat/opencvsharp/blob/main/nuget/README.managed.md Illustrates managing multiple `Mat` and `Window` resources automatically using `ResourcesTracker` for complex image processing pipelines. This approach simplifies cleanup for numerous disposable objects. ```csharp using var t = new ResourcesTracker(); var src = t.T(new Mat("lenna.png", ImreadModes.Grayscale)); var dst = t.NewMat(); Cv2.Canny(src, dst, 50, 200); var blurred = t.T(dst.Blur(new Size(3, 3))); t.T(new Window("src image", src)); t.T(new Window("dst image", blurred)); Cv2.WaitKey(); ``` -------------------------------- ### Common Image Processing Workflow in OpenCVSharp Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/04-cv2-imgcodecs-highgui.md A complete example demonstrating a typical image processing pipeline: reading an image, converting it to grayscale, applying Gaussian blur, saving the result, and displaying the original and processed images. ```csharp using OpenCvSharp; // Read image using var img = Cv2.Imread("input.jpg", ImreadModes.Color); if (img.Empty()) { Console.WriteLine("Cannot load image"); return; } // Process using var gray = new Mat(); Cv2.CvtColor(img, gray, ColorConversionCodes.BGR2GRAY); using var blurred = new Mat(); Cv2.GaussianBlur(gray, blurred, new Size(5, 5), 1.0); // Save result bool success = Cv2.Imwrite("output.jpg", blurred); // Display (with debugging) Cv2.ImShow("Original", img); Cv2.ImShow("Result", blurred); Cv2.WaitKey(0); Cv2.DestroyAllWindows(); ``` -------------------------------- ### Get Matrix Dimensions Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Retrieves the number of dimensions (rank) of the matrix. For standard 2D images, this is typically 2. ```csharp public int Dims { get; } ``` -------------------------------- ### Build OpenCV and OpenCvSharpExtern using vcpkg on Ubuntu Source: https://github.com/shimat/opencvsharp/blob/main/README.md Builds OpenCV and the native wrapper OpenCvSharpExtern using CMake, pointing to vcpkg for dependencies. Replace '/path/to/vcpkg' with your actual vcpkg path. ```bash cmake -C cmake/opencv_build_options.cmake \ -S opencv -B opencv/build \ -D OPENCV_EXTRA_MODULES_PATH=$PWD/opencv_contrib/modules \ -D CMAKE_INSTALL_PREFIX=$PWD/opencv_artifacts \ -D CMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake \ -D VCPKG_TARGET_TRIPLET=x64-linux-static cmake --build opencv/build -j$(nproc) cmake --install opencv/build cmake -S src -B src/build \ -D CMAKE_BUILD_TYPE=Release \ -D CMAKE_PREFIX_PATH=$PWD/opencv_artifacts \ -D CMAKE_TOOLCHAIN_FILE=/path/to/vcpkg/scripts/buildsystems/vcpkg.cmake \ -D VCPKG_TARGET_TRIPLET=x64-linux-static cmake --build src/build -j$(nproc) ``` -------------------------------- ### Build Docker Image Source: https://github.com/shimat/opencvsharp/blob/main/docker/command_sample.txt Builds a Docker image with the tag shimat/appengine-aspnetcore2.1-opencv4.2.0 from the current directory's Dockerfile. ```bash docker build -t shimat/appengine-aspnetcore2.1-opencv4.2.0 . ``` -------------------------------- ### Error Handling Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/INDEX.md Guide to exception handling in OpenCVSharp, detailing exception types, common error scenarios, and best practices. ```APIDOC ## Error Handling ### Description Information on how to handle exceptions and common error scenarios in OpenCVSharp. ### Exception Types - **OpenCvSharpException**: Base exception class for OpenCVSharp. - **OpenCVException**: Exception originating from the native OpenCV library. ### Common Error Scenarios - File not found - Invalid Mat dimensions - Invalid MatType - Size mismatch - Type mismatch - Memory allocation failure - Access after disposal - Null input arguments - Invalid ROI - Invalid kernel size - Image format issues - Feature detection failures - Empty input validation - Video capture failures ### Best Practices - Always use `using` statements for resource management. - Validate inputs before performing operations. - Wrap potentially problematic code in `try-catch` blocks. - Use `ResourcesTracker` for managing complex resource allocations. - Check operation success where applicable. ``` -------------------------------- ### Display Image with ImShow and WaitKey Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/04-cv2-imgcodecs-highgui.md Displays an image in a window and waits for a key press. Requires GTK3 on Linux for full functionality. Use Cv2.DestroyAllWindows() to close all windows. ```csharp using var img = Cv2.Imread("photo.jpg", ImreadModes.Color); Cv2.ImShow("Image Viewer", img); Cv2.WaitKey(0); // Wait for key press Cv2.DestroyAllWindows(); ``` -------------------------------- ### Drawing a Rectangle Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/03-cv2-imgproc.md Provides the signature for drawing a rectangle on an image. Parameters include start and end points, color, and thickness. ```csharp public static void Rectangle(InputOutputArray img, Point pt1, Point pt2, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Connected8, int shift = 0) ``` -------------------------------- ### Display Image in a Window using Window Class Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/04-cv2-imgcodecs-highgui.md Use the `Window` class for persistent window management to display an image. Ensure the image file exists and is accessible. ```csharp using var img = Cv2.Imread("image.jpg", ImreadModes.Color); using (var window = new Window("Display", img)) { Cv2.WaitKey(0); } ``` -------------------------------- ### Complete Feature Matching Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/05-cv2-features2d-ml.md Demonstrates a complete workflow for feature matching between two images using ORB for feature detection and computation, and BFMatcher with Hamming distance for matching, followed by Lowe's ratio test to filter good matches. ```APIDOC ## Complete Feature Matching Example ```csharp using OpenCvSharp; // Load images using var img1 = Cv2.Imread("scene.jpg", ImreadModes.Grayscale); using var img2 = Cv2.Imread("object.jpg", ImreadModes.Grayscale); // Detect and compute features using var orb = ORB.Create(5000); orb.DetectAndCompute(img1, null, out var kp1, descriptors1); orb.DetectAndCompute(img2, null, out var kp2, descriptors2); // Match features using var matcher = BFMatcher.Create(NormTypes.Hamming, false); matcher.KnnMatch(descriptors1, descriptors2, out var matches, 2); // Apply Lowe's ratio test var goodMatches = new List(); foreach (var matchPair in matches) { if (matchPair.Length == 2 && matchPair[0].Distance < 0.75f * matchPair[1].Distance) { goodMatches.Add(matchPair[0]); } } Console.WriteLine($"Good matches: {goodMatches.Count}"); ``` ``` -------------------------------- ### Get Element Size in Bytes Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/01-mat.md Returns the size, in bytes, of a single element in the matrix, considering its data type and channel count. ```csharp public int ElementSize { get; } ``` -------------------------------- ### Compile OpenCvSharpExtern on Unix Source: https://github.com/shimat/opencvsharp/wiki/Tutorial-for-Unix Navigate to the source directory, configure with CMake, and build the C++ wrapper using Make. This generates the necessary shared library for Unix platforms. ```bash cd opencvsharp/src cmake . make ``` -------------------------------- ### Convert Mat to Bitmap and vice-versa Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/configuration.md Utilize the OpenCvSharp.Extensions package to convert between Mat and System.Drawing.Bitmap objects. Ensure the package is installed for Windows projects. ```csharp using OpenCvSharp.Extensions; using System.Drawing; // Mat to Bitmap using var mat = Cv2.Imread("image.jpg"); Bitmap bitmap = mat.ToBitmap(); // Bitmap to Mat using var convertedMat = bitmap.ToMat(); // Bitmap to Mat with color conversion using var grayMat = bitmap.ToMat(ImreadModes.Grayscale); ``` -------------------------------- ### Complete Feature Matching Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/05-cv2-features2d-ml.md Performs feature detection, description, and matching between two images using ORB and BFMatcher. Applies Lowe's ratio test to filter good matches. ```csharp using OpenCvSharp; // Load images using var img1 = Cv2.Imread("scene.jpg", ImreadModes.Grayscale); using var img2 = Cv2.Imread("object.jpg", ImreadModes.Grayscale); // Detect and compute features using var orb = ORB.Create(5000); orb.DetectAndCompute(img1, null, out var kp1, descriptors1); orb.DetectAndCompute(img2, null, out var kp2, descriptors2); // Match features using var matcher = BFMatcher.Create(NormTypes.Hamming, false); matcher.KnnMatch(descriptors1, descriptors2, out var matches, 2); // Apply Lowe's ratio test var goodMatches = new List(); foreach (var matchPair in matches) { if (matchPair.Length == 2 && matchPair[0].Distance < 0.75f * matchPair[1].Distance) { goodMatches.Add(matchPair[0]); } } Console.WriteLine($"Good matches: {goodMatches.Count}"); ``` -------------------------------- ### Capture Video from Camera Device Source: https://github.com/shimat/opencvsharp/wiki/Capturing-Video Opens the default camera (index 0) and displays the video stream in a window. The loop continues until an empty frame is read, indicating the end of the stream or an error. ```csharp public static void Main(string[] args) { VideoCapture capture = new VideoCapture(0); using (Window window = new Window("Camera")) using (Mat image = new Mat()) // Frame image buffer { // When the movie playback reaches end, Mat.data becomes NULL. while (true) { capture.Read(image); // same as cvQueryFrame if (image.Empty())break; window.ShowImage(image); Cv2.WaitKey(30); } } } ``` -------------------------------- ### BorderInterpolate C# Example Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/02-cv2-core.md Calculates the source pixel index for an extrapolated pixel using BorderInterpolate. This is useful for understanding how border pixels are determined. ```csharp int srcPixel = Cv2.BorderInterpolate(-5, 640, BorderTypes.Reflect); ``` -------------------------------- ### Get OpenCV Build Information Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/04-cv2-imgcodecs-highgui.md Retrieves detailed build information for the OpenCV library. This can be useful for debugging or understanding specific build configurations. ```csharp public static string GetBuildInformation() ``` -------------------------------- ### Docker Login and Push Source: https://github.com/shimat/opencvsharp/blob/main/docker/command_sample.txt Logs into a Docker registry and pushes the previously built image. Ensure you are logged in before pushing. ```bash docker login docker push shimat/appengine-aspnetcore2.1-opencv4.2.0 ``` -------------------------------- ### Get OpenCV Version String Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/04-cv2-imgcodecs-highgui.md Retrieves the current version of the OpenCV library as a string. Use this to check compatibility or display version information. ```csharp public static string GetVersionString() ``` -------------------------------- ### VideoCapture Source: https://github.com/shimat/opencvsharp/blob/main/_autodocs/api-reference/06-cv2-calib3d-video-object-detect.md Provides functionality to capture video from files or camera devices. It allows reading frames, getting video properties, and controlling playback. ```APIDOC ## VideoCapture ### Description Provides functionality to capture video from files or camera devices. It allows reading frames, getting video properties, and controlling playback. ### Constructors * **VideoCapture(string fileName)**: Opens a video file for reading. * **VideoCapture(int deviceId)**: Opens a camera device for capturing video. ### Properties * **IsOpened** (bool): Gets a value indicating whether the video capture device is opened. * **FrameCount** (int): Gets the total number of frames in the video file. * **Fps** (double): Gets the frames per second of the video stream. * **FrameWidth** (int): Gets the width of the video frames. * **FrameHeight** (int): Gets the height of the video frames. * **CurrentFrame** (double): Gets or sets the current position in the video file (in frames). ### Methods * **Read(OutputArray image)**: Reads the next video frame. * **Grab()**: Grabs the next frame from the video device, but does not decode or return it. * **Retrieve(OutputArray image, int flag = 0)**: Decodes and returns the grabbed video frame. * **Release()**: Releases the video capture device. * **Get(VideoCaptureProperties propId)**: Gets a property of the video capture device. * **Set(VideoCaptureProperties propId, double value)**: Sets a property of the video capture device. ### Example ```csharp using var capture = new VideoCapture(0); // Webcam if (!capture.IsOpened()) return; Console.WriteLine($"FPS: {capture.Fps}"); Console.WriteLine($"Size: {capture.FrameWidth}×{capture.FrameHeight}"); using var frame = new Mat(); while (capture.Read(frame)) { Cv2.ImShow("Video", frame); if (Cv2.WaitKey(30) == 27) break; // ESC to exit } ``` ```