### Managing Video Capture Properties Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/TYPES_REFERENCE.md Example demonstrating how to get video properties like width, height, and FPS, and how to set properties such as FPS and brightness. ```python import cv2 cap = cv2.VideoCapture('video.mp4') # Read properties width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = cap.get(cv2.CAP_PROP_FPS) frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # Set properties cap.set(cv2.CAP_PROP_FPS, 30) cap.set(cv2.CAP_PROP_BRIGHTNESS, 128) ``` -------------------------------- ### Full Custom Build Process Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md A comprehensive guide to building OpenCV-Python from source, including cloning the repository, configuring build options, building the wheel, and installing it. It covers selecting alternative OpenCV versions and setting custom CMake arguments. ```bash # Clone with submodules git clone --recursive https://github.com/opencv/opencv-python.git cd opencv-python # Optional: Select alternative OpenCV version cd opencv && git checkout && cd .. # Configure build export CMAKE_ARGS="-DWITH_CUDA=ON" export ENABLE_CONTRIB=1 export ENABLE_HEADLESS=0 # Build wheel pip wheel . --verbose # Install the generated wheel pip install opencv_*.whl ``` -------------------------------- ### Install OpenCV-Python on Windows Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Perform a simple installation of OpenCV-Python. If DLL errors occur, ensure the Visual C++ redistributable is installed. ```bash # Simple installation pip install opencv-python # If DLL errors occur, verify Visual C++ is installed # Run: C:\Program Files (x86)\Microsoft Visual Studio\2019\Vc\Redist\MSVC\v142\vc_redist_x64.exe ``` -------------------------------- ### Configure Jupyter Notebook for OpenCV Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install Jupyter and OpenCV within a virtual environment, start the notebook server, and import cv2 in a notebook cell. ```bash # In virtual environment pip install jupyter opencv-python # Start Jupyter jupyter notebook # In notebook cell import cv2 print(cv2.__version__) ``` -------------------------------- ### Source Installation (No Wheel) Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md Installs OpenCV-Python directly from source without generating a wheel package. This can be useful for development or when wheel installation is not desired. ```bash # Build and install directly without wheel pip install --no-binary opencv-python opencv-python # Or force source build even if wheels available pip install --no-binary :all: opencv-python ``` -------------------------------- ### Install OpenCV-Python on Linux Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install OpenCV-Python using pre-built wheels. Alternatively, install the headless version if GUI dependencies are not needed. ```bash # Standard installation (pre-built wheels) pip install opencv-python # Or headless (no GUI dependencies) pip install opencv-python-headless ``` -------------------------------- ### Install Build Dependencies for Source Builds Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install necessary Python packages like NumPy, scikit-build, and setuptools for building OpenCV from source. ```bash pip install scikit-build numpy setuptools ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install the necessary command-line tools for development on macOS. ```bash xcode-select --install ``` -------------------------------- ### Install OpenCV Python Main Modules Source: https://github.com/opencv/opencv-python/blob/4.x/README.md Install the main OpenCV modules for standard desktop environments. This is the recommended package for most users. ```bash pip install opencv-python ``` -------------------------------- ### Version File Format Example Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md An example of the auto-generated `cv2/version.py` file, showing the format and fields that indicate the OpenCV version, build configuration, and release type. ```python opencv_version = "4.8.1.0" contrib = True headless = False rolling = False ci_build = True ``` -------------------------------- ### Install libGL.so.1 on Linux Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install the OpenGL library required for GUI functionalities on Linux systems to resolve related import errors. ```bash # Install missing library sudo apt-get install libgl1-mesa-glx # Or use headless variant (no GUI) pip install opencv-python-headless ``` -------------------------------- ### Inspecting the cv2 Package Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/PACKAGE_STRUCTURE.md Provides examples of how to inspect the installed cv2 package using Python's inspect module to find its file location, list all available symbols, and get the signature of specific functions like cv2.imread. ```python import cv2 import inspect # Get module location print(cv2.__file__) # Path to cv2 package # List all symbols all_symbols = dir(cv2) print(len(all_symbols)) # ~2000+ symbols # Get specific class/function print(inspect.signature(cv2.imread)) ``` -------------------------------- ### Install opencv-python Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/README.md Install the OpenCV package using pip. Choose the appropriate variant based on your needs (e.g., headless for servers). ```bash pip install opencv-python # With contrib modules pip install opencv-contrib-python # Headless (no GUI dependencies) pip install opencv-python-headless # Headless with contrib pip install opencv-contrib-python-headless ``` -------------------------------- ### Install CMake Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md Install CMake if it is not found on your system. This is automatically handled if CMake version 3.5 or higher is not detected. ```bash pip install cmake ``` -------------------------------- ### Run OpenCV Hello World Example Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Create, save, and optionally display a simple image using OpenCV and NumPy to confirm basic functionality and image handling. ```python import cv2 import numpy as np # Create a simple image img = np.zeros((480, 640, 3), dtype=np.uint8) cv2.putText(img, 'OpenCV Works!', (100, 240), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 3) # Save it cv2.imwrite('/tmp/test.jpg', img) print("Test image saved to /tmp/test.jpg") # If you have display capability try: cv2.imshow('Test', img) cv2.waitKey(1) print("Display works!") except Exception as e: print(f"Display not available: {e}") ``` -------------------------------- ### Install OpenCV Variants Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/PROJECT_OVERVIEW.md Use pip to install different variants of the OpenCV library, including standard, contrib, and headless versions. Ensure only one variant is installed at a time to avoid conflicts. ```bash # Standard installation (main modules, GUI) pip install opencv-python # With contrib/extra modules pip install opencv-contrib-python # Headless (no GUI dependencies) pip install opencv-python-headless # Headless + contrib pip install opencv-contrib-python-headless ``` -------------------------------- ### Build OpenCV-Python from Source Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Clone the repository, set environment variables for custom build options (contrib, headless, CUDA), build a wheel, and then install it. ```bash # Clone with submodules git clone --recursive https://github.com/opencv/opencv-python.git cd opencv-python # Optional: Enable contrib modules export ENABLE_CONTRIB=1 # Optional: Build headless (no GUI) export ENABLE_HEADLESS=1 # Optional: Add CMake flags (e.g., CUDA support) export CMAKE_ARGS="-DWITH_CUDA=ON" # Build wheel pip wheel . --verbose # Install the generated wheel pip install opencv_python*.whl ``` -------------------------------- ### Applying Thresholding Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/TYPES_REFERENCE.md Example of applying manual binary thresholding and automatic thresholding using Otsu's method. ```python import cv2 gray = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE) # Manual threshold ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # Automatic threshold (Otsu) ret, binary_otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) ``` -------------------------------- ### Configure VS Code for OpenCV Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Steps to create a virtual environment, activate it, install OpenCV, and select the interpreter within VS Code. ```bash 1. Create .venv virtual environment: ```bash python -m venv .venv ``` 2. Install opencv: ```bash source .venv/bin/activate # or .venv\Scripts\activate pip install opencv-python ``` 3. Select interpreter in VS Code: - `Ctrl+Shift+P` → "Python: Select Interpreter" - Choose `.venv` environment ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Set up a Python environment using Conda, specifying the Python version, activating it, and then installing opencv-python. ```bash # Create conda environment conda create -n opencv_env python=3.11 # Activate conda activate opencv_env # Install opencv-python pip install opencv-python ``` -------------------------------- ### Install OpenCV Python Headless Full Package Source: https://github.com/opencv/opencv-python/blob/4.x/README.md Install the headless version of the full OpenCV package, including main and contrib/extra modules, for server (headless) environments. This is the smallest option for server use. ```bash pip install opencv-contrib-python-headless ``` -------------------------------- ### Bit Depth Conversion Examples Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/api-reference/mat-type-reference.md Provides examples for converting between different bit depths (8-bit, 16-bit, 32-bit float) while preserving or adjusting value ranges. Note the scaling factors used for accurate conversion. ```python # 8-bit to 16-bit (preserve value, extend range) img_16bit = img_8bit.astype(np.uint16) * 257 # 257 = 65535 / 255 # 16-bit to 8-bit (reduce range) img_8bit = (img_16bit / 256).astype(np.uint8) # 8-bit to 32-bit float img_32f = img_8bit.astype(np.float32) / 255.0 # 32-bit float to 8-bit (clip and scale) img_8bit = np.clip(img_32f * 255, 0, 255).astype(np.uint8) ``` -------------------------------- ### Example: Setting CMAKE_ARGS for CUDA and cuDNN Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md Use this environment variable to pass additional arguments to OpenCV's CMake configuration. This example enables CUDA and cuDNN support. ```bash export CMAKE_ARGS="-DWITH_CUDA=ON -DWITH_CUDNN=ON" ``` -------------------------------- ### Install OpenCV Python Full Package Source: https://github.com/opencv/opencv-python/blob/4.x/README.md Install the full OpenCV package, including main modules and contrib/extra modules, for standard desktop environments. Use this if you need additional functionality from the contrib modules. ```bash pip install opencv-contrib-python ``` -------------------------------- ### Install CMake for Building OpenCV Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install CMake, a build system generator, which is required for compiling OpenCV from source. ```bash # Install cmake pip install cmake # Or via system package manager sudo apt-get install cmake # Ubuntu/Debian brew install cmake # macOS ``` -------------------------------- ### Test Basic OpenCV Import and Version Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Verify the OpenCV installation by importing the cv2 module and printing its version and build information. ```python import cv2 print(f"OpenCV version: {cv2.__version__}") print(f"Compiled by: {cv2.getBuildInformation()}") ``` -------------------------------- ### Install Specific OpenCV-Python Version Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install a particular version of opencv-python using version specifiers or list available versions. ```bash pip install opencv-python==4.8.1.0 pip install 'opencv-python>=4.8.0,<4.9.0' pip index versions opencv-python ``` -------------------------------- ### Dockerfile for OpenCV-Python Deployment Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md A sample Dockerfile to set up a Python 3.11 environment with OpenCV installed. It includes necessary system dependencies and installs the headless version of opencv-python, recommended for containerized applications. ```dockerfile FROM python:3.11-slim # Install dependencies RUN apt-get update && apt-get install -y \ libgl1-mesa-glx \ libsm6 \ libxext6 \ && rm -rf /var/lib/apt/lists/* # Install opencv (headless recommended for containers) RUN pip install opencv-python-headless numpy WORKDIR /app COPY . /app CMD ["python", "script.py"] ``` -------------------------------- ### Installing Build Dependencies Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md Installs necessary Python packages for building OpenCV-Python, including pip, numpy, scikit-build, and setuptools. Ensure pip is at least version 19.3. ```bash # Install build dependencies pip install --upgrade pip # 19.3 minimum pip install numpy scikit-build setuptools ``` -------------------------------- ### Install OpenCV Python Headless Main Modules Source: https://github.com/opencv/opencv-python/blob/4.x/README.md Install the headless version of the main OpenCV modules for server (headless) environments. This package avoids GUI dependencies and is smaller. ```bash pip install opencv-python-headless ``` -------------------------------- ### Install OpenCV-Python Build Dependencies on CentOS/RHEL Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install C++ compiler and Python development headers for building OpenCV from source. ```bash # Build dependencies sudo yum install gcc gcc-c++ python3-devel # Optional GUI libraries sudo yum install qt5-qtbase ``` -------------------------------- ### Install OpenCV-Python Variants Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Use pip to install the desired OpenCV-Python package variant. Choose only one package per environment to avoid conflicts. ```bash # Standard (main modules, GUI support) pip install opencv-python # Full (main + contrib modules, GUI support) pip install opencv-contrib-python # Headless standard (main modules, no GUI) pip install opencv-python-headless # Headless full (main + contrib, no GUI) pip install opencv-contrib-python-headless ``` -------------------------------- ### Detecting and Drawing KeyPoints Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/TYPES_REFERENCE.md Example of detecting keypoints in an image using ORB and drawing circles at their locations. ```python import cv2 detector = cv2.ORB_create() keypoints = detector.detect(img, None) for kp in keypoints: x, y = kp.pt size = kp.size angle = kp.angle cv2.circle(img, (int(x), int(y)), int(size/2), (0, 255, 0), 2) ``` -------------------------------- ### Install OpenCV on Ubuntu/Debian Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install OpenCV using the system's package manager on Ubuntu or Debian. This method is not recommended as system packages are often outdated; prefer pip. ```bash # Not recommended - system packages often outdated # Prefer pip instead sudo apt-get install python3-opencv ``` -------------------------------- ### Sobel Gradient Calculation Example Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/api-reference/image-filters-transforms.md Demonstrates calculating the X and Y gradients of a grayscale image using the Sobel operator and then computing the gradient magnitude. The result is scaled for display. ```python import cv2 import numpy as np gray = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE) # X gradient sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5) # Y gradient sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5) # Magnitude magnitude = np.sqrt(sobelx**2 + sobely**2) cv2.imshow('Magnitude', magnitude / magnitude.max() * 255) cv2.waitKey(0) ``` -------------------------------- ### Check and Reinstall OpenCV-Python Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Verify the OpenCV-Python installation and reinstall if necessary to resolve import errors. ```bash # Check installation pip list | grep opencv # Reinstall pip uninstall opencv-python -y pip install opencv-python ``` -------------------------------- ### Example METADATA File Content Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/PACKAGE_STRUCTURE.md Shows the typical metadata found in the METADATA file for the opencv-python package, including version, dependencies, and platform information. ```text Metadata-Version: 2.1 Name: opencv-python Version: 4.8.1.0 Summary: Wrapper package for OpenCV python bindings. Home-page: https://github.com/opencv/opencv-python Author: OpenCV Team License: Apache 2.0 Platform: MacOS Platform: Microsoft :: Windows Platform: POSIX Platform: Unix Requires-Dist: numpy>=2; python_version>="3.9" Requires-Dist: numpy>=1.13.3; python_version<"3.9" ``` -------------------------------- ### Grayscale Histogram Equalization Example Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/api-reference/image-filters-transforms.md Demonstrates histogram equalization on a grayscale image. It reads an image, equalizes its histogram, and displays both the original and equalized images. ```python import cv2 gray = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE) equalized = cv2.equalizeHist(gray) # Compare cv2.imshow('Original', gray) cv2.imshow('Equalized', equalized) cv2.waitKey(0) ``` -------------------------------- ### Install Specific OpenCV-Python Version Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Use this command to install a precise version of the opencv-python package. ```bash pip install opencv-python==4.8.1.0 ``` -------------------------------- ### Install scikit-build and numpy Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md Resolve 'ModuleNotFoundError: No module named 'skbuild'' by installing scikit-build and numpy. ```bash pip install scikit-build numpy ``` -------------------------------- ### Build on Raspberry Pi (Slow Systems) Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md Use this command to build OpenCV-Python on systems like Raspberry Pi, which may take several hours. It's recommended to use precompiled wheels or enable swap if available. Monitor build progress using tail. ```bash # May take several hours # Recommended: Use precompiled wheels if available, or enable swap: pip wheel . --verbose # Monitor build progress tail -f /var/log/build.log # if redirected ``` -------------------------------- ### Remove Conflicting OpenCV-Python Packages Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Uninstall all installed variants of OpenCV-Python to resolve conflicts, then install a single desired version. ```bash # Check for multiple variants pip list | grep opencv # Remove all variants pip uninstall opencv-python opencv-contrib-python opencv-python-headless opencv-contrib-python-headless -y # Install only one pip install opencv-python ``` -------------------------------- ### Save Image to File on Headless Linux Server Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Demonstrates saving an image to a file, which is a viable alternative to `cv2.imshow()` on headless servers. ```python import cv2 img = cv2.imread('image.jpg') cv2.imwrite('output.jpg', img) # Works on headless # cv2.imshow('image', img) # Won't work on headless ``` -------------------------------- ### Basic OpenCV Usage Validation Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md A simple Python script to validate the OpenCV installation after building and installing the wheel. It checks if VideoCapture can be opened. ```python import cv2 cap = cv2.VideoCapture("video.mp4") assert cap.isOpened() ``` -------------------------------- ### Install OpenCV-Python Build Dependencies on Ubuntu/Debian Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Install Python package manager, development headers, and essential build tools for compiling OpenCV from source. ```bash # Build dependencies for source builds sudo apt-get install python3-pip python3-dev build-essential # Optional GUI libraries sudo apt-get install libqt5gui5 libqt5core5a # Optional: CUDA (for GPU acceleration) # Follow NVIDIA's CUDA installation guide ``` -------------------------------- ### Read from Camera and Set Properties Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/COMMON_PATTERNS.md Captures video from the default camera (index 0). Sets camera properties like frame width, height, and FPS. Displays the captured frames and exits on 'q' key press. ```python import cv2 cap = cv2.VideoCapture(0) # 0 = default camera # Set camera properties cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) cap.set(cv2.CAP_PROP_FPS, 30) while True: ret, frame = cap.read() if not ret: break # Process frame cv2.imshow('Camera', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` -------------------------------- ### Install OpenCV-Python to a Specific Location Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Installs the opencv-python package to a custom directory, useful for performance optimization on SSDs. Ensure the target directory is added to your PYTHONPATH. ```bash # Install to specific location pip install --target /fast/ssd/opencv-python opencv-python # Add to PYTHONPATH export PYTHONPATH=/fast/ssd/opencv-python:$PYTHONTON ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Set up a dedicated Python virtual environment using `venv` for isolating project dependencies, including upgrading pip and installing opencv-python. ```bash # Create virtual environment python3 -m venv opencv_env # Activate source opencv_env/bin/activate # Linux/macOS # or opencv_env\Scripts\activate # Windows # Upgrade pip pip install --upgrade pip # Install opencv pip install opencv-python ``` -------------------------------- ### Initialize BFMatcher Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/api-reference/feature-detection.md Initialize the Brute Force Matcher with a specified distance metric (e.g., NORM_HAMMING for ORB/AKAZE, NORM_L2 for SIFT). Optionally enable cross-checking for more reliable matches. ```python import cv2 # For ORB, AKAZE, BRIEF descriptors: bf_hamming = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) # For SIFT, SURF descriptors: bf_l2 = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True) ``` -------------------------------- ### Apply Binary, Otsu, and Adaptive Thresholding Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/COMMON_PATTERNS.md Shows various thresholding methods on grayscale images: simple binary, inverted binary, automatic Otsu's thresholding, and adaptive thresholding for varying lighting conditions. ```python import cv2 import numpy as np gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Binary threshold ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # Inverted binary threshold ret, thresh_inv = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV) # Automatic threshold (Otsu) ret, thresh_otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) # Adaptive threshold adaptive = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) ``` -------------------------------- ### Drawing Keypoints and Orientation Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/api-reference/feature-detection.md Demonstrates how to draw keypoints and their orientation on an image using the properties of the KeyPoint object. ```python for kp in keypoints: x, y = kp.pt size = kp.size angle = kp.angle # Draw keypoint cv2.circle(img, (int(x), int(y)), int(size/2), (0, 255, 0), 2) # Draw orientation end_x = int(x + size * 0.5 * np.cos(np.radians(angle))) end_y = int(y + size * 0.5 * np.sin(np.radians(angle))) cv2.line(img, (int(x), int(y)), (end_x, end_y), (0, 0, 255), 2) ``` -------------------------------- ### GUI Configuration with Qt5 on Linux Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md Enables building OpenCV with Qt5 support on Linux when not in headless mode. This is typically used for applications requiring a graphical user interface. ```cmake -DWITH_QT=5 # Build with Qt 5 (CI builds) ``` -------------------------------- ### Drawing with a Point Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/TYPES_REFERENCE.md Example of drawing a circle using a point tuple for its center coordinates. ```python # Example cv2.circle(img, (100, 50), 5, (0, 255, 0), -1) ``` -------------------------------- ### Enable OpenCL Support in Build Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/BUILD_CONFIGURATION.md Configures the build to enable OpenCL support, allowing OpenCV to utilize OpenCL-compatible devices for accelerated computation. ```bash export CMAKE_ARGS="-DWITH_OPENCL=ON" pip wheel . --verbose ``` -------------------------------- ### Import OpenCV Source: https://github.com/opencv/opencv-python/blob/4.x/README.md Import the OpenCV library after installation. The package is imported using the alias 'cv2'. ```python import cv2 ``` -------------------------------- ### Basic Image Loading, Display, and Processing Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/README.md Load an image, display it, perform basic grayscale conversion and blurring, and save the result. Ensure 'image.jpg' exists. ```python import cv2 # Load image img = cv2.imread('image.jpg') # Display cv2.imshow('Image', img) cv2.waitKey(0) cv2.destroyAllWindows() # Simple processing gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) # Save result cv2.imwrite('output.jpg', blurred) ``` -------------------------------- ### Drawing a Rectangle Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/TYPES_REFERENCE.md Example of drawing a rectangle using its (x, y, width, height) tuple representation. ```python # Example x, y, w, h = rect cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) ``` -------------------------------- ### Build Wheel Package Source: https://github.com/opencv/opencv-python/blob/4.x/README.md Use pip wheel to build the package from the current directory. Ensure you have the latest pip version installed, as this command replaces the older setup.py bdist_wheel. ```bash pip wheel . --verbose ``` -------------------------------- ### Rendering Text with Fonts Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/TYPES_REFERENCE.md Example of rendering text using a regular font and an italicized font. ```python import cv2 img = cv2.imread('image.jpg') # Regular font cv2.putText(img, 'Text', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2) # Italic font cv2.putText(img, 'Italic', (50, 100), cv2.FONT_HERSHEY_SIMPLEX | cv2.FONT_ITALIC, 1.0, (255, 255, 255), 2) ``` -------------------------------- ### Feature Matching with SIFT and BFMatcher Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INDEX.md Example of using SIFT for feature detection and description, followed by Brute-Force Matcher (BFMatcher) to find good matches between two images using Lowe's ratio test. ```python sift = cv2.SIFT_create() kp1, des1 = sift.detectAndCompute(img1, None) kp2, des2 = sift.detectAndCompute(img2, None) bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2, k=2) # Apply Lowe's ratio test good = [m for m,n in matches if m.distance < 0.7*n.distance] ``` -------------------------------- ### Upgrade OpenCV-Python to Latest Version Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/INSTALLATION_AND_CONFIG.md Update the installed OpenCV-Python package to the most recent stable release available on PyPI. ```bash pip install --upgrade opencv-python ``` -------------------------------- ### Drawing Shapes with Styles Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/TYPES_REFERENCE.md Example of drawing a filled circle and an anti-aliased line using specified drawing styles. ```python import cv2 img = cv2.imread('image.jpg') # Filled circle (anti-aliased) cv2.circle(img, (100, 100), 50, (0, 255, 0), cv2.FILLED) # Anti-aliased line cv2.line(img, (0, 0), (100, 100), (255, 0, 0), 2, cv2.LINE_AA) ``` -------------------------------- ### Get Image Shape and Dimensions Source: https://github.com/opencv/opencv-python/blob/4.x/_autodocs/api-reference/mat-type-reference.md Retrieve the height, width, and number of channels of an image using the `.shape` attribute. ```python import cv2 img = cv2.imread('image.jpg') height, width = img.shape[:2] # Get spatial dimensions channels = 1 if len(img.shape) == 2 else img.shape[2] # Get channel count # Complete shape rows, cols, channels = img.shape # For color image rows, cols = img.shape # For grayscale ```