### Darknet CLI Examples Source: https://context7.com/hank-ai/darknet/llms.txt Provides examples of how to use the installed `darknet` executable and bundled example applications from the command line for various tasks. ```APIDOC ## CLI — Running Darknet from the command line The installed `darknet` executable and the bundled example apps (`darknet_01_inference_images`, `darknet_03_display_videos`, etc.) provide a ready-to-use CLI for common tasks without writing any code. ```bash # Check version darknet version # Run inference on images and print results + save annotated copies darknet_01_inference_images animals.cfg animals.names animals_best.weights *.jpg # Output per image: # -> using Darknet to predict .......... 2.034 ms [3 objects] # prediction results: 3 # -> 1/3: #0 prob=0.999 x=120 y=80 w=145 h=200 entries=1 # Display annotated images in a GUI window (with optional heatmaps) darknet_02_display_annotated_images --heatmaps animals dog.jpg # Play an annotated video at original frame rate darknet_03_display_videos LegoGears DSCN1582A.MOV # Process a video to disk as fast as possible using multi-threading darknet_05_process_videos_multithreaded LegoGears DSCN1582A.MOV # -> processed frame rate ..... 715.5 FPS # Export predictions to JSON darknet_06_images_to_json animals *.jpg # creates output.json: { "file": [{ "filename": "dog.jpg", "count": 3, "predictions": [...] }] } # Auto-generate YOLO annotation .txt files from an existing network darknet_11_images_to_yolo animals *.jpg # Calculate mAP accuracy darknet detector map driving.data driving.cfg driving_best.weights # Export network to ONNX format (experimental) darknet_onnx_export animals.cfg # Train a new network darknet detector -map -dont_show train animals.data animals.cfg # Training with 4 GPUs darknet detector -gpus 0,1,2,3 -map -dont_show train animals.data animals.cfg # Redirect all Darknet log output to a file darknet -log /tmp/darknet.log detector map animals.data animals.cfg animals_best.weights ``` ``` -------------------------------- ### Setup Dataset and Train Network Source: https://github.com/hank-ai/darknet/blob/master/colab/03_Training_a_new_network.ipynb Downloads and prepares the LegoGears-V2 dataset. It resizes images using ImageMagick to match network dimensions, creates training and validation text files, and modifies configuration files for batch size and paths. Finally, it starts the training process and logs the output. ```bash # Make sure we can run the darknet executable !darknet --version # Get our dataset onto the colab instance %mkdir -p ~/nn %cd ~/nn !wget --no-clobber https://www.ccoderun.ca/programming/2024-05-01_LegoGears/legogears_2_dataset.zip %rm -rf LegoGears_v2 %rm -rf LegoGears !unzip legogears_2_dataset.zip %mv LegoGears_v2 LegoGears %cd LegoGears # Had we used DarkMark, things would be very simple and we could train at this # point. But since we didn't we'll use image magick to modify our images to # match the network dimensions. This will make sure training takes much less # time. See the FAQ for details: # https://www.ccoderun.ca/programming/yolo_faq/#time_to_train # # WARNING: Make sure you understand what this is doing before blindly copying # this code. You cannot re-use this "as-is" with any dataset, the numbers used # must match the .cfg file and is specific to each dataset. See this question # in the FAQ which explains the math that was used: # https://www.ccoderun.ca/programming/yolo_faq/#optimal_network_size !sudo apt-get install imagemagick %mkdir training_images %cp set_0*/*.jpg training_images/ %cp set_0*/*.txt training_images/ !mogrify -verbose -strip -resize 224x160! -quality 75 training_images/*.jpg # this dataset doesn't have a train.txt nor valid.txt file, # so we must manually create them !find $(pwd)/training_images -name \*.jpg > LegoGears_train.txt %cp LegoGears_train.txt LegoGears_valid.txt # the paths in the .data file must be fixed up to point to this colab instance !sed -i "s+/home/stephane+${HOME}+g" LegoGears.data # the batch size in the .cfg file should be set to 64 while training !sed -i "s+batch=1+batch=64+g" LegoGears.cfg # start training! !darknet detector -map -dont_show train LegoGears.data LegoGears.cfg | tee output.log ``` ```python import cv2 as cv2 from matplotlib import pyplot as plt img = cv2.imread('chart.png') plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) ``` -------------------------------- ### Install Dependencies with vcpkg Source: https://github.com/hank-ai/darknet/blob/master/README.md Clones the vcpkg repository, bootstraps it, and then installs OpenCV with common modules and protobuf for Windows x64. ```bat cd c:\ mkdir c:\src cd c:\src git clone https://github.com/microsoft/vcpkg cd vcpkg bootstrap-vcpkg.bat .\vcpkg.exe integrate install .\vcpkg.exe integrate powershell .\vcpkg.exe install opencv[contrib,dnn,freetype,jpeg,openmp,png,webp,world]:x64-windows protobuf:x64-windows ``` -------------------------------- ### Install Darknet/YOLO and Dependencies Source: https://github.com/hank-ai/darknet/blob/master/colab/03_Training_a_new_network.ipynb Installs necessary build tools, OpenCV, and CMake. Clones the Darknet/YOLO repository, builds it using CMake, and installs it as a .deb package. Finally, it verifies the installation by checking the version. ```bash !sudo apt-get install build-essential git libopencv-dev cmake # Make sure we have access to CUDA !nvidia-smi !nvcc --version # Get the Darknet/YOLO source code %mkdir -p ~/src %cd ~/src %rm -rf ~/src/darknet !git clone https://codeberg.org/CCodeRun/darknet # Build Darknet/YOLO %mkdir -p ~/src/darknet/build %cd ~/src/darknet/build !cmake -DCMAKE_BUILD_TYPE=Release .. %cd ~/src/darknet/build !make -j $(nproc) package # Install the .deb package !sudo dpkg -i darknet*.deb # Check to see that we can run Darknet/YOLO !darknet --version ``` -------------------------------- ### Install Build Tools and Libraries Source: https://github.com/hank-ai/darknet/blob/master/colab/01_Building_the_Hank_ai_Darknet_YOLO_Framework.ipynb Installs essential build tools like `build-essential`, `git`, `libopencv-dev`, and `cmake`. It also checks for installed NVIDIA libraries. ```python # First part will install the tools we'll use to build. !sudo apt-get install build-essential git libopencv-dev cmake # Which NVIDIA libraries are currently installed? !dpkg -l | egrep "libcuda|libcudnn" # Last updated on 2025-08-15; you may need to update the library version numbers # You should have libcudnn and libcuda installed. If not, then you'll need to # check what is available, and install it with the following lines. #!apt-cache search libcudnn #!apt-cache search cuda-libraries #!sudo apt-get install libcudnn9-dev-XYZ cuda-libraries-dev-XYZ ``` -------------------------------- ### Darknet Annotation File Example Source: https://github.com/hank-ai/darknet/blob/master/README.md Example content for a .names file listing the classes for object detection. Each class must be on a new line. ```txt dog cat bird horse ``` -------------------------------- ### Darknet Data Configuration File Example Source: https://github.com/hank-ai/darknet/blob/master/README.md Example content for a .data file specifying paths to training/validation data, class names, and backup directory. ```txt classes = 4 train = /home/username/nn/animals/animals_train.txt valid = /home/username/nn/animals/animals_valid.txt names = /home/username/nn/animals/animals.names backup = /home/username/nn/animals ``` -------------------------------- ### Run NSIS Installer Source: https://github.com/hank-ai/darknet/blob/master/README.md Launches the NSIS installer package to complete the Darknet installation, which includes the CLI applications and necessary DLLs. ```bat darknet--win64.exe ``` -------------------------------- ### Install OpenBLAS for CPU-Only Builds Source: https://github.com/hank-ai/darknet/blob/master/README.md Install OpenBLAS libraries to enhance performance for CPU-only Darknet builds. These are only used when a GPU is not present. ```sh sudo apt-get install libopenblas64-0 libopenblas64-0-openmp libopenblas64-openmp-dev ``` -------------------------------- ### Set Installation Prefix Source: https://github.com/hank-ai/darknet/blob/master/README_CMake_flags.md Force Darknet installation to a custom path by setting CPack destination directory and install prefix. ```bash cmake -DCPACK_SET_DESTDIR=ON -DCMAKE_INSTALL_PREFIX=/usr/local/ ... ``` -------------------------------- ### Build Darknet from Source Source: https://github.com/hank-ai/darknet/blob/master/colab/02_Building_Darknet_and_DarkHelp_to_use_the_Python_interface.ipynb Installs Darknet by cloning the repository, configuring with CMake, compiling, and installing the package. Ensure your notebook is set to a T4 GPU for optimal performance. ```bash # make sure the notebook is set to T4 GPU (edit->settings) !sudo apt-get install build-essential git libopencv-dev cmake %mkdir -p ~/src %cd ~/src %rm -rf ~/src/darknet !git clone https://codeberg.org/CCodeRun/darknet %mkdir ~/src/darknet/build %cd ~/src/darknet/build !cmake -DCMAKE_BUILD_TYPE=Release .. !make -j $(nproc) package !sudo dpkg -i darknet*.deb %cd ~ !darknet version ``` -------------------------------- ### Install Protocol Buffer Compiler Source: https://github.com/hank-ai/darknet/blob/master/src-onnx/onnx.proto3.txt Installs the necessary Protocol Buffer compiler on Debian/Ubuntu systems. This is a prerequisite for generating C++ source files from .proto definitions. ```bash sudo apt-get install protobuf-compiler ``` -------------------------------- ### Start Darknet Training with Verbose Output Source: https://github.com/hank-ai/darknet/blob/master/README.md Command to start Darknet training and display more detailed information during the process by adding the -verbose parameter. ```sh darknet detector -map -dont_show train animals.data animals.cfg -verbose ``` -------------------------------- ### Build and Install DarkHelp CLI Source: https://github.com/hank-ai/darknet/blob/master/colab/01_Building_the_Hank_ai_Darknet_YOLO_Framework.ipynb Installs DarkHelp dependencies, clones the repository, and builds/installs the DarkHelp CLI using CMake and Make, similar to Darknet. ```python # Build and install the DarkHelp CLI !sudo apt-get install build-essential libtclap-dev libmagic-dev libopencv-dev %cd ~/src %rm -rf ~/src/DarkHelp !git clone https://codeberg.org/CCodeRun/DarkHelp.git %cd ~/src/DarkHelp %mkdir build %cd build !cmake -DCMAKE_BUILD_TYPE=Release .. !make -j $(nproc) !make package !sudo dpkg -i darkhelp*.deb ``` -------------------------------- ### Install OpenBLAS for CPU-only builds Source: https://github.com/hank-ai/darknet/blob/master/README.md Installs the OpenBLAS library with core and threading support for x64 Windows, recommended for CPU-only Darknet builds to improve performance. ```bat .\vcpkg.exe install openblas[core,threads]:x64-windows ``` -------------------------------- ### Build DarkHelp CLI from Source Source: https://github.com/hank-ai/darknet/blob/master/colab/02_Building_Darknet_and_DarkHelp_to_use_the_Python_interface.ipynb Installs the DarkHelp command-line interface by cloning the repository, configuring with CMake, compiling, and installing the package. This is a prerequisite for using the Python API. ```bash # Build and install the DarkHelp CLI !sudo apt-get install build-essential libtclap-dev libmagic-dev libopencv-dev %cd ~/src %rm -rf ~/src/DarkHelp !git clone https://codeberg.org/CCodeRun/DarkHelp %cd ~/src/DarkHelp %mkdir build %cd build !cmake -DCMAKE_BUILD_TYPE=Release .. !make -j $(nproc) package !sudo dpkg -i darkhelp*.deb %cd ~ !DarkHelp --version ``` -------------------------------- ### Package and Install Darknet/YOLO Source: https://github.com/hank-ai/darknet/blob/master/colab/01_Building_the_Hank_ai_Darknet_YOLO_Framework.ipynb Creates a Debian package (`.deb`) for Darknet and installs it system-wide using `dpkg`. ```python # Create and install the .deb installation package %cd ~/src/darknet/build !make package !sudo dpkg -i darknet*.deb ``` -------------------------------- ### V3 C API Example: Load Neural Network Source: https://github.com/hank-ai/darknet/blob/master/doc/03_api.dox Demonstrates loading a neural network using the V3 C API. This function is analogous to the C++ API equivalent. ```c darknet_load_neural_network(); ``` -------------------------------- ### C API - Direct use of libdarknet Source: https://context7.com/hank-ai/darknet/llms.txt Illustrates how to directly use the `libdarknet.so` / `darknet.dll` from C code. This example shows network loading, configuration, and basic operations. ```APIDOC ## C API — Direct use of `libdarknet` from C code The C API in `darknet.h` mirrors the C++ API and is suitable for embedding Darknet into C projects or other language runtimes. ```c #include "darknet.h" #include int main(void) { darknet_show_version_info(); /* Configure before loading */ darknet_set_verbose(false); darknet_set_gpu_index(0); /* GPU 0, or -1 for CPU */ DarknetNetworkPtr net = darknet_load_neural_network( "animals.cfg", "animals.names", "animals_best.weights"); /* Adjust thresholds */ darknet_set_detection_threshold(net, 0.40f); darknet_set_non_maximal_suppression_threshold(net, 0.45f); darknet_fix_out_of_bound_values(net, true); /* Query dimensions */ int w = 0, h = 0, c = 0; darknet_network_dimensions(net, &w, &h, &c); printf("network: %dx%dx%d\n", w, h, c); /* Skip unwanted classes */ darknet_add_skipped_class(net, 2); /* ignore class 2 */ /* Send Darknet log to a file instead of stdout */ darknet_set_output_stream("/tmp/darknet.log"); darknet_free_neural_network(&net); /* net is set to NULL */ return 0; } ``` ``` -------------------------------- ### Install Build Tools with winget Source: https://github.com/hank-ai/darknet/blob/master/README.md Installs essential build tools like Git, CMake, NSIS, and Visual Studio Community Edition using the Windows Package Manager. ```bat winget install Git.Git winget install Kitware.CMake winget install nsis.nsis winget install Microsoft.VisualStudio.2022.Community ``` -------------------------------- ### Install Darknet CLI on Unix Source: https://github.com/hank-ai/darknet/blob/master/src-cli/CMakeLists.txt Installs the darknetcli executable to the 'bin' directory on Unix-like systems. ```cmake INSTALL (TARGETS darknetcli DESTINATION bin) ``` -------------------------------- ### V3 C++ API Example: Load Neural Network Source: https://github.com/hank-ai/darknet/blob/master/doc/03_api.dox Demonstrates loading a neural network using the V3 C++ API. This function is part of the simpler V3+ API. ```cpp Darknet::load_neural_network(); ``` -------------------------------- ### Install Darknet .deb Package Source: https://github.com/hank-ai/darknet/blob/master/README.md Install the built Darknet package using dpkg on Debian-based systems. This command installs the executables, headers, and libraries. ```sh sudo dpkg -i darknet-2.0.1-Linux.deb ``` -------------------------------- ### Start Darknet Training Source: https://github.com/hank-ai/darknet/blob/master/README.md Command to initiate the training process for a custom Darknet network. Use this for single GPU training. ```sh cd ~/nn/animals/ darknet detector -map -dont_show train animals.data animals.cfg ``` -------------------------------- ### Install Darknet CLI on Windows Source: https://github.com/hank-ai/darknet/blob/master/src-cli/CMakeLists.txt Installs the darknetcli executable and its runtime dependencies to the 'bin' directory on Windows, with specific exclusions for certain DLLs. ```cmake INSTALL (TARGETS darknetcli DESTINATION bin RUNTIME_DEPENDENCIES PRE_EXCLUDE_REGEXES "api-ms-" "ext-ms-" "wpaxholder" "HvsiFileTrust" "PdmUtilities" POST_EXCLUDE_REGEXES ".*system32/.*\\.dll" DIRECTORIES ${CMAKE_BINARY_DIR}/bin RUNTIME DESTINATION bin ) ``` -------------------------------- ### Image Utilities - resize_keeping_aspect_ratio and iou Source: https://context7.com/hank-ai/darknet/llms.txt Provides C++ examples for image utility functions: `resize_keeping_aspect_ratio` to resize images while maintaining aspect ratio, and `iou` to calculate intersection-over-union between bounding boxes. ```APIDOC ## `Darknet::resize_keeping_aspect_ratio()` and `Darknet::iou()` — Image utilities `resize_keeping_aspect_ratio()` resizes a `cv::Mat` as close as possible to the desired size while preserving the original aspect ratio. `iou()` computes intersection-over-union for two rectangles, useful for post-processing detection results. ```cpp #include "darknet.hpp" int main() { cv::Mat mat = cv::imread("large_photo.jpg"); // e.g. 4032 x 3024 // Shrink to fit within 1024x768, keeping aspect ratio Darknet::resize_keeping_aspect_ratio(mat, cv::Size(1024, 768), cv::InterpolationFlags::INTER_AREA); // mat is now 1024 x 768 (or smaller to preserve ratio) // Intersection-over-union between two detections cv::Rect box_a(10, 10, 100, 80); cv::Rect box_b(50, 40, 90, 70); float overlap = Darknet::iou(box_a, box_b); printf("IoU = %.3f\n", overlap); // IoU = 0.274 // Duration formatting utility auto start = std::chrono::high_resolution_clock::now(); // ... some work ... auto end = std::chrono::high_resolution_clock::now(); std::cout << Darknet::format_duration_string(end - start) << std::endl; // e.g. "2.453 milliseconds" return 0; } ``` ``` -------------------------------- ### Build and Package Darknet Source: https://github.com/hank-ai/darknet/blob/master/README_PGO.md After configuring CMake with the correct compilers, use 'make' to build the project and 'package' to create an installable package. This ensures the build uses the specified compiler versions. ```bash make -j4 package sudo dpkg -i darknet...etc... ``` -------------------------------- ### Start Darknet Training with Multiple GPUs Source: https://github.com/hank-ai/darknet/blob/master/README.md Command to initiate Darknet training utilizing multiple GPUs. Specify the GPU indices after the -gpus flag. ```sh cd ~/nn/animals/ darknet detector -gpus 0,1,2,3 -map -dont_show train animals.data animals.cfg ``` -------------------------------- ### Verify NVIDIA Tools Installation Source: https://github.com/hank-ai/darknet/blob/master/colab/01_Building_the_Hank_ai_Darknet_YOLO_Framework.ipynb Checks for the presence and version of NVIDIA's `nvidia-smi` and `nvcc` compiler, which are crucial for GPU acceleration. ```python # There are 2 specific tools from NVIDIA we're going to use to verify that everything is installed. # The first is nvidia-smi which gives real-time information in the GPU. !nvidia-smi # Next is the nvidia compiler. If you get a "command not found" error then things will not work! !nvcc --version ``` -------------------------------- ### Upgrade CMake on Ubuntu Source: https://github.com/hank-ai/darknet/blob/master/README.md Commands to remove the existing CMake installation and install the latest version using Snap. This is necessary if you are using an older version of CMake. ```sh sudo apt-get purge cmake sudo snap install cmake --classic ``` -------------------------------- ### Darknet CLI: Check Version Source: https://context7.com/hank-ai/darknet/llms.txt Checks the installed Darknet executable version. ```bash darknet version ``` -------------------------------- ### Train Darknet Model Source: https://github.com/hank-ai/darknet/blob/master/README.md Use this command to start training a Darknet object detection model. Ensure you are in the correct directory and have your configuration files set up. ```sh cd ~/nn/animals/ darknet detector -map -dont_show -verbose train animals.data animals.cfg ``` -------------------------------- ### Build Darknet with CMake on Linux Source: https://github.com/hank-ai/darknet/blob/master/README.md Steps to clone the Darknet repository, configure the build with CMake, compile the project, and package it as a .deb file. Ensure you have the necessary development tools and libraries installed. ```sh sudo apt-get install build-essential git libopencv-dev cmake libprotobuf-dev protobuf-compiler mkdir ~/src cd ~/src git clone https://codeberg.org/CCodeRun/darknet.git cd darknet mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Release .. make -j4 package sudo dpkg -i darknet-.deb ``` -------------------------------- ### List Installed GCC Compilers Source: https://github.com/hank-ai/darknet/blob/master/README_PGO.md Use this command to list available GCC compiler versions on your system. This helps in identifying the correct compiler to specify for CMake. ```bash ls -lh /usr/bin/g++* ``` -------------------------------- ### Download YOLOv4-tiny Weights Source: https://github.com/hank-ai/darknet/blob/master/README.md Use wget to download the yolov4-tiny weights. The --no-clobber option prevents overwriting existing files. ```sh wget --no-clobber https://github.com/hank-ai/darknet/releases/download/v2.0/yolov4-tiny.weights ``` -------------------------------- ### Confirm Global Darknet Installation Source: https://github.com/hank-ai/darknet/blob/master/colab/01_Building_the_Hank_ai_Darknet_YOLO_Framework.ipynb Verifies that the `darknet` command is accessible from any directory after installation and lists installed YOLO configuration files. ```python # Confirm that we can run "darknet" from anywhere since it has now been installed %cd ~ !darknet version # Show some of the /opt/ files we've installed. This should show ~40 .cfg files. !ls -lh /opt/darknet/cfg/yolov* ``` -------------------------------- ### DarkHelp Initialization and Configuration Source: https://github.com/hank-ai/darknet/blob/master/colab/02_Building_Darknet_and_DarkHelp_to_use_the_Python_interface.ipynb This section details how to initialize the DarkHelp neural network with a specified configuration, weights, and names file. It also covers various configuration options to customize the detection process, such as enabling/disabling annotations, name inclusion, snapping, tiling, setting confidence thresholds, and annotation line thickness. ```APIDOC ## DarkHelp Initialization and Configuration ### Description Initializes the DarkHelp neural network with configuration, weights, and names files. Allows customization of various detection and annotation parameters. ### Functions #### CreateDarkHelpNN * **Description**: Creates and initializes a DarkHelp neural network object. * **Parameters**: * `cfg_filename` (bytes): Path to the Darknet configuration file. * `weights_filename` (bytes): Path to the pre-trained weights file. * `names_filename` (bytes): Path to the file containing class names. * **Returns**: A pointer to the initialized DarkHelpNN object. #### DestroyDarkHelpNN * **Description**: Destroys and frees the memory associated with a DarkHelpNN object. * **Parameters**: * `dh` (DarkHelpNN pointer): Pointer to the DarkHelpNN object to destroy. #### EnableAnnotationAutoHideLabels * **Description**: Toggles the auto-hide behavior for annotation labels. * **Parameters**: * `dh` (DarkHelpNN pointer): Pointer to the DarkHelpNN object. * `enable` (bool): `True` to enable auto-hide, `False` to disable. #### EnableNamesIncludePercentage * **Description**: Toggles whether class names in annotations include their confidence percentage. * **Parameters**: * `dh` (DarkHelpNN pointer): Pointer to the DarkHelpNN object. * `enable` (bool): `True` to include percentage, `False` to exclude. #### EnableSnapping * **Description**: Toggles the snapping feature for bounding boxes. * **Parameters**: * `dh` (DarkHelpNN pointer): Pointer to the DarkHelpNN object. * `enable` (bool): `True` to enable snapping, `False` to disable. #### EnableTiles * **Description**: Toggles the tiling feature for processing large images. * **Parameters**: * `dh` (DarkHelpNN pointer): Pointer to the DarkHelpNN object. * `enable` (bool): `True` to enable tiling, `False` to disable. #### SetThreshold * **Description**: Sets the confidence threshold for object detection. * **Parameters**: * `dh` (DarkHelpNN pointer): Pointer to the DarkHelpNN object. * `threshold` (float): The minimum confidence score (0.0 to 1.0) for a detection to be considered valid. #### SetAnnotationLineThickness * **Description**: Sets the thickness of the lines used for annotations. * **Parameters**: * `dh` (DarkHelpNN pointer): Pointer to the DarkHelpNN object. * `thickness` (int): The line thickness in pixels. ### Example Usage ```python import DarkHelp dh = DarkHelp.CreateDarkHelpNN( b"yolov4-tiny.cfg", b"yolov4-tiny.weights", b"coco.names" ) DarkHelp.EnableAnnotationAutoHideLabels(dh, False) DarkHelp.EnableNamesIncludePercentage(dh, False) DarkHelp.EnableSnapping(dh, False) DarkHelp.EnableTiles(dh, False) DarkHelp.SetThreshold(dh, 0.45) DarkHelp.SetAnnotationLineThickness(dh, 1) # ... perform predictions ... DarkHelp.DestroyDarkHelpNN(dh) ``` ``` -------------------------------- ### Initialize DarkHelp Python API and Perform Object Detection Source: https://github.com/hank-ai/darknet/blob/master/colab/02_Building_Darknet_and_DarkHelp_to_use_the_Python_interface.ipynb Sets up the DarkHelp Python environment, downloads necessary model files, and performs object detection on an image. It configures detection parameters, annotates the output, and prints prediction details. ```python %mkdir -p ~/testing %cd ~/testing # Download the MSCOCO pre-trained weights (https://github.com/hank-ai/darknet#mscoco-pre-trained-weights). !wget --no-clobber https://github.com/hank-ai/darknet/releases/download/v2.0/yolov4-tiny.weights # Copy the files we're going to use. !cp /opt/darknet/cfg/yolov4-tiny.cfg . !cp /opt/darknet/cfg/coco.names . !cp ~/src/DarkHelp/src-python/DarkHelp.py . !cp ~/src/darknet/artwork/dog.jpg . import DarkHelp import json from matplotlib import pyplot as plt print("DarkHelp v" + DarkHelp.DarkHelpVersion().decode()) print("Darknet v" + DarkHelp.DarknetVersion().decode()) # Note the order in which the filenames are specified when constructing a # DarkHelp object does not matter. It will figure out which file is which. dh = DarkHelp.CreateDarkHelpNN( "yolov4-tiny.cfg".encode(), "yolov4-tiny.weights".encode(), "coco.names".encode()) DarkHelp.EnableAnnotationAutoHideLabels(dh, False) DarkHelp.EnableNamesIncludePercentage(dh, False) DarkHelp.EnableSnapping(dh, False) DarkHelp.EnableTiles(dh, False) DarkHelp.SetThreshold(dh, 0.45) DarkHelp.SetAnnotationLineThickness(dh, 1) DarkHelp.PredictFN(dh, "dog.jpg".encode()) # Note that cv2.imread() uses BGR, while matplotlib uses RGB, so we'll skip # the call to cv2.cvtColor() and use matplotlib to read the image. If we # need to manipulate the image in OpenCV, we'd probably be better off using # cv2.imread() instead. DarkHelp.Annotate(dh, "output.jpg".encode()) img = plt.imread("output.jpg") plt.imshow(img) # Iterate over all predictions made and display some information on each one. j = json.loads(DarkHelp.GetPredictionResults(dh)) for prediction in j['file'][0]['prediction']: if False: # the next line displays a lot of information so turn it off by default print(prediction) idx = prediction['best_class'] name = prediction['name'] prob = prediction['best_probability'] * 100.0 x = prediction['rect']['x'] y = prediction['rect']['y'] w = prediction['rect']['width'] h = prediction['rect']['height'] print(f"class #{idx}: {prob:.1f}% \"{name}\" at {prediction['rect']}") # If you want, the RoI can be extracted and you could then do whatever you # want with it, such as saving it to a file or passing it to a function. if False: roi = img[y:y+h, x:x+w] plt.imshow(roi) DarkHelp.DestroyDarkHelpNN(dh) ``` -------------------------------- ### Read from Webcam (V3+) Source: https://github.com/hank-ai/darknet/blob/master/README.md Display webcam feed with object detection using the V3+ CLI. ```bash darknet_08_display_webcam animals ``` -------------------------------- ### Read from Webcam (V2) Source: https://github.com/hank-ai/darknet/blob/master/README.md Capture and process video from a webcam using the V2 CLI, specifying camera index 0. ```bash darknet detector demo animals.data animals.cfg animals_best.weights -c 0 ``` -------------------------------- ### V3 Python API Source: https://github.com/hank-ai/darknet/blob/master/doc/03_api.dox The Python API for Darknet/YOLO is structured similarly to the C API. Refer to the source files for detailed implementation and example usage. ```APIDOC ## V3 Python API ### Description The Python API is very similar to the C API. See @p src-python/darknet.py for details, or @p src-python/example.py for sample code. For documentation, see @ref apiv3_c. ``` -------------------------------- ### Process Video (V2) Source: https://github.com/hank-ai/darknet/blob/master/README.md Run object detection on a video file using the V2 CLI with the -ext_output flag. ```bash darknet detector demo animals.data animals.cfg animals_best.weights -ext_output test.mp4 ``` -------------------------------- ### Download MSCOCO Weights Source: https://github.com/hank-ai/darknet/blob/master/colab/01_Building_the_Hank_ai_Darknet_YOLO_Framework.ipynb Downloads the `yolov4-tiny.weights` file for MSCOCO detection using `wget`. The `--no-clobber` option prevents re-downloading if the file already exists. ```python # Download the MSCOCO pre-trained weights (https://codeberg.org/CCodeRun/darknet#mscoco-pre-trained-weights) %cd ~/src/darknet !wget --no-clobber https://github.com/hank-ai/darknet/releases/download/v2.0/yolov4-tiny.weights ``` -------------------------------- ### Process Video (DarkHelp) Source: https://github.com/hank-ai/darknet/blob/master/README.md Run object detection on a video file using the DarkHelp CLI. ```bash DarkHelp animals.cfg animals.names animals_best.weights test.mp4 ``` -------------------------------- ### Process Video (V3+) Source: https://github.com/hank-ai/darknet/blob/master/README.md Display object detection results on a video using the V3+ CLI. ```bash darknet_03_display_videos animals.cfg test.mp4 ``` -------------------------------- ### Predict with Image (DarkHelp) Source: https://github.com/hank-ai/darknet/blob/master/README.md Perform object detection on an image using the DarkHelp CLI. Requires config, names, and weights files. ```bash DarkHelp cars.cfg cars.cfg cars_best.weights image1.jpg ``` -------------------------------- ### Clone and Build Darknet with CMake Source: https://github.com/hank-ai/darknet/blob/master/README.md Clones the Darknet repository, creates a build directory, and then configures the build using CMake with vcpkg toolchain integration, followed by building the solution with msbuild. ```bat cd c:\src git clone https://codeberg.org/CCodeRun/darknet.git cd darknet mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=C:/src/vcpkg/scripts/buildsystems/vcpkg.cmake .. msbuild.exe /property:Platform=x64;Configuration=Release /target:Build -maxCpuCount -verbosity:normal -detailedSummary darknet.sln msbuild.exe /property:Platform=x64;Configuration=Release PACKAGE.vcxproj ``` -------------------------------- ### Real-Time Detection using Webcam Input Source: https://github.com/hank-ai/darknet/blob/master/src-python/readme.md Process real-time video from a webcam (input index 1) for object detection. ```bash python darknet_video.py --input 1 --weights yolov4.weights --config_file yolov4.cfg --data_file obj.data ``` -------------------------------- ### Configure CPack Generator for RPM Package Source: https://github.com/hank-ai/darknet/blob/master/README.md Modify the CM_package.cmake file to change the CPack generator from DEB to RPM. This is required for building RPM installation files for distros like CentOS and OpenSUSE. ```cmake SET (CPACK_GENERATOR "DEB") # SET (CPACK_GENERATOR "RPM") ``` ```cmake # SET (CPACK_GENERATOR "DEB") SET (CPACK_GENERATOR "RPM") ``` -------------------------------- ### Run DarkHelp on Video with YOLOv4-tiny Source: https://github.com/hank-ai/darknet/blob/master/README.md Utilize DarkHelp for video analysis with coco.names, yolov4-tiny.cfg, and yolov4-tiny.weights. ```sh DarkHelp coco.names yolov4-tiny.cfg yolov4-tiny.weights video1.avi ``` -------------------------------- ### Build Darknet with PGO Generation Enabled Source: https://github.com/hank-ai/darknet/blob/master/README_PGO.md Use this command to initially build Darknet with PGO generation enabled. This step creates the necessary profile data files during runtime. ```sh cd ~/src/darknet/build cmake -DCMAKE_C_COMPILER=/usr/bin/gcc-12 -DCMAKE_CXX_COMPILER=/usr/bin/g++-12 -DDARKNET_PROFILE_GEN=ON -DDARKNET_PROFILE_USE=OFF .. make -j4 package sudo dpkg -i darknet...etc... ``` -------------------------------- ### DarkHelp Prediction Results Retrieval Source: https://github.com/hank-ai/darknet/blob/master/colab/02_Building_Darknet_and_DarkHelp_to_use_the_Python_interface.ipynb This section explains how to retrieve the detailed results of an object detection prediction in JSON format. It includes the function to get the prediction results and a description of the expected JSON structure. ```APIDOC ## DarkHelp Prediction Results Retrieval ### Description Allows retrieval of the detailed prediction results in JSON format after a prediction has been made. ### Functions #### GetPredictionResults * **Description**: Retrieves the prediction results as a JSON string. * **Parameters**: * `dh` (DarkHelpNN pointer): Pointer to the DarkHelpNN object. * **Returns**: A C-style string (bytes) containing the JSON representation of the prediction results. ### Prediction Results JSON Structure The returned JSON contains information about the file processed and a list of predictions. Each prediction includes: * `best_class` (int): The index of the class with the highest confidence. * `name` (string): The name of the detected object class. * `best_probability` (float): The confidence score for the best class (0.0 to 1.0). * `rect` (object): A bounding box object with `x`, `y`, `width`, and `height` properties. ### Example Usage ```python import DarkHelp import json # Assuming 'dh' is an initialized DarkHelpNN object and a prediction has been made results_json = DarkHelp.GetPredictionResults(dh) j = json.loads(results_json.decode()) for prediction in j['file'][0]['prediction']: print(f"Class: {prediction['name']}, Probability: {prediction['best_probability']:.1%}") ``` ``` -------------------------------- ### Run Object Detection with DarkHelp Source: https://github.com/hank-ai/darknet/blob/master/colab/01_Building_the_Hank_ai_Darknet_YOLO_Framework.ipynb Performs object detection on an image using the DarkHelp CLI with various parameters to customize output. Results are saved as 'dog.png'. ```python # This is what the command looks like when using Darknet to predict. Because we're using --dont-show, the results will be saved as an image to "predictions.jpg" #!darknet detector test --dont-show cfg/coco.data cfg/yolov4-tiny.cfg yolov4-tiny.weights artwork/dog.jpg # And this how we do the equivalent but with DarkHelp instead. See the DarkHelp documentation to see all the options which alter the look of the output image. # https://www.ccoderun.ca/darkhelp/api/Parameters.html !DarkHelp --json --autohide off --keep --duration off --fontscale 0.7 --line 5 --shade 0.25 --threshold 0.5 --outdir . cfg/yolov4-tiny.cfg cfg/coco.names yolov4-tiny.weights artwork/dog.jpg ``` -------------------------------- ### C++ Image Utilities: Resize and IoU Source: https://context7.com/hank-ai/darknet/llms.txt Utilize C++ Darknet utilities for image resizing while maintaining aspect ratio and calculating Intersection-over-Union (IoU) for bounding boxes. Also includes a duration formatting utility. ```cpp #include "darknet.hpp" int main() { cv::Mat mat = cv::imread("large_photo.jpg"); // e.g. 4032 x 3024 // Shrink to fit within 1024x768, keeping aspect ratio Darknet::resize_keeping_aspect_ratio(mat, cv::Size(1024, 768), cv::InterpolationFlags::INTER_AREA); // mat is now 1024 x 768 (or smaller to preserve ratio) // Intersection-over-union between two detections cv::Rect box_a(10, 10, 100, 80); cv::Rect box_b(50, 40, 90, 70); float overlap = Darknet::iou(box_a, box_b); printf("IoU = %.3f\n", overlap); // IoU = 0.274 // Duration formatting utility auto start = std::chrono::high_resolution_clock::now(); // ... some work ... auto end = std::chrono::high_resolution_clock::now(); std::cout << Darknet::format_duration_string(end - start) << std::endl; // e.g. "2.453 milliseconds" return 0; } ``` -------------------------------- ### Run DarkHelp on Image with YOLOv4-tiny Source: https://github.com/hank-ai/darknet/blob/master/README.md Utilize DarkHelp for image analysis with coco.names, yolov4-tiny.cfg, and yolov4-tiny.weights. ```sh DarkHelp coco.names yolov4-tiny.cfg yolov4-tiny.weights image1.jpg ``` -------------------------------- ### JSON Output (V2) Source: https://github.com/hank-ai/darknet/blob/master/README.md Run object detection on a video stream and output results in JSON format to a specified port using the V2 CLI. ```bash darknet detector demo animals.data animals.cfg animals_best.weights test50.mp4 -json_port 8070 -mjpeg_port 8090 -ext_output ``` -------------------------------- ### Darknet CLI: Run Inference on Images Source: https://context7.com/hank-ai/darknet/llms.txt Runs inference on images, prints results, and saves annotated copies. Requires network configuration, names, and weights files. ```bash darknet_01_inference_images animals.cfg animals.names animals_best.weights *.jpg ``` -------------------------------- ### Build Darknet Docker Image with GPU Support Source: https://github.com/hank-ai/darknet/blob/master/README.md Dockerfile to build Darknet with GPU support. Requires nvidia-container-toolkit. Build with `docker build -t darknet-hankai . && docker run -it --gpus all darknet-hankai`. ```docker FROM nvidia/cuda:12.8.0-cudnn-devel-ubuntu24.04 # Set environment variables ENV DEBIAN_FRONTEND=noninteractive ENV PATH="/usr/local/cuda/bin:${PATH}" ENV LD_LIBRARY_PATH="/usr/local/cuda/lib64:${LD_LIBRARY_PATH}" # Install dependencies RUN apt-get update RUN apt-get install -y build-essential git libopenblas64-openmp-dev libopencv-dev wget file cmake # Set working directory for Darknet WORKDIR /workspace # Clone Darknet RUN git clone https://codeberg.org/CCodeRun/darknet.git # Defer building the Darknet package to runtime (GPU visible) CMD ["/bin/bash", "-c", " \ cd /workspace/darknet && \ # initialize cmake mkdir build && cd build && cmake ..; \ # build darknet make -j$(nproc) package && \ # package darknet dpkg -i /workspace/darknet/build/darknet-*.deb && \ # run darknet version to verify build & enter terminal darknet version && \ exec /bin/bash"] ``` -------------------------------- ### Load Neural Network with Darknet::load_neural_network() Source: https://context7.com/hank-ai/darknet/llms.txt Load a Darknet neural network using explicit file paths or pre-parsed arguments. Remember to call `Darknet::free_neural_network()` to release memory. ```cpp #include "darknet.hpp" int main(int argc, char * argv[]) { try { // Method 1: explicit paths Darknet::NetworkPtr net = Darknet::load_neural_network( "animals.cfg", "animals.names", "animals_best.weights"); // Method 2: from pre-parsed parms Darknet::Parms parms = Darknet::parse_arguments(argc, argv); Darknet::NetworkPtr net2 = Darknet::load_neural_network(parms); // Query the network input dimensions int w = 0, h = 0, c = 0; Darknet::network_dimensions(net, w, h, c); std::cout << "network: " << w << " x " << h << " x " << c << std::endl; // Output: network: 416 x 416 x 3 Darknet::free_neural_network(net); Darknet::free_neural_network(net2); } catch (const std::exception & e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; } ``` -------------------------------- ### Select a Different GPU for Detection Source: https://github.com/hank-ai/darknet/blob/master/src-python/readme.md Specify the GPU index to use for accelerating detection processes. Defaults to GPU 0 if not specified. ```bash --gpu_index 1 ``` -------------------------------- ### Run on Specific GPU (V2) Source: https://github.com/hank-ai/darknet/blob/master/README.md Execute object detection on a specific GPU (index 1) using the V2 CLI. ```bash darknet detector demo animals.data animals.cfg animals_best.weights -i 1 test.mp4 ``` -------------------------------- ### Python API - Object Detection Source: https://context7.com/hank-ai/darknet/llms.txt Demonstrates how to perform object detection on a single image using the Python ctypes bindings. It covers loading the network, performing detection, and printing the results. ```APIDOC ## Python API — Object detection via ctypes bindings The `src-python/darknet.py` module wraps `libdarknet.so` / `darknet.dll` using Python's ctypes. `src-python/darknet_images.py` provides higher-level helpers (`image_detection()`, `batch_detection()`) that handle BGR↔RGB conversion and resizing automatically. ```python import cv2 import darknet # src-python/darknet.py from darknet_images import image_detection, load_images # --- Setup --- network = darknet.load_network( config_file="animals.cfg", data_file="animals.data", # only needed for the legacy API path weights="animals_best.weights", batch_size=1) class_names = open("animals.names").read().splitlines() class_colors = darknet.class_colors(class_names) # deterministic BGR colors per class # --- Single image detection --- image, detections = image_detection( "dog.jpg", network, class_names, class_colors, thresh=0.50) darknet.print_detections(detections, coordinates=True) # Objects: # dog: 98.5% (left_x: 68 top_y: 164 width: 191 height: 314) cv2.imwrite("dog_annotated.jpg", image) # --- Query network dimensions --- w, h, c = darknet.network_dimensions(network) print(f"network input: {w}x{h}x{c}") # network input: 416x416x3 # --- Skip classes and adjust verbose output --- darknet.set_verbose(False) darknet.add_skipped_class(network, 0) # skip class 0 # --- Control output stream (suppress Darknet console output) --- darknet.set_output_stream(b"/dev/null") # --- Version info --- print(darknet.version_short().decode()) # e.g. "5.1.42" darknet.show_version_info() ``` ``` -------------------------------- ### Save Video Results (V3+) Source: https://github.com/hank-ai/darknet/blob/master/README.md Process videos and save results using multithreading with the V3+ CLI. ```bash darknet_05_process_videos_multithreaded animals.cfg animals.names animals_best.weights test.mp4 ``` -------------------------------- ### Predict with Image (V2) Source: https://github.com/hank-ai/darknet/blob/master/README.md Perform object detection on an image using the V2 CLI. Requires data, config, and weights files. ```bash darknet detector test cars.data cars.cfg cars_best.weights image1.jpg ``` -------------------------------- ### Save Video Results (V2) Source: https://github.com/hank-ai/darknet/blob/master/README.md Process a video and save the annotated output to a new video file using the V2 CLI. ```bash darknet detector demo animals.data animals.cfg animals_best.weights test.mp4 -out_filename res.avi ``` -------------------------------- ### Run Darknet to Generate Profile Data Source: https://github.com/hank-ai/darknet/blob/master/README_PGO.md After building with PGO generation enabled, run Darknet/YOLO with typical workloads (training or inference) to generate the profile output files (e.g., .gcda files). ```sh cd ~/nn/LegoGears darknet_05_process_videos_multithreaded LegoGears DSCN*.MOV ``` -------------------------------- ### Initial CMake Configuration for PGO Generation Source: https://github.com/hank-ai/darknet/blob/master/README_PGO.md This command configures the build process to enable PGO generation. Ensure you disable PGO usage in this initial build step. ```sh cd ~/src/darknet/build cmake -DDARKNET_PROFILE_GEN=ON -DDARKNET_PROFILE_USE=OFF .. make -j4 package sudo dpkg -i darknet...etc... ``` -------------------------------- ### Use a Different YOLO Model for Video Processing Source: https://github.com/hank-ai/darknet/blob/master/src-python/readme.md Specify custom paths for weights, configuration, and data files to use a different YOLO model for video processing. ```bash python darknet_video.py --input path/to/your/video.mp4 --weights path/to/your/weights.weights --config_file path/to/your/config.cfg --data_file path/to/your/data.data ``` -------------------------------- ### JSON Output (DarkHelp) Source: https://github.com/hank-ai/darknet/blob/master/README.md Perform object detection and output results in JSON format using the DarkHelp CLI. ```bash DarkHelp --json animals.names animals.cfg animals_best.weights image1.jpg ``` -------------------------------- ### Configure Darknet Build with CMake Source: https://github.com/hank-ai/darknet/blob/master/colab/01_Building_the_Hank_ai_Darknet_YOLO_Framework.ipynb Prepares the build directory and configures the Darknet build using CMake, specifying a Release build type. Verifies CUDA and cuDNN detection. ```python # Prepare the Darknet/YOLO build directory %cd ~/src/darknet %rm -rf ~/src/darknet/build %mkdir ~/src/darknet/build %cd ~/src/darknet/build !cmake -DCMAKE_BUILD_TYPE=Release .. # Once cmake has finished, make sure that CUDA and cuDNN are working. The output should contain lines such as: # "CUDA detected. Darknet will use the GPU." # and # "Found cuDNN" ``` -------------------------------- ### Output Coordinates (V3+) Source: https://github.com/hank-ai/darknet/blob/master/README.md Perform inference on images and output results using the V3+ CLI. ```bash darknet_01_inference_images animals dog.jpg ```