Using OpenCV (v1.5)

Updated at:
Copy as MD

1. Overview

The PPU SDK is compatible with OpenCV hardware acceleration. The verified OpenCV version is 4.10.

Based on OpenCV 4.10, the opencv_contrib_python-4.10.0.84 package, which includes hardware acceleration, is available in the SAIL pip repository. You can install it directly by running:

pip install opencv-contrib-python==4.10.0.84

This document explains how to build your own custom OpenCV and opencv-python packages with hardware acceleration.

Note

Before you install or build the OpenCV and opencv-python packages with hardware acceleration, uninstall any existing OpenCV and opencv-python packages from your environment.

2. Build and install OpenCV

2.1 Download the source code

opencv_build.sh

    git clone --branch 4.10.0 --depth 1 https://github.com/opencv/opencv.git
    git clone --branch 4.10.0 --depth 1 https://github.com/opencv/opencv_contrib.git
    git clone --branch 4.10.0 --depth 1 https://github.com/opencv/opencv_extra.git
    
    cd opencv
    ln -sf ../opencv_contrib opencv_contrib

2.2 Prepare the build script

Before compiling, ensure that you have installed the PPU SDK and run the envsetup.sh script to configure the SDK environment.

The following script removes selected modules and enables as many CUDA acceleration modules as possible. You can customize the script to meet your requirements:

build_opencv.sh

mkdir build
cd build

cmake_option=""

# Configure the modules to skip. The list provided is an example; you can modify it as needed.
SKIP_LIST=(xfeatures2d matlab xobjdetect xphoto wechat_qrcode)  
SKIP_DEFINES=''
for m in ${SKIP_LIST[@]}; do
    SKIP_DEFINES+=" -DBUILD_opencv_${m}=OFF"
done
cmake_option+=" ${SKIP_DEFINES}"

# Add required modules. This configuration enables as many CUDA-accelerated modules as possible.
ENABLE_LIST=(legacy ximgproc cudev cudastereo cudaarithm cudaimgproc cudacodec cudafilters cudawarping cudaoptflow cudabgsegm cudafeatures2d cudaobjdetect cudalegacy)
ENABLE_DEFINES=''
for m in ${ENABLE_LIST[@]}; do
    ENABLE_DEFINES+=" -DBUILD_opencv_${m}=ON"
done
cmake_option+=" -DWITH_CUDA=ON -DWITH_CUDNN=ON -DWITH_CUBLAS=ON -DWITH_CUFFT=ON -DOPENCV_DNN_CUDA=ON -DCUDA_ARCH_BIN=80 -DWITH_NVCUVID=ON"
cmake_option+=" -DOPENCV_ENABLE_NONFREE=ON"
cmake_option+=" ${ENABLE_DEFINES}"

# Disable some non-essential options. You can re-enable them if needed.
cmake_option+=" -DWITH_OPENCL=OFF -DOPENCV_DNN_OPENCL=OFF"
cmake_option+=" -DWITH_ANDROID_MEDIANDK=OFF -DWITH_GTK=OFF -DWITH_IPP=OFF -DBUILD_JAVA=OFF"
cmake_option+=" -DWITH_V4L=OFF -DWITH_GSTREAMER=OFF -DWITH_1394=OFF"

# Specify the location of opencv_contrib. This path assumes it is a sibling of the opencv directory.
cmake_option+=" -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules/"

# Specify the installation directory, one level above the source directory. If not specified, make install defaults to /usr/local.
cmake_option+="-DOPENCV_GENERATE_PKGCONFIG -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=../"

2.3 Configure FFmpeg support

If FFmpeg is not installed on your system, simply enabling the -DWITH_FFMPEG=ON flag during configuration is not sufficient for the build system to find it. As a result, the final libopencv_videoio.so library will not include FFmpeg support.

For instructions on building and using FFmpeg, see the Video FFmpeg User Guide.

Assuming your FFmpeg installation directory is FFMPEG_PATH, add the following to the build_opencv.sh script:

export PKG_CONFIG_LIBDIR=$FFMPEG_PATH/lib/pkgconfig:$PKG_CONFIG_LIBDIR
cmake_option+=" -DWITH_FFMPEG=ON -DOPENCV_FFMPEG_USE_FIND_PACKAGE=ON -DOPENCV_FFMPEG_SKIP_BUILD_CHECK=ON -DFFMPEG_DIR=./"

A successful configuration produces output similar to the following. The version number after YES reflects your local FFmpeg version.

--   Video I/O:
--     FFMPEG:                      YES (find_package)
--       avcodec:                   YES (60.31.102)
--       avformat:                  YES (60.16.100)
--       avutil:                    YES (58.29.100)
--       swscale:                   YES (7.5.100)
--       avresample:                NO

Set the FFmpeg directory to the installation directory of your FFmpeg build with hardware acceleration.

2.4 Configure test cases and samples

To build and install the built-in OpenCV test cases and test data, add the following options. This step is optional.

cmake_option+=" -DBUILD_PERF_TESTS=ON -DBUILD_TESTS=ON -DINSTALL_TESTS=ON -DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata"

Here, opencv_extra is the directory containing the test data, which you previously cloned from GitHub.

2.5 Build

build_opencv.sh

cmake $cmake_option ..
make -j && make install

2.6 Run samples

Navigate to the bin directory within your installation path:

cd ../bin
export LD_LIBRARY_PATH=$FFMPEG_PATH/lib:../lib:$LD_LIBRARY_PATH  # Add the FFmpeg and OpenCV library directories to LD_LIBRARY_PATH
export OPENCV_TEST_DATA_PATH=../share/opencv4/testdata  # testdata is the directory obtained from git clone https://github.com/opencv/opencv_extra.git

You can now run the native test programs.

3. Build and install opencv-python

3.1 Download the source code

git clone --branch 84 --depth 1 https://github.com/opencv/opencv-python.git

Since you built OpenCV 4.10 in the previous section, you need to download the corresponding opencv-python version.

3.2 Modify setup.py

You can reuse the opencv and opencv_contrib source code from Section 2.1 instead of downloading them again.

cd opencv-python
rm opencv opencv_contrib opencv_extra multibuild -r
# Assume that opencv-python, opencv, and opencv_contrib are in the same parent directory
ln -sf ../opencv opencv
ln -sf ../opencv_contrib opencv_contrib
ln -sf ../opencv_extra opencv_extra
git clone https://github.com/multi-build/multibuild.git

Modify the setup.py file to disable automatic Git submodule updates and to customize the build options. The options are similar to those in Section 2.2 and can be adjusted to fit your requirements:

-    if os.path.exists(".git"):
-        import pip._internal.vcs.git as git
-        g = git.Git()  # NOTE: pip API's are internal, this has to be refactored
-        g.run_command(["submodule", "sync"])
-        if build_rolling:
-            g.run_command(
-                ["submodule", "update", "--init", "--recursive", "--remote", cmake_source_dir]
-            )
-            if build_contrib:
-                g.run_command(
-                    ["submodule", "update", "--init", "--recursive", "--remote", "opencv_contrib"]
-                )
-        else:
-            g.run_command(
-                ["submodule", "update", "--init", "--recursive", cmake_source_dir]
-            )
-
-            if build_contrib:
-                g.run_command(
-                    ["submodule", "update", "--init", "--recursive", "opencv_contrib"]
-                )

... ...

             "-DBUILD_OPENEXR=ON",
+            "-DWITH_OPENCL=OFF",
+            "-DOPENCV_DNN_OPENCL=OFF",
+            "-DWITH_FFMPEG=ON",
+            "-DOPENCV_FFMPEG_USE_FIND_PACKAGE=ON",
+            "-DOPENCV_FFMPEG_SKIP_BUILD_CHECK=ON",
+            "-DFFMPEG_DIR=/usr/local", # Replace this with the installation directory of your FFmpeg build with hardware acceleration
+            "-DWITH_CUDA=ON",
+            "-DWITH_CUDNN=ON",
+            "-DWITH_CUBLAS=ON",
+            "-DWITH_CUFFT=ON",
+            "-DOPENCV_DNN_CUDA=ON",
+            "-DCUDA_ARCH_BIN=80",
+            "-DWITH_V4L=OFF",
+            "-DWITH_GSTREAMER=OFF",
+            "-DWITH_1394=OFF",
+            "-DWITH_ANDROID_MEDIANDK=OFF",
+            "-DWITH_GTK=OFF",
+            "-DWITH_IPP=OFF",
+            "-DBUILD_JAVA=OFF",
+            "-DWITH_VTK=OFF",
+            "-DENABLE_FLAKE8=OFF",
+            "-DENABLE_PYLINT=OFF",
+            "-DBUILD_opencv_legacy=ON",
+            "-DOPENCV_ENABLE_NONFREE=ON",
+            "-DBUILD_opencv_xfeatures2d=OFF",
+            "-DBUILD_opencv_matlab=OFF",
+            "-DBUILD_opencv_xobjdetect=OFF",
+            "-DBUILD_opencv_xphoto=OFF",
+            "-DBUILD_opencv_wechat_qrcode=OFF",
+            "-DBUILD_opencv_ximgproc=ON",
+            "-DBUILD_opencv_cudev=ON",
+            "-DBUILD_opencv_cudastereo=ON",
+            "-DBUILD_opencv_cudaarithm=ON",
+            "-DBUILD_opencv_cudaimgproc=ON",
+            "-DBUILD_opencv_cudacodec=ON",
+            "-DBUILD_opencv_cudafilters=ON",
+            "-DBUILD_opencv_cudawarping=ON",
+            "-DBUILD_opencv_cudaoptflow=ON",
+            "-DBUILD_opencv_cudabgsegm=ON",
+            "-DBUILD_opencv_cudafeatures2d=ON",
+            "-DBUILD_opencv_cudaobjdetect=ON",
+            "-DBUILD_opencv_cudalegacy=ON",
+            "-DOPENCV_GENERATE_PKGCONFIG=ON"
        ]

3.3 Build

This build requires scikit-build. You can install it by running pip install scikit-build.

export ENABLE_CONTRIB=1
python3 setup.py bdist_wheel

3.4 Install

The generated wheel file, opencv_contrib_python-4.10.0.84-cp37-cp37m-linux_x86_64.whl, is in the dist/ directory.

pip install dist/opencv_contrib_python-4.10.0.84-cp37-cp37m-linux_x86_64.whl

To verify the installation, open a Python interactive shell and run import cv2. A successful import verifies the installation.

4. Known issues

  • cuBLAS:

    • GEMM: cublasCgemm_v2 is not supported.

  • cuFFT:

    • Dft/Convolve: cufftPlan2d is not supported.

  • Cudacodec:

    • Older video formats such as MPEG4, MPEG2, VC1, and VP8 are not supported.

  • Cudaoptflow:

    • Some test cases fail because the PPU lacks optical flow hardware.

In addition, a small number of native test cases may fail when run on the PPU. These failures are safe to ignore and typically fall into one of the following categories:

  • Minor discrepancies in floating-point precision that fall within the acceptable ULP (Unit in the Last Place) tolerance. Some of these tests also fail on NVIDIA A100 GPUs.

  • Results differ due to uninitialized variables within a kernel or allocated device memory that was not cleared to zero. In NVIDIA environments, local variables and allocated device memory are often zero-initialized by default, whereas on the PPU they are not.

  • Results differ due to different underlying operators or algorithms.

5. Usage example

This example demonstrates how to use opencv-python with Ultralytics YOLOv5 to enable hardware acceleration for preprocessing and post-processing in an object detection model inference pipeline.

https://github.com/ultralytics/yolov5.git

To enable PPU hardware acceleration for video decoding during preprocessing, you must explicitly use FFmpeg for video capture and set the cuvid hardware acceleration options, as the following code shows:

object_tracking.py

+os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "hwaccel;cuvid|video_codec;h264_cuvid|vsync;0"
-cap = cv2.VideoCapture(path)
+cap = cv2.VideoCapture(path, cv2.CAP_FFMPEG)

For post-processing, cv2.VideoWriter uses FFmpeg for video encoding by default. If you have configured FFmpeg with hardware acceleration as described in this guide, hardware encoding is enabled automatically, and no code changes are required:

object_tracking.py

result = cv2.VideoWriter("object_tracking.mp4",
                       cv2.VideoWriter_fourcc(*'avc1'),
                       fps,
                       (w, h))