### Install Dependencies on RHEL/Fedora/CentOS 7 Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/Tutorial-for-Linux Commands to install necessary development tools, .NET SDK, PowerShell, and CMake on RHEL-based distributions. ```bash sudo yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm sudo yum update sudo yum groupinstall 'Development tools' sudo yum install -y dotnet-sdk-2.1 openblas-devel powershell cmake3 sudo ln -s /usr/bin/cmake3 /usr/bin/cmake sudo yum install https://github.com/PowerShell/PowerShell/releases/download/v7.2.2/powershell-lts-7.2.2-1.rh.x86_64.rpm ``` -------------------------------- ### Install Intel MKL on Debian/Ubuntu Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/Tutorial-for-Linux Configures the Intel APT repository and installs the Intel Math Kernel Library for performance optimization. ```bash apt-get update apt install -y wget apt-transport-https wget https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2019.PUB apt-key add GPG-PUB-KEY-INTEL-SW-PRODUCTS-2019.PUB sh -c 'echo deb https://apt.repos.intel.com/mkl all main > /etc/apt/sources.list.d/intel-mkl.list' apt-get update apt-get install -y intel-mkl-64bit-2019.0-045 ``` -------------------------------- ### Build and Run DlibDotNet SURF Example Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/Surf/README.md Commands to compile the project using the .NET CLI and execute the SURF feature detection on an input image file. Ensure all native dependencies are present in the output directory before execution. ```bash dotnet build -c Release cd dotnet run -c Release Lenna.bmp ``` -------------------------------- ### Install DlibDotNet Packages Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt Commands to install the DlibDotNet library and its variants (CUDA, MKL) using the .NET CLI or Package Manager Console. ```bash dotnet add package DlibDotNet PM> Install-Package DlibDotNet dotnet add package DlibDotNet.CUDA102 dotnet add package DlibDotNet.MKL ``` -------------------------------- ### Run DlibDotNet Project with .NET CLI Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/DnnMmodFindCars2/README.md This snippet demonstrates how to execute a .NET project using the 'dotnet run' command in Release configuration. It's typically used after building the project to start the application. ```bash cd dotnet run -c Release ``` -------------------------------- ### Build and Run DlibDotNet SVM Pegasos Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/SvmPegasos/README.md Commands to compile the project using the .NET CLI and execute the SVM Pegasos example. Ensure native DlibDotNet libraries are present in the output directory before execution. ```bash dotnet build -c Release dotnet run --configuration Release ``` -------------------------------- ### Install DlibDotNet using Package Manager Console Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/How-to-install This command installs the DlibDotNet NuGet package using the Package Manager Console in Visual Studio. This package is for CPU-only usage. ```powershell PM> Install-Package DlibDotNet ``` -------------------------------- ### Install DlibDotNet using .NET CLI Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/How-to-install This command adds the DlibDotNet NuGet package to your project using the .NET Command Line Interface. This package is suitable for CPU-only environments. ```bash > dotnet add package DlibDotNet ``` -------------------------------- ### Convert EmguCV Mat to DlibDotNet Matrix Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/How-to-convert-EmguCV.Mat-to? This example demonstrates how to read an image using EmguCV's CvInvoke.Imread and convert the resulting Mat object into a DlibDotNet.Matrix. ```APIDOC ## Convert EmguCV Mat to DlibDotNet Matrix ### Description Converts an EmguCV Mat object to a DlibDotNet.Matrix. ### Method N/A (Code Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```csharp using (var mat = CvInvoke.Imread("Lenna.png", ImreadModes.AnyColor)) { var array = new byte[mat.Width * mat.Height * mat.ElementSize]; mat.CopyTo(array); // TODO: support BGR image using (var image = new DlibDotNet.Matrix(array, mat.Height, mat.Width, mat.ElementSize)) { // something to do } } ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Run Face Detection (Multi Thread) Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/MultiThreadFaceDetectionCpp/README.md Executes the face detection program using multiple threads (specifically two in this example). This snippet illustrates the command and the initial output, showing the preparation for multi-threaded execution but not the final detection results, implying a potential issue. ```powershell git lfs pull pwsh .\Run.ps1 2 deserialize: mmod_human_face_detector.dat thread_num: 2 load_image: 2007_007763.jpg prepare thread wait all thread start thread_id: 0 start thread_id: 1 ``` -------------------------------- ### Hough Transform for Line Detection in C# Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt Demonstrates the use of the HoughTransform class in DlibDotNet to detect lines in an image. The example includes drawing a test line, computing the Hough transform, finding the strongest line, and visualizing the results. Dependencies include DlibDotNet and an image window. ```csharp using DlibDotNet; using var img = new Array2D(400, 400); using var ht = new HoughTransform(size: 300); using var win = new ImageWindow(); // Draw a test line var center = img.Rect.Center; Dlib.AssignAllPixels(img, (byte)0); Dlib.DrawLine(img, new Point(50, 100), new Point(350, 300), (byte)255); // Compute Hough transform using var houghImg = new Array2D(); var offset = new Point(50, 50); var houghRect = Dlib.GetRect(ht); var searchBox = Rectangle.Translate(houghRect, offset); ht.Operator(img, searchBox, houghImg); // Find strongest line (peak in Hough space) using var mat = Dlib.Mat(houghImg); var peak = Dlib.MaxPoint(mat); // Get line coordinates from Hough space point var line = ht.GetLine(peak); var p1 = line.Item1 + offset; var p2 = line.Item2 + offset; Console.WriteLine($"Detected line: ({p1.X}, {p1.Y}) to ({p2.X}, {p2.Y})"); // Visualize using var colorImg = new Array2D(); Dlib.AssignImage(img, colorImg); Dlib.DrawLine(colorImg, p1, p2, new RgbPixel { Red = 255 }); win.SetImage(colorImg); win.AddOverlay(searchBox, new RgbPixel { Green = 255 }); // Search region in green // Display Hough space visualization using var win2 = new ImageWindow(); using var jetImage = Dlib.Jet(houghImg); win2.SetImage(jetImage); ``` -------------------------------- ### Displaying Images and Overlays with ImageWindow Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt Demonstrates how to initialize an ImageWindow, load an image, perform face detection, and render overlays such as rectangles, dots, and lines. It highlights the importance of manual resource management for overlay objects. ```csharp using DlibDotNet; if (!Dlib.IsSupportGui) { Console.WriteLine("GUI not supported on this platform"); return; } using var win = new ImageWindow(); using var img = Dlib.LoadImage("photo.jpg"); win.Title = "Face Detection Results"; win.SetImage(img); using var detector = Dlib.GetFrontalFaceDetector(); var faces = detector.Operator(img); win.AddOverlay(faces, new RgbPixel { Red = 255, Green = 0, Blue = 0 }); var dots = new List(); foreach (var face in faces) { dots.Add(new OverlayDot(face.Center, new RgbPixel { Green = 255 })); } win.AddOverlay(dots); var lines = new List(); lines.Add(new OverlayLine(new Point(0, 0), new Point(100, 100), new RgbPixel { Blue = 255 })); win.AddOverlay(lines); Console.WriteLine("Press any key to close..."); Console.ReadKey(); win.ClearOverlay(); foreach (var dot in dots) dot.Dispose(); foreach (var line in lines) line.Dispose(); ``` -------------------------------- ### GUI Visualization with ImageWindow Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt Demonstrates how to initialize a GUI window, load an image, perform face detection, and render overlays such as rectangles, dots, and lines. ```APIDOC ## GUI Visualization ### Description This functionality allows developers to display images and visual overlays (like detection results) in a native window. It requires GUI support to be enabled in the build. ### Method N/A (Library Class Usage) ### Endpoint DlibDotNet.ImageWindow ### Parameters #### Request Body - **win** (ImageWindow) - Required - The window instance to display content. - **img** (Array2D) - Required - The image data to be rendered. - **overlays** (List) - Optional - Collection of OverlayDot, OverlayLine, or Rectangle objects. ### Request Example ```csharp using var win = new ImageWindow(); win.SetImage(img); win.AddOverlay(faces, new RgbPixel { Red = 255 }); ``` ### Response #### Success Response (Void) - **Action** - Renders the image and overlays to the screen. ``` -------------------------------- ### Initialize DlibDotNet Repository Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/Tutorial-for-Linux Clones the DlibDotNet repository and runs the initialization script to prepare the environment. ```bash git clone https://github.com/takuya-takeuchi/DlibDotNet cd DlibDotNet ./Initialize.sh ``` -------------------------------- ### Convert EmguCV Mat to DlibDotNet Array2D Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/How-to-convert-EmguCV.Mat-to? This example shows how to convert an EmguCV Mat object into a DlibDotNet.Array2D using Dlib.LoadImageData. ```APIDOC ## Convert EmguCV Mat to DlibDotNet Array2D ### Description Converts an EmguCV Mat object to a DlibDotNet.Array2D. ### Method N/A (Code Example) ### Endpoint N/A ### Parameters N/A ### Request Example ```csharp using (var mat = CvInvoke.Imread("Lenna.png", ImreadModes.AnyColor)) { var array = new byte[mat.Width * mat.Height * mat.ElementSize]; mat.CopyTo(array); using (var image = Dlib.LoadImageData(array, (uint)mat.Height, (uint)mat.Width, (uint)(mat.Width * mat.ElementSize))) { // something to do } } ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Clone DlibDotNet Repository and Initialize Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/Tutorial-for-Windows This snippet shows the commands to clone the DlibDotNet repository from GitHub and run the initialization script. ```bash git clone https://github.com/takuya-takeuchi/DlibDotNet cd DlibDotNet Initialize.bat ``` -------------------------------- ### Build Random Cropper Project with .NET CLI Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/RandomCropper/README.md This snippet demonstrates how to build the Random Cropper project using the .NET CLI. It requires changing the directory to the project's root and executing the 'dotnet build' command. Ensure that DlibDotNet.dll, DlibDotNetNative.dll, and DlibDotNetNativeDnn.dll are copied to the output directory. ```bash cd dotnet build -c Release ``` -------------------------------- ### Get Libpng Copyright Information (C) Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/Licenses/libpng.txt This C code snippet demonstrates how to retrieve the copyright information for the libpng library using the `png_get_copyright` function. This is typically used in 'about' boxes or for informational purposes within an application that uses libpng. ```c printf("%s",png_get_copyright(NULL)); ``` -------------------------------- ### Querying System and CUDA Capabilities Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt Shows how to retrieve library versions and check for hardware acceleration support. It also demonstrates how to enumerate available CUDA devices when GPU support is enabled. ```csharp using DlibDotNet; Console.WriteLine($"Native DlibDotNet version: {Dlib.GetNativeVersion()}"); Console.WriteLine($"Native DNN version: {Dlib.GetNativeDnnVersion()}"); Console.WriteLine($"GUI supported: {Dlib.IsSupportGui}"); Console.WriteLine($"CUDA supported: {Dlib.IsSupportCuda}"); Console.WriteLine($"DNN GUI supported: {Dlib.IsDnnSupportGui}"); Console.WriteLine($"DNN CUDA supported: {Dlib.IsDnnSupportCuda}"); if (Dlib.IsDnnSupportCuda) { int deviceCount = DlibDotNet.Dnn.Cuda.GetDeviceCount(); Console.WriteLine($"CUDA devices available: {deviceCount}"); for (int i = 0; i < deviceCount; i++) { string deviceName = DlibDotNet.Dnn.Cuda.GetDeviceName(i); Console.WriteLine($" Device {i}: {deviceName}"); } } Dlib.Encoding = System.Text.Encoding.UTF8; ``` -------------------------------- ### Convert OpenCVSharp Mat to DlibDotNet Array2D Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/How-to-convert-OpenCVSharp.Mat-to? This example illustrates converting an OpenCVSharp Mat to a DlibDotNet Array2D. It reads an image, copies its data into a byte array, and then uses Dlib.LoadImageData to create the DlibDotNet Array2D object, specifying dimensions and stride. ```csharp using (var mat = Cv2.ImRead("Lenna.png", ImreadModes.AnyColor)) { var array = new byte[mat.Width * mat.Height * mat.ElemSize()]; Marshal.Copy(mat.Data, array, 0, array.Length); using (var image = Dlib.LoadImageData(array, (uint)mat.Height, (uint)mat.Width, (uint)(mat.Width * mat.ElemSize()))) { // something to do } } ``` -------------------------------- ### Run Random Cropper Application Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/RandomCropper/README.md This snippet shows how to execute the Random Cropper application after building it. It involves navigating to the project directory and running the application using 'dotnet run', specifying the release configuration and providing the path to the training data XML file. The application will then prompt the user to hit enter to view random crops. ```bash cd dotnet run --configuration Release ``` -------------------------------- ### Build and Run DlibDotNet Video Tracking Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/VideoTracking/README.md Commands to compile the project using the .NET CLI and execute the video tracking application with the required data path. Ensure all native DLL dependencies are present in the output directory before execution. ```bash dotnet build -c Release cd dotnet run -c Release ``` -------------------------------- ### Build and Run Hough Transform Project Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/HoughTransform/README.md Commands to compile the .NET project using the CLI and execute the resulting binary. Ensure all native DlibDotNet DLLs are present in the output directory before running. ```bash dotnet build -c Release cd dotnet run -c Release ``` -------------------------------- ### Define Compiler Flags and Initialize CPACK Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/src/DlibDotNet.Native/CMakeLists.txt This CMake code defines a list of common compiler flags for C and C++ across different build types (Debug, Release). It also sets up project name and version variables for CPACK, a CPack module used for creating installers. ```cmake set(CompilerFlags CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE ) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack) ``` -------------------------------- ### Execute DnnInstanceSegmentationTrain via .NET CLI Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/Template/README.md This command runs the training application for instance segmentation. It requires navigating to the project directory and providing the path to the PASCAL VOC2012 dataset along with detection and segmentation batch sizes as arguments. ```bash cd dotnet run --configuration Release -- ``` -------------------------------- ### Support Vector Machine (SVM) Classification Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt Demonstrates Support Vector Machine (SVM) classification using DlibDotNet with a Radial Basis Function (RBF) kernel. This example generates synthetic data with a circular decision boundary, normalizes features, trains an SVM model using cross-validation to find optimal hyperparameters, and then makes predictions on new data points. It also shows how to save and load the trained model. ```csharp using DlibDotNet; using SampleType = DlibDotNet.Matrix; // Prepare training data var samples = new List(); var labels = new List(); // Generate circular decision boundary data for (int r = -20; r <= 20; r++) { for (int c = -20; c <= 20; c++) { var sample = new SampleType(); sample.SetSize(2, 1); // 2D feature vector sample[0] = r; sample[1] = c; samples.Add(sample); // Label: +1 if within radius 10, -1 otherwise double distance = Math.Sqrt(r * r + c * c); labels.Add(distance <= 10 ? +1 : -1); } } // Normalize features using var normalizer = new VectorNormalizer(); normalizer.Train(samples); for (int i = 0; i < samples.Count; i++) { var normalized = normalizer.Operator(samples[i]); samples[i].Dispose(); samples[i] = normalized; } // Randomize sample order for cross-validation Dlib.RandomizeSamples(samples, labels); // Create SVM trainer with RBF kernel using var trainer = new SvmNuTrainer>>(); // Find best hyperparameters via cross-validation double maxNu = Dlib.MaximumNu(labels); double bestGamma = 0.15625, bestNu = 0.15625; using var kernel = new RadialBasisKernel>(gamma: bestGamma, 0, 0); trainer.Kernel = kernel; trainer.Nu = bestNu; // Cross-validate using var cvResult = Dlib.CrossValidateTrainer(trainer, samples, labels, folds: 3); Console.WriteLine($"Cross-validation accuracy: {cvResult}"); // Train final model var learnedFunction = new NormalizedFunction>>>(); learnedFunction.Normalizer = normalizer; using var function = trainer.Train(samples, labels); learnedFunction.Function = function; // Make predictions using var testSample = new SampleType(); testSample.SetSize(2, 1); testSample[0] = 3.123; testSample[1] = 2; Console.WriteLine($"Prediction for (3.123, 2): {learnedFunction.Operator(testSample)}"); // Should be > 0 testSample[0] = 13.123; testSample[1] = 9.3545; Console.WriteLine($"Prediction for (13.123, 9.35): {learnedFunction.Operator(testSample)}"); // Should be < 0 // Save and load trained model NormalizedFunction>>> .Serialize("svm_model.dat", learnedFunction); var loadedFunction = NormalizedFunction>>> .Deserialize("svm_model.dat"); ``` -------------------------------- ### Build and Sign UWP Application with MSBuild Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/test/DlibDotNet.UWP.Tests/README.md Builds and packages a Universal Windows Platform (UWP) application using MSBuild. This command restores dependencies, rebuilds the project, and creates an AppX bundle, signing it with a specified certificate thumbprint and PFX file. ```bat > cd DlibDotNet > set rootDlibDotNet=%cd% > cd test\DlibDotNet.UWP.Tests > set OutputDir=Package > set msbuild="C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\amd64\MSBuild.exe" > if exist Package rmdir %OutputDir% /s /q > %msbuild% DlibDotNet.UWP.Tests.csproj ^ /t:restore ^ /t:Rebuild ^ /p:RestoreAdditionalProjectSources=%rootDlibDotNet%\nuget ^ /p:RestoreNoCache=true ^ /p:Configuration=Release ^ /p:Platform="x64" ^ /p:OutDir=%OutputDir% ^ /p:AppxBundle=Always ^ /p:AppxBundlePlatforms="x64" ^ /p:AppxPackageSigningEnabled=true ^ /p:PackageCertificateThumbprint=f57d76083b91b1bddf9bfbc5fdb14bd352c73fec ^ /p:PackageCertificateKeyFile="DlibDotNet.pfx" ``` -------------------------------- ### Perform Face Recognition with DNN in C# Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt This C# code snippet illustrates how to perform face recognition using DlibDotNet's deep neural network (DNN) capabilities, specifically the LossMetric network. It involves detecting faces, extracting aligned face chips, generating 128D face descriptors, and comparing these descriptors to determine if faces belong to the same person. It also includes an example of face clustering using the Chinese Whispers algorithm. ```csharp using DlibDotNet; using DlibDotNet.Dnn; // Load required models using var detector = Dlib.GetFrontalFaceDetector(); using var sp = ShapePredictor.Deserialize("shape_predictor_5_face_landmarks.dat"); using var net = LossMetric.Deserialize("dlib_face_recognition_resnet_model_v1.dat"); using var img = Dlib.LoadImageAsMatrix("people.jpg"); // Detect and align faces var faces = new List>(); foreach (var faceRect in detector.Operator(img)) { var shape = sp.Detect(img, faceRect); // Extract aligned face chip (150x150 normalized) var chipDetails = Dlib.GetFaceChipDetails(shape, size: 150, padding: 0.25); var faceChip = Dlib.ExtractImageChip(img, chipDetails); faces.Add(faceChip); chipDetails.Dispose(); } if (faces.Count == 0) { Console.WriteLine("No faces found!"); return; } // Generate 128D face descriptors for each face var faceDescriptors = net.Operator(faces); // Compare faces - distance < 0.6 means same person for (int i = 0; i < faceDescriptors.Count; i++) { for (int j = i + 1; j < faceDescriptors.Count; j++) { var diff = faceDescriptors[i] - faceDescriptors[j]; double distance = Dlib.Length(diff); bool samePerson = distance < 0.6; Console.WriteLine($"Face {i} vs Face {j}: distance={distance:F4}, same person: {samePerson}"); } } // Face clustering using Chinese Whispers algorithm var edges = new List(); for (uint i = 0; i < faceDescriptors.Count; i++) { for (uint j = i; j < faceDescriptors.Count; j++) { var diff = faceDescriptors[i] - faceDescriptors[j]; if (Dlib.Length(diff) < 0.6) edges.Add(new SamplePair(i, j)); } } Dlib.ChineseWhispers(edges, iterations: 100, out var numClusters, out var labels); Console.WriteLine($"Number of distinct people: {numClusters}"); // Clean up foreach (var face in faces) face.Dispose(); foreach (var desc in faceDescriptors) desc.Dispose(); foreach (var edge in edges) edge.Dispose(); ``` -------------------------------- ### Execute DnnInception Project with .NET CLI Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/DnnInception/README.md This snippet shows the command to navigate to the project directory and run the DnnInception application in release mode. It assumes the DnnInception directory is accessible. ```bash cd dotnet run -c Release . ``` -------------------------------- ### CMake: Project and OS Information Configuration Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/src/DlibDotNet.Native.Dnn/CMakeLists.txt Initializes the CMake project, sets policies, and prints system information such as OS name, processor, C/C++ compilers, and directory paths. This helps in diagnosing build environment issues. ```cmake cmake_minimum_required(VERSION 3.0.0) cmake_policy(SET CMP0053 NEW) cmake_policy(SET CMP0054 NEW) set(PROJ_NAME DlibDotNetNativeDnn) # It means that CMakeLists.txt version rather than library version project(${PROJ_NAME} VERSION 1.0.0) # OS info message("-------------------------------------------------------") message("-- CMAKE_SYSTEM_INFO_FILE: ${CMAKE_SYSTEM_INFO_FILE}") message("-- CMAKE_SYSTEM_NAME: ${CMAKE_SYSTEM_NAME}") message("-- CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}") message("-- CMAKE_SYSTEM: ${CMAKE_SYSTEM}") message("-- CMAKE_C_COMPILER: ${CMAKE_C_COMPILER}") message("-- CMAKE_CXX_COMPILER: ${CMAKE_CXX_COMPILER}") string (REGEX MATCH "\\.el[1-9]" os_version_suffix ${CMAKE_SYSTEM}) message("-- os_version_suffix: ${os_version_suffix}") message("-- Project: ${CMAKE_CURRENT_SOURCE_DIR}") message("-- Binaries: ${CMAKE_CURRENT_BINARY_DIR}") message("-------------------------------------------------------") # Version info set(VERSION_MAJOR 19) set(VERSION_MINOR 21) set(VERSION_PATCH 0) set(VERSION_DATE 20220724) ``` -------------------------------- ### Build DlibDotNet Project Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/DnnMmodFaceDetection/README.md This command builds the DlibDotNet project in Release configuration. Ensure you are in the project directory. Dependencies include the .NET SDK. ```bash dotnet build -c Release ``` -------------------------------- ### Run Windows App Certification Kit Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/test/DlibDotNet.UWP.Tests/README.md Executes the Windows App Certification Kit (appcert.exe) to test a packaged UWP application. This command takes the path to the AppX package and an output path for the report as arguments. ```bat > cd DlibDotNet.UWP.Tests > set rootUWPTest=%cd% > set appcert="C:\Program Files (x86)\Windows Kits\10\App Certification Kit\appcert.exe" > set appx="%rootUWPTest%\Package\DlibDotNet.UWP.Tests\DlibDotNet.UWP.Tests_1.0.0.0_x64.appx" > set report="%rootUWPTest%\Package\DlibDotNet.UWP.Tests\AppCertReport.xml" > if exist %report% del %report% > %appcert% test -appxpackagepath %appx% -reportoutputpath %report% ``` -------------------------------- ### Perform Face Detection with FrontalFaceDetector Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt Shows how to initialize the frontal face detector, process images (including upscaling), and retrieve bounding boxes or detailed detection results with confidence scores. ```csharp using DlibDotNet; using var detector = Dlib.GetFrontalFaceDetector(); using var img = Dlib.LoadImage("group_photo.jpg"); Dlib.PyramidUp(img); Rectangle[] faces = detector.Operator(img); foreach (var faceRect in faces) { Console.WriteLine($"Face at: {faceRect.Left}, {faceRect.Top}"); } if (Dlib.IsSupportGui) { using var win = new ImageWindow(); win.SetImage(img); win.AddOverlay(faces, new RgbPixel { Red = 255 }); } ``` -------------------------------- ### Build DlibDotNet.Native using PowerShell Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/Tutorial-for-Windows This command builds the native DlibDotNet library. It accepts parameters for build configuration (Release/Debug), target (cpu/cuda/mkl), architecture (32/64), platform (desktop/uwp), and optional CUDA version or MKL path. ```powershell pwsh Build.ps1 <32/64> ``` -------------------------------- ### Build and Run DlibDotNet Face Detection Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/FaceDetection/README.md Commands to compile the C# project using the .NET CLI and execute the face detection application on a specific image file. ```bash dotnet build -c Release dotnet run -c Release ``` -------------------------------- ### Run FHog Object Detector with .NET CLI Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/FHogObjectDetector/README.md This snippet demonstrates how to execute the FHog Object Detector application using the .NET CLI. It requires the project to be built and the demo data to be downloaded. ```bash cd dotnet run -c Release ``` -------------------------------- ### Image Processing and Transforms in C# Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt Illustrates various image processing operations using DlibDotNet, including loading, resizing (pyramid up/down), flipping, histogram equalization, and extracting face chips. It also shows how to draw on images. Dependencies include DlibDotNet and image files. ```csharp using DlibDotNet; using var img = Dlib.LoadImage("photo.jpg"); // Resize using pyramid operations Dlib.PyramidUp(img); // Double image size Dlib.PyramidDown(img); // Halve image size // Flip operations Dlib.FlipImageLeftRight(img); using var flippedVertical = new Array2D(); Dlib.FlipImageUpDown(img, flippedVertical); // Histogram equalization using var grayImg = Dlib.LoadImage("photo.jpg"); Dlib.EqualizeHistogram(grayImg); // Extract face chips (aligned, normalized face regions) using var detector = Dlib.GetFrontalFaceDetector(); using var sp = ShapePredictor.Deserialize("shape_predictor_68_face_landmarks.dat"); var faces = detector.Operator(img); var shapes = new List(); foreach (var face in faces) { var shape = sp.Detect(img, face); shapes.Add(shape); } // Get aligned face chips var chipLocations = Dlib.GetFaceChipDetails(shapes, size: 150, padding: 0.25); using var faceChips = Dlib.ExtractImageChips(img, chipLocations); // Create tiled image of all faces using var tiled = Dlib.TileImages(faceChips); Dlib.SaveJpeg(tiled, "all_faces.jpg"); // Drawing on images using var canvas = new Array2D(400, 400); Dlib.AssignAllPixels(canvas, new RgbPixel { Blue = 255 }); // Blue background // Draw line Dlib.DrawLine(canvas, new Point(10, 10), new Point(390, 390), new RgbPixel { Red = 255 }); // Red diagonal // Clean up foreach (var shape in shapes) shape.Dispose(); foreach (var chip in chipLocations) chip.Dispose(); ``` -------------------------------- ### Build and Run Logger Custom Output Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/LoggerCustomOutput/README.md Commands to build the project using the .NET CLI and execute the resulting binary. Ensure all native DlibDotNet DLLs are present in the output directory before execution. ```bash dotnet build -c Release cd dotnet run --configuration Release ``` -------------------------------- ### Build and Run DlibDotNet Instance Segmentation Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/DnnInstanceSegmentation/README.md Commands to compile the project using the .NET CLI and execute the segmentation process on a directory of images. Requires specific Dlib native DLLs to be present in the output directory. ```bash dotnet build -c Release dotnet run --configuration Release -- D:\VOC2012\JPEGImages ``` -------------------------------- ### Build Scripts for Face Detection Project Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/examples/MultiThreadFaceDetectionCpp/README.md Provides PowerShell scripts to build the necessary components for the face detection project, including Boost and the main application. These scripts are essential for setting up the environment before running the detection. ```powershell pwsh BuildBoost.ps1 pwsh Build.ps1 ``` -------------------------------- ### Build DlibDotNet Managed Library Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/Tutorial-for-Linux Compiles the managed .NET library using the .NET CLI. ```bash dotnet build -c ``` -------------------------------- ### Training Custom MMOD Object Detectors (C#) Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt This snippet outlines the process of training a custom MMOD object detector using Dlib.NET. It involves loading annotated image datasets, configuring MMOD options, setting up the trainer with augmentation techniques, and evaluating the trained model. Dependencies include DlibDotNet and image annotation tools like imglab. ```csharp using DlibDotNet; using DlibDotNet.Dnn; // Load training and testing datasets from XML annotations // Use imglab tool to create annotations: https://github.com/davisking/dlib/tree/master/tools/imglab Dlib.LoadImageDataset("faces/training.xml", out IList> imagesTrain, out IList> boxesTrain); Dlib.LoadImageDataset("faces/testing.xml", out IList> imagesTest, out IList> boxesTest); Console.WriteLine($"Training images: {imagesTrain.Count}"); Console.WriteLine($"Testing images: {imagesTest.Count}"); // Configure MMOD options (40x40 minimum object size) using var options = new MModOptions(boxesTrain, targetSize: 40, minTargetSize: 40); Console.WriteLine($"Detector windows: {options.DetectorWindows.Count()}"); Console.WriteLine($"NMS IOU threshold: {options.OverlapsNms.GetIouThresh()}"); // Create network and trainer using var net = new LossMmod(options, numFilters: 2); using var trainer = new DnnTrainer(net); trainer.SetLearningRate(0.1); trainer.BeVerbose(); trainer.SetSynchronizationFile("mmod_sync", intervalSeconds: 300); trainer.SetIterationsWithoutProgressThreshold(300); // Training with random cropping and color augmentation using var cropper = new RandomCropper(); using var chipDims = new ChipDims(200, 200); cropper.ChipDims = chipDims; cropper.SetMinObjectSize(40, 40); using var rnd = new Rand(); while (trainer.GetLearningRate() >= 1e-4) { // Generate mini-batch with random crops cropper.Operator(batchSize: 150, imagesTrain, boxesTrain, out var miniBatchSamples, out var miniBatchLabels); // Apply color augmentation foreach (var img in miniBatchSamples) Dlib.DisturbColors(img, rnd); // Train one step LossMmod.TrainOneStep(trainer, miniBatchSamples, miniBatchLabels); } trainer.GetNet(); // Wait for training to complete Console.WriteLine("Training complete!"); // Save the trained network net.Clean(); LossMmod.Serialize(net, "my_detector.dat"); // Evaluate on test set using var trainResults = Dlib.TestObjectDetectionFunction(net, imagesTrain, boxesTrain); using var testResults = Dlib.TestObjectDetectionFunction(net, imagesTest, boxesTest); Console.WriteLine($"Training results: {trainResults}"); Console.WriteLine($"Testing results: {testResults}"); ``` -------------------------------- ### Build DlibDotNet Native Components Source: https://github.com/takuya-takeuchi/dlibdotnet/wiki/Tutorial-for-Linux Uses PowerShell to build the native C++ components of DlibDotNet, allowing configuration of build type, hardware acceleration, and architecture. ```powershell pwsh Build.ps1 <32/64> ``` ```powershell pwsh Build.ps1 <32/64> ``` -------------------------------- ### Object Detection with Pre-trained MMOD Face Detector (C#) Source: https://context7.com/takuya-takeuchi/dlibdotnet/llms.txt This snippet demonstrates how to load a pre-trained MMOD face detector model using Dlib.NET and perform object detection on an image. It outputs the bounding boxes, confidence scores, and labels for detected faces. Dependencies include DlibDotNet and a downloaded MMOD model file. ```csharp using DlibDotNet; using DlibDotNet.Dnn; // Load a pre-trained MMOD face detector // Download from: http://dlib.net/files/mmod_human_face_detector.dat.bz2 using var net = LossMmod.Deserialize("mmod_human_face_detector.dat"); using var img = Dlib.LoadImageAsMatrix("faces.jpg"); // Optionally upscale for better small face detection Dlib.PyramidUp(img); // Run detection - returns list of MModRect detections var detections = net.Operator(img); foreach (var detection in detections[0]) { Console.WriteLine($"Face detected at: {detection.Rect}"); Console.WriteLine($"Confidence: {detection.DetectionConfidence}"); Console.WriteLine($"Label: {detection.Label}"); } // Display results using var win = new ImageWindow(img); foreach (var det in detections[0]) win.AddOverlay(det); // Clean up detections foreach (var detList in detections) foreach (var det in detList) det.Dispose(); ``` -------------------------------- ### Build Library with CUDA Support (CMake) Source: https://github.com/takuya-takeuchi/dlibdotnet/blob/master/src/DlibDotNet.Native.Dnn/CMakeLists.txt This snippet handles the build process when CUDA support is enabled. It configures a CUDA resource file, sets the CUDA runtime library to be non-static, includes the CUDA SDK path, and adds the library with specified sources and headers. ```cmake if (${DLIB_USE_CUDA}) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/version-cuda.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version-cuda.rc @ONLY) # disable cuda static link set(CUDA_USE_STATIC_CUDA_RUNTIME OFF) # include CUDA Runtime Library if (MSVC OR MSYS OR MINGW) include_directories("$ENV{CUDA_PATH}/include") elseif(APPLE) include_directories("$ENV{CUDA_PATH}/include") elseif(UNIX AND NOT APPLE) include_directories("$ENV{CUDA_PATH}/include") else() message(FATAL_ERROR "Failed to link CUDA Runtime Library") endif() add_library(${PROJ_NAME} SHARED ${HEADERS} ${SOURCES} ${DLIBDOTNET_SHARED_HEADER1} ${DLIBDOTNET_SHARED_HEADER2} ${CMAKE_CURRENT_BINARY_DIR}/version-cuda.rc) else() configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY) if ("${CMAKE_SYSTEM_NAME}" STREQUAL "iOS") add_library(${PROJ_NAME} ${HEADERS} ${SOURCES} ${DLIBDOTNET_SHARED_HEADER1} ${DLIBDOTNET_SHARED_HEADER2} ${CMAKE_CURRENT_BINARY_DIR}/version.rc) else() add_library(${PROJ_NAME} SHARED ${HEADERS} ${SOURCES} ${DLIBDOTNET_SHARED_HEADER1} ${DLIBDOTNET_SHARED_HEADER2} ${CMAKE_CURRENT_BINARY_DIR}/version.rc) endif() endif() target_link_libraries(${PROJ_NAME} dlib::dlib ) ```