### Object Detection Example Setup and Usage Source: https://docs.opencv.org/5.0.0-alpha/d4/db9/samples_2dnn_2object_detection_8cpp-example.html This section provides instructions on how to download models, set environment variables, and run the object detection example. It also details the command-line arguments available for configuring the model, input source, and detection parameters. ```cpp #include #include #include #include #include #include #include #include #include #include "iostream" #include "common.hpp" using namespace cv; using namespace dnn; using namespace std; const string about = "Firstly, download required models using `download_models.py` (if not already done). Set environment variable OPENCV_DOWNLOAD_CACHE_DIR to specify where models should be downloaded. Also, point OPENCV_SAMPLES_DATA_PATH to opencv/samples/data.\n" "To run:\n" "\t ./example_dnn_object_detection model_name --input=path/to/your/input/image/or/video (don't give --input flag if want to use device camera)\n" "Sample command:\n" "\t ./example_dnn_object_detection yolov8 --input=$OPENCV_SAMPLES_DATA_PATH/baboon.jpg\n" "Model path can also be specified using --model argument. "; const string param_keys = "{ help h | | Print help message. }" "{ @alias | | An alias name of model to extract preprocessing parameters from models.yml file. }" "{ zoo | ../dnn/models.yml | An optional path to file with preprocessing parameters }" "{ device | 0 | camera device number. }" "{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera. }" "{ thr | .5 | Confidence threshold. }" "{ nms | .4 | Non-maximum suppression threshold. }" "{ async | 0 | Number of asynchronous forwards at the same time. " "Choose 0 for synchronous mode }" "{ padvalue | 114.0 | padding value. }" "{ paddingmode | 2 | Choose one of padding modes: " "0: resize to required input size without extra processing, " "1: Image will be cropped after resize, " "2: Resize image to the desired size while preserving the aspect ratio of original image }"; const string backend_keys = format( "{ backend | default | Choose one of computation backends: " "default: automatically (by default), " "openvino: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), " "opencv: OpenCV implementation, " "vkcom: VKCOM, " "cuda: CUDA, " "webnn: WebNN }", backend_keys); const string target_keys = format( "{ target | cpu | Choose one of target computation devices: " "cpu: CPU target (by default), " "opencl: OpenCL, " "opencl_fp16: OpenCL fp16 (half-float precision), " "vpu: VPU, " "vulkan: Vulkan, " "cuda: CUDA, " "cuda_fp16: CUDA fp16 (half-float preprocess) }", target_keys); string keys = param_keys + backend_keys + target_keys; float confThreshold, nmsThreshold, scale, paddingValue; vector labels; Scalar meanv; bool swapRB; int inpWidth, inpHeight; size_t asyncNumReq = 0; ImagePaddingMode paddingMode; string modelName, framework; static void preprocess(const Mat& frame, Net& net, Size inpSize); static void postprocess(Mat& frame, const vector& outs, Net& net, int backend, vector& classIds, vector& confidences, vector& boxes, const string postprocessing); static void drawPred(vector& classIds, vector& confidences, vector& boxes, Mat& frame, FontFace& sans, int stdSize, int stdWeight, int stdImgSize, int stdThickness); static void callback(int pos, void* userdata); static Scalar getColor(int classId); static void yoloPostProcessing( const vector& outs, vector& keep_classIds, vector& keep_confidences, vector& keep_boxes, float conf_threshold, float iou_threshold, const string& postprocessing); ``` -------------------------------- ### FloodFill Example Setup and Help Function Source: https://docs.opencv.org/5.0.0-alpha/d9/dae/samples_2cpp_2floodfill_8cpp-example.html Includes necessary headers, namespace declarations, and a help function to display usage instructions and hotkeys for interacting with the flood fill demonstration. ```cpp #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include using namespace cv; using namespace std; static void help(char** argv) { cout << "\nThis program demonstrated the floodFill() function\n" "Call:\n" << argv[0] << " [image_name -- Default: fruits.jpg]\n" << endl; cout << "Hot keys: \n" "\tESC - quit the program\n" "\tc - switch color/grayscale mode\n" "\tm - switch mask mode\n" "\tr - restore the original image\n" "\ts - use null-range floodfill\n" "\tf - use gradient floodfill with fixed(absolute) range\n" "\tg - use gradient floodfill with floating(relative) range\n" "\t4 - use 4-connectivity mode\n" "\t8 - use 8-connectivity mode\n" << endl; } ``` -------------------------------- ### Main Function with PCA Setup Source: https://docs.opencv.org/5.0.0-alpha/d3/db0/samples_2cpp_2pca_8cpp-example.html Parses command-line arguments to get the input image list file. Initializes the PCA process and sets up the trackbar for interactive variance control. ```cpp int main(int argc, char** argv) { cv::CommandLineParser parser(argc, argv, "{@input||image list}{help h||show help message}"); if (parser.has("help")) { parser.printMessage(); exit(0); } ``` -------------------------------- ### Hough Lines Python Example Setup Source: https://docs.opencv.org/5.0.0-alpha/d9/db0/tutorial_hough_lines.html Sets up the filename for the Hough lines example. Uses a default image if no filename is provided. ```python import sys import math import cv2 as cv import numpy as np def main(argv): default_file = 'sudoku.png' filename = argv[0] if len(argv) > 0 else default_file ``` -------------------------------- ### GrabCut Algorithm Setup and Help Function Source: https://docs.opencv.org/5.0.0-alpha/d8/d34/samples_2cpp_2grabcut_8cpp-example.html This C++ code sets up the necessary includes and a help function for the GrabCut example. It outlines the program's usage, hotkeys, and mouse interactions for segmentation. ```cpp #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include using namespace std; using namespace cv; static void help(char** argv) { cout << "\nThis program demonstrates GrabCut segmentation -- select an object in a region\n" "and then grabcut will attempt to segment it out.\n" "Call:\n" << argv[0] << " \n" "\nSelect a rectangular area around the object you want to segment\n" << "\nHot keys: \n" "\tESC - quit the program\n" "\tr - restore the original image\n" "\tn - next iteration\n" "\n" "\tleft mouse button - set rectangle\n" "\n" "\tCTRL+left mouse button - set GC_BGD pixels\n" "\tSHIFT+left mouse button - set GC_FGD pixels\n" "\n" "\tCTRL+right mouse button - set GC_PR_BGD pixels\n" "\tSHIFT+right mouse button - set GC_PR_FGD pixels\n" << endl; } ``` -------------------------------- ### Configure OpenCV with Relative Install Prefix Source: https://docs.opencv.org/5.0.0-alpha/db/d05/tutorial_config_reference.html Set the installation root directory relative to the current working directory. This example sets it to a 'install' subdirectory. ```bash cmake -DCMAKE_INSTALL_PREFIX=install ../opencv ``` -------------------------------- ### setup Source: https://docs.opencv.org/5.0.0-alpha/dc/d47/classcv_1_1bioinspired_1_1Retina-members.html Configures the retina model with various setup options. ```APIDOC ## setup (String retinaParameterFile="", const bool applyDefaultSetupOnFailure=true) ### Description Sets up the retina model using parameters from a file. If the file is not found or invalid, a default setup can be applied. ### Method `pure virtual` ### Parameters * **retinaParameterFile** (String) - Path to the parameter file (default: empty string). * **applyDefaultSetupOnFailure** (const bool) - Whether to apply default settings if setup fails (default: true). ``` ```APIDOC ## setup (cv::FileStorage &fs, const bool applyDefaultSetupOnFailure=true) ### Description Sets up the retina model using parameters from a cv::FileStorage object. ### Method `pure virtual` ### Parameters * **fs** (cv::FileStorage&) - FileStorage object containing the parameters. * **applyDefaultSetupOnFailure** (const bool) - Whether to apply default settings if setup fails (default: true). ``` ```APIDOC ## setup (RetinaParameters newParameters) ### Description Sets up the retina model with a provided RetinaParameters object. ### Method `pure virtual` ### Parameters * **newParameters** (RetinaParameters) - The new parameters to configure the retina model. ``` -------------------------------- ### Print Setup Configuration (C++) Source: https://docs.opencv.org/5.0.0-alpha/d2/d94/bioinspired_retina.html Outputs a string representation of the current parameter setup for the Retina instance. ```cpp const String printSetup (); ``` -------------------------------- ### Build and Install OpenCV Source: https://docs.opencv.org/5.0.0-alpha/db/d05/tutorial_config_reference.html Build the OpenCV library and install the produced binaries to the configured installation location. ```bash cmake --build . --target install ``` -------------------------------- ### Python Meanshift Tracking Setup Source: https://docs.opencv.org/5.0.0-alpha/d7/d00/tutorial_meanshift.html Initializes argument parsing for a Python script demonstrating the Meanshift algorithm. Specifies the video file URL for the example. ```python import numpy as np import cv2 as cv import argparse parser = argparse.ArgumentParser(description='This sample demonstrates the meanshift algorithm. \ The example file can be downloaded from: \ https://www.bogotobogo.com/python/OpenCV_Python/images/mean_shift_tracking/slow_traffic_small.mp4') ``` -------------------------------- ### Write Setup Configuration (C++) Source: https://docs.opencv.org/5.0.0-alpha/d2/d94/bioinspired_retina.html Writes the current parameter setup to an XML or YAML file. ```cpp virtual void write (String fs) const; virtual void write (FileStorage &fs) const; ``` -------------------------------- ### Build and Install OpenCV Source: https://docs.opencv.org/5.0.0-alpha/d2/de6/tutorial_py_setup_in_ubuntu.html Compile the OpenCV library using the 'make' command and then install it using 'sudo make install'. This process builds the necessary files and installs them into the '/usr/local/' directory. ```bash make ``` ```bash # sudo make install ``` -------------------------------- ### Run Example from Command Line Source: https://docs.opencv.org/5.0.0-alpha/d5/de7/tutorial_dnn_googlenet.html Executes the compiled DNN example from the command line, specifying the GoogLeNet model. ```bash ./example_dnn_classification googlenet ``` -------------------------------- ### Install Tesseract Script Source: https://docs.opencv.org/5.0.0-alpha/db/d4c/tutorial_install_tesseract.html Executes the installation script for Tesseract. ```bash ./installTesseract.sh ``` -------------------------------- ### Build and Install zlib and PNG Source: https://docs.opencv.org/5.0.0-alpha/db/d4c/tutorial_install_tesseract.html This script builds and installs zlib and libpng libraries using CMake and Visual Studio. It configures installation paths and builds both release and debug versions. ```bash #!/bin/bash myRepo=$(pwd) CMAKE_CONFIG_GENERATOR="Visual Studio 14 2015 Win64" RepoSource=zlib mkdir Build/$RepoSource pushd Build/$RepoSource cmake . -G"Visual Studio 14 2015 Win64" \ -DCMAKE_INSTALL_PREFIX:PATH="$myRepo"/install/zlib -DINSTALL_BIN_DIR:PATH="$myRepo"/install/zlib/bin \ -DINSTALL_INC_DIR:PATH="$myRepo"/install/zlib/include -DINSTALL_LIB_DIR:PATH="$myRepo"/install/zlib/lib "$myRepo"/"$RepoSource" cmake --build . --config release cmake --build . --target install --config release cmake --build . --config debug cmake --build . --target install --config debug popd RepoSource=lpng mkdir Build/$RepoSource pushd Build/$RepoSource cp "$myRepo"/"$RepoSource"/scripts/pnglibconf.h.prebuilt "$myRepo"/"$RepoSource"/pnglibconf.h cmake . -G"Visual Studio 14 2015 Win64" \ -DZLIB_INCLUDE_DIR:PATH="$myRepo"/install/zlib/include -DZLIB_LIBRARY_DEBUG:FILE="$myRepo"/install/zlib/lib/zlibstaticd.lib \ -Dld-version-script:BOOL=OFF -DPNG_TESTS:BOOL=OFF -DAWK:STRING= \ -DZLIB_LIBRARY_RELEASE:FILE="$myRepo"/install/zlib/lib/zlibstatic.lib -DCMAKE_INSTALL_PREFIX="$myRepo"/Install/"$RepoSource" \ "$myRepo"/"$RepoSource" cmake --build . --config release cmake --build . --target install --config release cmake --build . --config debug cmake --build . --target install --config debug popd ``` -------------------------------- ### Install with Make Source: https://docs.opencv.org/5.0.0-alpha/d7/d9f/tutorial_linux_install.html Installs OpenCV to the default location (/usr/local) using Make. Requires elevated privileges. ```bash sudo make install ``` -------------------------------- ### Set Installation Prefix for OpenCV Source: https://docs.opencv.org/5.0.0-alpha/d3/d52/tutorial_windows_install.html This CMake option specifies the directory where OpenCV will be installed after compilation. The example shows installation into a subdirectory named 'opencv' within an 'install' folder. ```bash -DCMAKE_INSTALL_PREFIX="$myRepo/install/$RepoSource" ``` -------------------------------- ### Install with Ninja Source: https://docs.opencv.org/5.0.0-alpha/d7/d9f/tutorial_linux_install.html Installs OpenCV to the default location (/usr/local) using Ninja. Requires elevated privileges. ```bash sudo ninja install ``` -------------------------------- ### setup() Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/bioinspired/Retina.html Attempts to load retina parameters from an XML file. If the file is not found, default settings are applied. Exceptions are thrown if the XML file is invalid. ```APIDOC ## setup ### Description Try to open an XML retina parameters file to adjust current retina instance setup. If the xml file does not exist, then default setup is applied. Warning, Exceptions are thrown if read XML file is not valid. You can retrieve the current parameters structure using the method Retina::getParameters and update it before running method Retina::setup. ``` -------------------------------- ### Configure OpenCV with Custom Install Prefix Source: https://docs.opencv.org/5.0.0-alpha/db/d05/tutorial_config_reference.html Set the installation root directory for OpenCV binaries during configuration. This example sets it to '/opt/opencv'. ```bash cmake -DCMAKE_INSTALL_PREFIX=/opt/opencv ../opencv ``` -------------------------------- ### setup Source: https://docs.opencv.org/5.0.0-alpha/dd/dc9/structcv_1_1detail_1_1OCVSetupHelper_3_01Impl_00_01std_1_1tuple_3_01Ins_8_8_8_01_4_01_4-members.html Sets up the OpenCV environment with provided metadata and arguments. ```APIDOC ## setup ### Description Sets up the OpenCV environment using metadata arguments, general arguments, state, and compilation arguments. ### Method static ### Parameters - **metaArgs** (const GMetaArgs &) - Description not provided. - **args** (const GArgs &) - Description not provided. - **state** (GArg &) - Description not provided. - **compileArgs** (const GCompileArgs &) - Description not provided. ### Request Example ```json { "example": "Not available" } ``` ### Response #### Success Response (200) - **void** - Description not provided. #### Response Example ```json { "example": "Not available" } ``` ``` -------------------------------- ### Install OpenCV-Python from Fedora Repositories Source: https://docs.opencv.org/5.0.0-alpha/dd/dd5/tutorial_py_setup_in_fedora.html Installs necessary packages including OpenCV and Numpy using the yum package manager. After installation, verify the setup by importing cv2 and printing its version in a Python interpreter. ```bash $ yum install numpy opencv* ``` ```python >>> import cv2 as cv >>> print( cv.__version__ ) ``` -------------------------------- ### setup() Source: https://docs.opencv.org/5.0.0-alpha/dc/d54/classcv_1_1bioinspired_1_1Retina.html Sets up the retina module using parameters from a FileStorage object. It can optionally apply default settings on failure. ```APIDOC ## cv::bioinspired::Retina::setup() ### Description Sets up the retina module using parameters from a FileStorage object. ### Method virtual void ### Parameters * **_fs** (cv::FileStorage &) - The open Filestorage which contains retina parameters. * **_applyDefaultSetupOnFailure** (const bool) - Set to true if an error must be thrown on error. Defaults to true. ### Python Equivalent ```python cv.bioinspired.Retina.setup([, retinaParameterFile[, applyDefaultSetupOnFailure]]) -> None ``` ``` -------------------------------- ### setup Source: https://docs.opencv.org/5.0.0-alpha/d5/d0a/classcv_1_1bioinspired_1_1RetinaFastToneMapping-members.html Sets up the parameters for the RetinaFastToneMapping algorithm. ```APIDOC ## setup ### Description Sets up the parameters for the RetinaFastToneMapping algorithm. ### Method `virtual void setup(const float photoreceptorsNeighborhoodRadius = 3.f, const float ganglioncellsNeighborhoodRadius = 1.f, const float meanLuminanceModulatorK = 1.f) = 0` ### Parameters * `photoreceptorsNeighborhoodRadius` (float) - The radius of the neighborhood for photoreceptors. Defaults to 3.f. * `ganglioncellsNeighborhoodRadius` (float) - The radius of the neighborhood for ganglion cells. Defaults to 1.f. * `meanLuminanceModulatorK` (float) - The modulator constant for mean luminance. Defaults to 1.f. ``` -------------------------------- ### Execute the OpenCV Installation Script Source: https://docs.opencv.org/5.0.0-alpha/d3/d52/tutorial_windows_install.html Run the previously saved 'installOCV.sh' script from your Git Bash terminal to start the OpenCV build and installation process. ```bash ./installOCV.sh ``` -------------------------------- ### Install Node.js Dependencies Source: https://docs.opencv.org/5.0.0-alpha/d4/da1/tutorial_js_setup.html Navigate to the build directory and install necessary Node.js packages for running tests. ```bash cd build_js/bin npm install ``` -------------------------------- ### Get OpenCV Version Information Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/core/Core.html Retrieves the major, minor, and revision numbers of the installed OpenCV library. ```java System.out.println(Core.VERSION); ``` -------------------------------- ### Get OpenCV Version String Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/core/Core.html Returns the full library version as a string, for example, "3.4.1-dev". ```java public static java.lang.String getVersionString() ``` -------------------------------- ### Sample Command-Line Arguments Source: https://docs.opencv.org/5.0.0-alpha/db/da9/tutorial_aruco_board_detection.html Provides example command-line arguments for running the `detect_board.cpp` sample. These arguments specify board configuration, input video, and camera calibration files. ```cpp Sample video: A full working example is included in the `detect_board.cpp` inside the `samples/cpp/tutorial_code/objectDetection/`. The samples now take input via command line via the `cv::CommandLineParser`. For this file the example parameters will look like: -w=5 -h=7 -l=100 -s=10 -v=/path_to_opencv/opencv/doc/tutorials/objdetect/aruco_board_detection/gboriginal.jpg -c=/path_to_opencv/opencv/samples/cpp/tutorial_code/objectDetection/tutorial_camera_params.yml -cd=/path_to_opencv/opencv/samples/cpp/tutorial_code/objectDetection/tutorial_dict.yml ``` -------------------------------- ### printSetup() Source: https://docs.opencv.org/5.0.0-alpha/dc/d54/classcv_1_1bioinspired_1_1Retina.html Outputs a string containing the current parameters setup of the retina module. ```APIDOC ## cv::bioinspired::Retina::printSetup() ### Description Outputs a string showing the used parameters setup. ### Method virtual String ### Returns A string which contains formatted parameters information. ### Python Equivalent ```python cv.bioinspired.Retina.printSetup() -> retval ``` ``` -------------------------------- ### Java Morphological Lines Detection Setup Source: https://docs.opencv.org/5.0.0-alpha/dd/dd7/tutorial_morph_lines_detection.html This Java code snippet shows the initial setup for image processing in OpenCV. It checks for command-line arguments and loads an image. This is a starting point for more complex image manipulation tasks. ```java import org.opencv.core.*; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; class Morphology_3Run { public void run(String[] args) { // Check number of arguments if (args.length == 0){ System.out.println("Not enough parameters!"); System.out.println("Program Arguments: [image_path]"); System.exit(-1); } ``` -------------------------------- ### ORB Create Method Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/features/ORB.html Creates an ORB detector instance with default parameters. This is a convenient way to get started with ORB. ```java public static ORB create() ``` -------------------------------- ### Get OpenCV Version String Source: https://docs.opencv.org/5.0.0-alpha/db/de0/group__core__utils.html Retrieves the full version string of the OpenCV library, for example, "3.4.1-dev". ```cpp cv::String versionString = cv::getVersionString(); ``` -------------------------------- ### help_init Source: https://docs.opencv.org/5.0.0-alpha/d0/d83/structcv_1_1detail_1_1scratch__helper_3_01true_00_01Impl_00_01Ins_8_8_8_01_4-members.html Initializes the scratch buffer with metadata and input arguments. ```APIDOC ## help_init ### Description Initializes the scratch buffer with metadata and input arguments. ### Method static ### Parameters #### Path Parameters - **metas** (const cv::GMetaArgs &) - Description - **in_args** (const cv::GArgs &) - Description - **b** (gapi::fluid::Buffer &) - Description ``` -------------------------------- ### TickMeter Counter and FPS Methods Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/core/TickMeter.html Gets the number of times the timer has been started and stopped, and calculates the frames per second (FPS). ```java public long getCounter() ``` ```java public double getFPS() ``` -------------------------------- ### setup_impl Source: https://docs.opencv.org/5.0.0-alpha/dd/dc9/structcv_1_1detail_1_1OCVSetupHelper_3_01Impl_00_01std_1_1tuple_3_01Ins_8_8_8_01_4_01_4-members.html Internal implementation for setting up the OpenCV environment. ```APIDOC ## setup_impl ### Description Internal implementation function for setting up the OpenCV environment. It handles the details of extracting metadata and state for the setup process. ### Method static ### Parameters - **metaArgs** (const GMetaArgs &) - Metadata arguments for the setup. - **args** (const GArgs &) - General arguments for the setup. - **state** (GArg &) - The current state object. - **compileArgs** (const GCompileArgs &) - Compilation arguments. - **detail::Seq< IIs... >** - Sequence of indices for template parameter deduction. ### Request Example ```json { "example": "Not available" } ``` ### Response #### Success Response (200) - **decltype(...)** - The return type is deduced based on the Impl::setup call, typically void. #### Response Example ```json { "example": "Not available" } ``` ``` -------------------------------- ### Python SVM Setup Source: https://docs.opencv.org/5.0.0-alpha/d1/d73/tutorial_introduction_to_svm.html Imports necessary libraries for OpenCV and NumPy operations in Python. This is a common starting point for computer vision tasks. ```Python import cv2 as cv import numpy as np ``` -------------------------------- ### setup(String retinaParameterFile, boolean applyDefaultSetupOnFailure) Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/bioinspired/Retina.html Attempts to load retina parameters from an XML file. If the file is not found, default settings are applied. Exceptions are thrown if the XML file is invalid. ```APIDOC ## setup ### Description Try to open an XML retina parameters file to adjust current retina instance setup. If the xml file does not exist, then default setup is applied. Warning, Exceptions are thrown if read XML file is not valid. You can retrieve the current parameters structure using the method Retina::getParameters and update it before running method Retina::setup. ### Parameters - `retinaParameterFile` (String) - the parameters filename - `applyDefaultSetupOnFailure` (boolean) - set to true if an error must be thrown on error ``` -------------------------------- ### Get Tick Count for Performance Timing Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/core/Core.html Returns the number of clock ticks since the program started. This can be used in conjunction with `getTickFrequency()` for performance measurements. ```java public static long getTickCount() ``` -------------------------------- ### setup(String retinaParameterFile) Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/bioinspired/Retina.html Attempts to load retina parameters from an XML file. If the file is not found, default settings are applied. Exceptions are thrown if the XML file is invalid. ```APIDOC ## setup ### Description Try to open an XML retina parameters file to adjust current retina instance setup. If the xml file does not exist, then default setup is applied. Warning, Exceptions are thrown if read XML file is not valid. You can retrieve the current parameters structure using the method Retina::getParameters and update it before running method Retina::setup. ### Parameters - `retinaParameterFile` (String) - the parameters filename ``` -------------------------------- ### Stitching Images (Python) Source: https://docs.opencv.org/5.0.0-alpha/examples.html Python example for image stitching using OpenCV. This snippet shows the basic setup for creating a panorama from a list of images. ```python import cv2 import numpy as np # Load images images = [] # ... load images into the 'images' list ... # Create a Stitcher object stitcher = cv2.Stitcher_create(cv::Stitcher::PANORAMA) # Stitch images (status, pano) = stitcher.stitch(images) if status == cv2.Stitcher_OK: # ... process the stitched panorama 'pano' ... cv2.imshow("Stitched Image", pano) cv2.waitKey(0) cv2.destroyAllWindows() else: print("Stitching failed") ``` -------------------------------- ### Initialize GrabCut Application Source: https://docs.opencv.org/5.0.0-alpha/d8/d34/samples_2cpp_2grabcut_8cpp-example.html Sets up the GrabCut application with an image and window name, then displays the initial image. ```cpp GCApplication gcapp; static void on_mouse( int event, int x, int y, int flags, void* param ) { gcapp.mouseClick( event, x, y, flags, param ); } int main( int argc, char** argv ) { cv::CommandLineParser parser(argc, argv, "{@input| messi5.jpg |}"); help(argv); string filename = parser.get("@input"); if( filename.empty() ) { cout << "\nDurn, empty filename" << endl; return 1; } Mat image = imread(samples::findFile(filename), IMREAD_COLOR); if( image.empty() ) { cout << "\n Durn, couldn't read image filename " << filename << endl; return 1; } const string winName = "image"; namedWindow( winName, WINDOW_AUTOSIZE ); setMouseCallback( winName, on_mouse, 0 ); gcapp.setImageAndWinName( image, winName ); gcapp.showImage(); for(;;) { char c = (char)waitKey(0); switch( c ) { case '\x1b': cout << "Exiting ..." << endl; goto exit_main; case 'r': cout << endl; gcapp.reset(); gcapp.showImage(); break; case 'n': int iterCount = gcapp.getIterCount(); cout << "<" << iterCount << "... "; int newIterCount = gcapp.nextIter(); if( newIterCount > iterCount ) { gcapp.showImage(); cout << iterCount << ">" << endl; } else cout << "rect must be determined>" << endl; break; } } exit_main: destroyWindow( winName ); return 0; } ``` -------------------------------- ### OpenCV Hello World C++ Example Source: https://docs.opencv.org/5.0.0-alpha/d7/d16/tutorial_linux_eclipse.html A basic C++ program that uses OpenCV to display 'Hello World!' in a window. Ensure OpenCV is installed and configured. ```cpp #include using namespace cv; int main ( int argc, char **argv ) { Mat img(480, 640, CV_8U); putText(img, "Hello World!", Point( 200, 400 ), FONT_HERSHEY_SIMPLEX | FONT_ITALIC, 1.0, Scalar( 255, 255, 0 )); imshow("My Window", img); waitKey(); return 0; } ``` -------------------------------- ### printSetup Source: https://docs.opencv.org/5.0.0-alpha/javadoc/org/opencv/bioinspired/Retina.html Outputs a string containing the currently used parameters setup in a formatted manner. ```APIDOC ## printSetup ### Description Outputs a string showing the used parameters setup. ### Returns - String: a string which contains formatted parameters information ``` -------------------------------- ### Command Line Parser Setup Source: https://docs.opencv.org/5.0.0-alpha/db/db6/samples_2cpp_2tutorial_code_2features_2Homography_2homography_from_camera_displacement_8cpp-example.html Defines command-line parameters for the homography tutorial, including image paths, intrinsics file, and chessboard dimensions. ```cpp const char* params = "{ help h | | print usage }" "{ image1 | left02.jpg | path to the source chessboard image }" "{ image2 | left01.jpg | path to the desired chessboard image }" "{ intrinsics | left_intrinsics.yml | path to camera intrinsics }" "{ width bw | 9 | chessboard width }" "{ height bh | 6 | chessboard height }" "{ square_size | 0.025 | chessboard square size }"; ``` -------------------------------- ### C++ Geometric Drawing Example Source: https://docs.opencv.org/5.0.0-alpha/d3/d96/tutorial_basic_geometric_drawing.html Demonstrates drawing various geometric shapes using OpenCV's C++ API. Includes setup for image display and window management. ```cpp #include #include #include #define w 400 using namespace cv; void MyEllipse( Mat img, double angle ); void MyFilledCircle( Mat img, Point center ); void MyPolygon( Mat img ); void MyLine( Mat img, Point start, Point end ); int main( void ){ char atom_window[] = "Drawing 1: Atom"; char rook_window[] = "Drawing 2: Rook"; Mat atom_image = Mat::zeros( w, w, CV_8UC3 ); Mat rook_image = Mat::zeros( w, w, CV_8UC3 ); MyEllipse( atom_image, 90 ); MyEllipse( atom_image, 0 ); MyEllipse( atom_image, 45 ); MyEllipse( atom_image, -45 ); MyFilledCircle( atom_image, Point( w/2, w/2) ); MyPolygon( rook_image ); rectangle( rook_image, Point( 0, 7*w/8 ), Point( w, w), Scalar( 0, 255, 255 ), FILLED, LINE_8 ); MyLine( rook_image, Point( 0, 15*w/16 ), Point( w, 15*w/16 ) ); MyLine( rook_image, Point( w/4, 7*w/8 ), Point( w/4, w ) ); MyLine( rook_image, Point( w/2, 7*w/8 ), Point( w/2, w ) ); MyLine( rook_image, Point( 3*w/4, 7*w/8 ), Point( 3*w/4, w ) ); imshow( atom_window, atom_image ); moveWindow( atom_window, 0, 200 ); imshow( rook_window, rook_image ); moveWindow( rook_window, w, 200 ); waitKey( 0 ); return(0); } void MyEllipse( Mat img, double angle ) { int thickness = 2; int lineType = 8; ellipse( img, Point( w/2, w/2 ), Size( w/4, w/16 ), angle, 0, 360, Scalar( 255, 0, 0 ), thickness, lineType ); } void MyFilledCircle( Mat img, Point center ) { circle( img, center, w/32, Scalar( 0, 0, 255 ), FILLED, LINE_8 ); } void MyPolygon( Mat img ) { int lineType = LINE_8; Point rook_points[1][20]; rook_points[0][0] = Point( w/4, 7*w/8 ); rook_points[0][1] = Point( 3*w/4, 7*w/8 ); rook_points[0][2] = Point( 3*w/4, 13*w/16 ); rook_points[0][3] = Point( 11*w/16, 13*w/16 ); rook_points[0][4] = Point( 19*w/32, 3*w/8 ); rook_points[0][5] = Point( 3*w/4, 3*w/8 ); rook_points[0][6] = Point( 3*w/4, w/8 ); rook_points[0][7] = Point( 26*w/40, w/8 ); rook_points[0][8] = Point( 26*w/40, w/4 ); rook_points[0][9] = Point( 22*w/40, w/4 ); rook_points[0][10] = Point( 22*w/40, w/8 ); rook_points[0][11] = Point( 18*w/40, w/8 ); rook_points[0][12] = Point( 18*w/40, w/4 ); rook_points[0][13] = Point( 14*w/40, w/4 ); rook_points[0][14] = Point( 14*w/40, w/8 ); rook_points[0][15] = Point( w/4, w/8 ); rook_points[0][16] = Point( w/4, 3*w/8 ); rook_points[0][17] = Point( 13*w/32, 3*w/8 ); rook_points[0][18] = Point( 5*w/16, 13*w/16 ); rook_points[0][19] = Point( w/4, 13*w/16 ); const Point* ppt[1] = { rook_points[0] }; int npt[] = { 20 }; fillPoly( img, ppt, npt, 1, Scalar( 255, 255, 255 ), lineType ); } void MyLine( Mat img, Point start, Point end ) { int thickness = 2; int lineType = LINE_8; line( img, start, end, Scalar( 0, 0, 0 ), thickness, lineType ); } ``` -------------------------------- ### Command Line Execution Example Source: https://docs.opencv.org/5.0.0-alpha/dd/d6e/tutorial_windows_visual_studio_opencv.html This example shows how to run an executable with command-line arguments from the Windows command prompt. Navigate to the executable's directory and provide the argument, such as an image file name. ```bash D: CD OpenCV\MySolutionName\Release MySolutionName.exe exampleImage.jpg ``` -------------------------------- ### Minimal OpenCV.js Node.js Example Source: https://docs.opencv.org/5.0.0-alpha/dc/de6/tutorial_js_nodejs.html This snippet shows the basic setup for running OpenCV.js in Node.js. It defines the `Module.onRuntimeInitialized` callback and loads the `opencv.js` library using Node.js's `require` function. ```javascript Module = { onRuntimeInitialized() { // this is our application: console.log(cv.getBuildInformation()) } } // Load 'opencv.js' assigning the value to the global variable 'cv' cv = require('./opencv.js') ``` -------------------------------- ### Prepare Build Directory Source: https://docs.opencv.org/5.0.0-alpha/d2/de6/tutorial_py_setup_in_ubuntu.html Create a 'build' directory within the downloaded 'opencv' folder and navigate into it. This directory will be used for the build process. ```bash mkdir build ``` ```bash cd build ``` -------------------------------- ### Java Dense Optical Flow Initialization Source: https://docs.opencv.org/5.0.0-alpha/d4/dee/tutorial_optical_flow.html Initializes video capture and converts the first frame to grayscale for dense optical flow computation. This is the setup part of the Java optical flow example. ```java import java.util.ArrayList; import org.opencv.core.*; import org.opencv.highgui.HighGui; import org.opencv.imgproc.Imgproc; import org.opencv.video.Video; import org.opencv.videoio.VideoCapture; class OptFlowDense { public void run(String[] args) { String filename = args[0]; VideoCapture capture = new VideoCapture(filename); if (!capture.isOpened()) { //error in opening the video input System.out.println("Unable to open file!"); System.exit(-1); } Mat frame1 = new Mat() , prvs = new Mat(); capture.read(frame1); Imgproc.cvtColor(frame1, prvs, Imgproc.COLOR_BGR2GRAY); while (true) { ``` -------------------------------- ### Run Retina Tutorial with Webcam Source: https://docs.opencv.org/5.0.0-alpha/d3/d86/tutorial_bioinspired_retina_model.html Execute the compiled retina tutorial program to process live video from a webcam. Add 'log' as the last parameter for spatial log sampling. ```bash ./Retina_tuto -video ``` -------------------------------- ### Serve Build Directory for Browser Tests Source: https://docs.opencv.org/5.0.0-alpha/d4/da1/tutorial_js_setup.html Launch a local web server in the build output directory to serve test files. This command uses `npx http-server` and assumes Node.js is installed. ```bash npx http-server build_js/bin ``` -------------------------------- ### Read Specific Number of KeyPoints from HDF5 Source: https://docs.opencv.org/5.0.0-alpha/d3/d23/classcv_1_1hdf_1_1HDF5.html This example shows how to read a specific count of KeyPoints from an HDF5 dataset, starting at a given offset. It's useful for retrieving subsets of data efficiently. ```cpp // open hdf5 file cv::Ptr h5io = cv::hdf::open( "mytest.h5" ); // blank KeyPoint container std::vector keypoints; // read three keypoints starting second one h5io->kpread( keypoints, "keypoints", 1, 3 ); // release h5io->close(); ``` -------------------------------- ### Intelligent Scissors Example Source: https://docs.opencv.org/5.0.0-alpha/d9/df5/tutorial_js_intelligent_scissors.html Launches an interactive Intelligent Scissors tool. Click on the image to pick a source point, then hover to specify a target point candidate. The code can be modified in the textarea for further investigation. Requires 'Start' button click to launch. ```javascript let canvas = new cv.Mat(); let ctx = canvas.getContext('2d'); let img = cv.imread('canvasInput'); ctx.drawImage(img.data, img.cols, img.rows); img.delete(); let scissors = new cv.segmentation.IntelligentScissorsMB(img, 10, 10); let dst = new cv.Mat(); let mask = new cv.Mat(); let point = new cv.Point(x, y); scissors.set(point, mask, dst); scissors.advance(point, mask, dst); scissors.advanceAndGrow(point, mask, dst); scissors.advanceAndShrink(point, mask, dst); scissors.forward(mask, dst); scissors.backward(mask, dst); scissors.grow(mask, dst); scissors.shrink(mask, dst); scissors.getContour(dst); scissors.getMask(mask); scissors.clearPath(); scissors.clear(); scissors.delete(); ``` -------------------------------- ### Retrieve Depth and BGR Images using grab/retrieve Source: https://docs.opencv.org/5.0.0-alpha/d7/d6f/tutorial_kinect_openni.html This example shows how to use VideoCapture::grab and VideoCapture::retrieve to get both the depth map and the BGR image from a depth sensor. It initializes the capture object and then continuously grabs and retrieves the specified data maps. ```cpp VideoCapture capture(0); // or CAP_OPENNI2 for(;;) { Mat depthMap; Mat bgrImage; capture.grab(); capture.retrieve( depthMap, CAP_OPENNI_DEPTH_MAP ); capture.retrieve( bgrImage, CAP_OPENNI_BGR_IMAGE ); if( waitKey( 30 ) >= 0 ) break; } ``` -------------------------------- ### cv::detail::OCVSetupHelper::setup_impl Source: https://docs.opencv.org/5.0.0-alpha/d3/d2a/structcv_1_1detail_1_1OCVSetupHelper_3_01Impl_00_01std_1_1tuple_3_01Ins_8_8_8_01_4_01_4.html Internal implementation helper for the setup method. This is typically not called directly by users. ```APIDOC ## template static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, GArg &state, const GCompileArgs &, detail::Seq< IIs... >) -> decltype(Impl::setup(detail::get_in_meta< Ins >(metaArgs, args, IIs)..., std::declval< typename std::add_lvalue_reference< std::shared_ptr< typename Impl::State > >::type >()), void()) ### Description This is the first overload of the internal setup implementation. It is responsible for invoking the `Impl::setup` method with specific arguments derived from the input metadata and arguments, and a reference to the state object. ### Parameters - **metaArgs** (const GMetaArgs &) - Metadata for the operation. - **args** (const GArgs &) - Arguments for the operation. - **state** (GArg &) - The state object to be configured. - **compileArgs** (const GCompileArgs &) - Compilation arguments (unused in this overload). - **detail::Seq< IIs... >** - A sequence of integers used for parameter expansion. ``` ```APIDOC ## template static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, GArg &state, const GCompileArgs &compileArgs, detail::Seq< IIs... >) -> decltype(Impl::setup(detail::get_in_meta< Ins >(metaArgs, args, IIs)..., std::declval< typename std::add_lvalue_reference< std::shared_ptr< typename Impl::State > >::type >(), compileArgs), void()) ### Description This is the second overload of the internal setup implementation. It is similar to the first overload but also passes the `compileArgs` to the `Impl::setup` method, allowing for more detailed compilation-time configuration. ### Parameters - **metaArgs** (const GMetaArgs &) - Metadata for the operation. - **args** (const GArgs &) - Arguments for the operation. - **state** (GArg &) - The state object to be configured. - **compileArgs** (const GCompileArgs &) - Compilation arguments for the kernel. - **detail::Seq< IIs... >** - A sequence of integers used for parameter expansion. ``` -------------------------------- ### Set Image Generator Output Mode and Get FPS Source: https://docs.opencv.org/5.0.0-alpha/d7/d6f/tutorial_kinect_openni.html This example demonstrates how to set the output mode for the image generator of a depth sensor and retrieve its current frames per second (FPS). It uses VideoCapture::set and VideoCapture::get with specific OpenNI flags. ```cpp VideoCapture capture( CAP_OPENNI2 ); capture.set( CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CAP_OPENNI_VGA_30HZ ); cout << "FPS " << capture.get( CAP_OPENNI_IMAGE_GENERATOR+CAP_PROP_FPS ) << endl; ``` -------------------------------- ### printSetup Source: https://docs.opencv.org/5.0.0-alpha/dc/d47/classcv_1_1bioinspired_1_1Retina-members.html Prints the current setup and parameters of the retina model. ```APIDOC ## printSetup ### Description Prints the current setup and parameters of the retina model to the console or log. ### Method `pure virtual` ``` -------------------------------- ### Main Function for Mask Creation Example Source: https://docs.opencv.org/5.0.0-alpha/d3/d10/samples_2cpp_2snippets_2create_mask_8cpp-example.html Initializes the image, window, and mouse callback. It parses command-line arguments for the input image and displays instructions for using the mouse. ```cpp #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include using namespace std; using namespace cv; Mat src, img1, mask, final; Point point; vector pts; int drag = 0; int var = 0; int flag = 0; void mouseHandler(int, int, int, int, void*); int main(int argc, char **argv) { CommandLineParser parser(argc, argv, "{@input | lena.jpg | input image}"); parser.about("This program demonstrates using mouse events\n"); parser.printMessage(); cout << "\n\tleft mouse button - set a point to create mask shape\n" "\tright mouse button - create mask from points\n" "\tmiddle mouse button - reset\n"; String input_image = parser.get("@input"); src = imread(samples::findFile(input_image)); if (src.empty()) { printf("Error opening image: %s\n", input_image.c_str()); return 0; } namedWindow("Source", WINDOW_AUTOSIZE); setMouseCallback("Source", mouseHandler, NULL); imshow("Source", src); waitKey(0); return 0; } ``` -------------------------------- ### Setup Retina Parameters (C++) Source: https://docs.opencv.org/5.0.0-alpha/d2/d94/bioinspired_retina.html Configures the Retina instance using parameters loaded from an XML file or a FileStorage object. A default setup is applied on failure if specified. ```cpp void setup (String retinaParameterFile="", const bool applyDefaultSetupOnFailure=true); void setup (FileStorage &fs, const bool applyDefaultSetupOnFailure=true); void setup (RetinaParameters newParameters); ``` -------------------------------- ### start() Source: https://docs.opencv.org/5.0.0-alpha/d2/d77/classcv_1_1GStreamingCompiled-members.html Starts the stream processing. ```APIDOC ## start() ### Description Starts the execution of the GStreamingCompiled stream. ### Method member function ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response N/A ``` -------------------------------- ### Initialize Video Capture and Image List Source: https://docs.opencv.org/5.0.0-alpha/d5/de7/tutorial_dnn_googlenet.html Sets up video capture from a file, camera, or a list of images. Handles errors if the input cannot be opened. ```cpp VideoCapture cap; vector imageList; size_t currentImageIndex = 0; if (parser.has("input")) { string input = findFile(parser.get("input")); if (isImgList) { bool check = readStringList(samples::findFile(input), imageList); if (imageList.empty() || !check) { cout << "Error: No images found or the provided file is not a valid .yaml or .xml file." << endl; return -1; } } else { // Input is not a directory, try to open as video or image cap.open(input); if (!cap.isOpened()) { cout << "Failed to open the input." << endl; return -1; } } } else { cap.open(0); // Open default camera } ``` -------------------------------- ### Display Help Message Source: https://docs.opencv.org/5.0.0-alpha/dc/da9/tutorial_decode_graycode_pattern.html Provides a help message explaining how to run the example and its required arguments. ```cpp static void help() { cout << "\nThis example shows how to use the \"Structured Light module\" to decode a previously acquired gray code pattern, generating a pointcloud" << "\nCall:\n" << "./example_structured_light_pointcloud \n" << endl; } ``` -------------------------------- ### Install OpenCV Source: https://docs.opencv.org/5.0.0-alpha/d6/d15/tutorial_building_tegra_cuda.html Install the built OpenCV library to the system. Root privileges may be required depending on the installation path. ```bash $ make install ``` -------------------------------- ### cv::detail::OCVSetupHelper::setup Source: https://docs.opencv.org/5.0.0-alpha/d3/d2a/structcv_1_1detail_1_1OCVSetupHelper_3_01Impl_00_01std_1_1tuple_3_01Ins_8_8_8_01_4_01_4.html Static method to set up the G-API kernel state using provided metadata, arguments, and compilation arguments. This is the primary interface for users to call. ```APIDOC ## static void setup(const GMetaArgs &metaArgs, const GArgs &args, GArg &state, const GCompileArgs &compileArgs) ### Description Sets up the kernel state for G-API operations using OpenCV's CPU backend. It takes metadata, arguments, the state object, and compilation arguments to configure the kernel. ### Parameters - **metaArgs** (const GMetaArgs &) - Metadata for the operation. - **args** (const GArgs &) - Arguments for the operation. - **state** (GArg &) - The state object to be configured. - **compileArgs** (const GCompileArgs &) - Compilation arguments for the kernel. ``` -------------------------------- ### Install CMake for Building OpenCV Source: https://docs.opencv.org/5.0.0-alpha/d2/de6/tutorial_py_setup_in_ubuntu.html CMake is required to configure the installation process when compiling OpenCV from source. Install it using apt-get. ```bash sudo apt-get install cmake ``` -------------------------------- ### start Source: https://docs.opencv.org/5.0.0-alpha/d1/d9b/classcv_1_1GStreamingCompiled.html Starts the execution of the streaming pipeline. ```APIDOC ## start () ### Description Start the pipeline execution. ### Method `GAPI_WRAP void start()` ### Parameters None ### Response None ### Response Example ```cpp streaming_compiled_graph.start(); ``` ``` -------------------------------- ### Enable Documentation and Disable Tests/Samples Source: https://docs.opencv.org/5.0.0-alpha/dd/dd5/tutorial_py_setup_in_fedora.html Configure the build to include documentation while excluding tests and sample applications. ```bash cmake -D BUILD_DOCS=ON -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D BUILD_EXAMPLES=OFF .. ``` -------------------------------- ### Verify OpenCV-Python Installation Source: https://docs.opencv.org/5.0.0-alpha/d2/de6/tutorial_py_setup_in_ubuntu.html After installation, run these commands in a Python interpreter to confirm OpenCV is working and to check its version. This is useful for verifying a successful installation. ```python import cv2 as cv print(cv.__version__) ``` -------------------------------- ### Install CMake using Homebrew Source: https://docs.opencv.org/5.0.0-alpha/d0/db2/tutorial_macos_install.html A convenient way to install CMake on macOS using the Homebrew package manager. Ensure Homebrew is installed first. ```bash brew install cmake ```