Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to install OpenCV 4.5 with CUDA 11.2 in Ubuntu 20.04

How to install OpenCV 4.5.2 with CUDA 11.2 and CUDNN 8.2 in Ubuntu 20.04

First of all install update and upgrade your system:

    $ sudo apt update
    $ sudo apt upgrade

Then, install required libraries:

  • Generic tools:

      $ sudo apt install build-essential cmake pkg-config unzip yasm git checkinstall
    
  • Image I/O libs

    $ sudo apt install libjpeg-dev libpng-dev libtiff-dev
    
  • Video/Audio Libs - FFMPEG, GSTREAMER, x264 and so on.

    $ sudo apt install libavcodec-dev libavformat-dev libswscale-dev libavresample-dev
    $ sudo apt install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
    $ sudo apt install libxvidcore-dev x264 libx264-dev libfaac-dev libmp3lame-dev libtheora-dev 
    $ sudo apt install libfaac-dev libmp3lame-dev libvorbis-dev
    
  • OpenCore - Adaptive Multi Rate Narrow Band (AMRNB) and Wide Band (AMRWB) speech codec

    $ sudo apt install libopencore-amrnb-dev libopencore-amrwb-dev
    
  • Cameras programming interface libs

    $ sudo apt-get install libdc1394-22 libdc1394-22-dev libxine2-dev libv4l-dev v4l-utils
    $ cd /usr/include/linux
    $ sudo ln -s -f ../libv4l1-videodev.h videodev.h
    $ cd ~
    
  • GTK lib for the graphical user functionalites coming from OpenCV highghui module

    $ sudo apt-get install libgtk-3-dev
    
  • Python libraries for python3:

    $ sudo apt-get install python3-dev python3-pip
    $ sudo -H pip3 install -U pip numpy
    $ sudo apt install python3-testresources
    
  • Parallelism library C++ for CPU

    $ sudo apt-get install libtbb-dev
    
  • Optimization libraries for OpenCV

    $ sudo apt-get install libatlas-base-dev gfortran
    
  • Optional libraries:

    $ sudo apt-get install libprotobuf-dev protobuf-compiler
    $ sudo apt-get install libgoogle-glog-dev libgflags-dev
    $ sudo apt-get install libgphoto2-dev libeigen3-dev libhdf5-dev doxygen
    

We will now proceed with the installation (see the Qt flag that is disabled to do not have conflicts with Qt5.0).

$ cd ~/Downloads
$ wget -O opencv.zip https://github.com/opencv/opencv/archive/refs/tags/4.5.2.zip
$ wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/refs/tags/4.5.2.zip
$ unzip opencv.zip
$ unzip opencv_contrib.zip

$ echo "Create a virtual environtment for the python binding module (OPTIONAL)"
$ sudo pip install virtualenv virtualenvwrapper
$ sudo rm -rf ~/.cache/pip
$ echo "Edit ~/.bashrc"
$ export WORKON_HOME=$HOME/.virtualenvs
$ export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv cv -p python3
$ pip install numpy

$ echo "Procced with the installation"
$ cd opencv-4.5.2
$ mkdir build
$ cd build

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_TBB=ON \
-D ENABLE_FAST_MATH=1 \
-D CUDA_FAST_MATH=1 \
-D WITH_CUBLAS=1 \
-D WITH_CUDA=ON \
-D BUILD_opencv_cudacodec=OFF \
-D WITH_CUDNN=ON \
-D OPENCV_DNN_CUDA=ON \
-D CUDA_ARCH_BIN=7.5 \
-D WITH_V4L=ON \
-D WITH_QT=OFF \
-D WITH_OPENGL=ON \
-D WITH_GSTREAMER=ON \
-D OPENCV_GENERATE_PKGCONFIG=ON \
-D OPENCV_PC_FILE_NAME=opencv.pc \
-D OPENCV_ENABLE_NONFREE=ON \
-D OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages \
-D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \
-D OPENCV_EXTRA_MODULES_PATH=~/Downloads/opencv_contrib-4.5.2/modules \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D BUILD_EXAMPLES=OFF ..

If you want to build the libraries statically you only have to include the -D BUILD_SHARED_LIBS=OFF

$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc-6 -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D WITH_TBB=ON -D WITH_CUDA=ON -D BUILD_opencv_cudacodec=OFF -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_PC_FILE_NAME=opencv.pc -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages -D OPENCV_EXTRA_MODULES_PATH=~/downloads/opencv/opencv_contrib-4.5.2/modules -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python -D BUILD_EXAMPLES=ON -D BUILD_SHARED_LIBS=OFF ..

In case you do not want to include include CUDA set -D WITH_CUDA=OFF

$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc-6 -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D WITH_TBB=ON -D WITH_CUDA=OFF -D BUILD_opencv_cudacodec=OFF -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_PC_FILE_NAME=opencv.pc -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages -D OPENCV_EXTRA_MODULES_PATH=~/downloads/opencv/opencv_contrib-4.5.2/modules -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python -D BUILD_EXAMPLES=ON ..

If you want also to use CUDNN you must include those flags (to set the correct value of CUDA_ARCH_BIN you must visit https://developer.nvidia.com/cuda-gpus and find the Compute Capability CC of your graphic card). If you have problems with the setting up of CUDDN check the List of documented problems:

-D WITH_CUDNN=ON \
-D OPENCV_DNN_CUDA=ON \
-D CUDA_ARCH_BIN=7.5 \

Before the compilation you must check that CUDA has been enabled in the configuration summary printed on the screen. (If you have problems with the CUDA Architecture go to the end of the document).

--   NVIDIA CUDA:                   YES (ver 11.2, CUFFT CUBLAS FAST_MATH)
--     NVIDIA GPU arch:             75
--     NVIDIA PTX archs:
-- 
--   cuDNN:                         YES (ver 8.2.0)

I've included below the output of my configuration.

If it is fine proceed with the compilation (Use nproc to know the number of cpu cores):

$ nproc
$ make -j8
$ sudo make install

Include the libs in your environment

$ sudo /bin/bash -c 'echo "/usr/local/lib" >> /etc/ld.so.conf.d/opencv.conf'
$ sudo ldconfig

If you want to have available opencv python bindings in the system environment you should copy the created folder during the installation of OpenCV (* -D OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages *) into the dist-packages folder of the target python interpreter:

$ sudo cp -r ~/.virtualenvs/cv/lib/python3.8/site-packages/cv2 /usr/local/lib/python3.8/dist-packages

$ echo "Modify config-3.8.py to point to the target directory" 
$ sudo nano /usr/local/lib/python3.8/dist-packages/cv2/config-3.8.py 

``` 
    PYTHON_EXTENSIONS_PATHS = [
    os.path.join('/usr/local/lib/python3.8/dist-packages/cv2', 'python-3.8')
    ] + PYTHON_EXTENSIONS_PATHS
``` 

Additional Support

@keaneflynn has created a repository that contains a bash script with all the steps to build and install the libraries and a python script to test it over a mp4 video, already attached. Main peculiarity of his installation is the explicitly definition of the gcc and g++ versions. Other folks have also reported incompatibility problems with g++, as @keaneflynn, so I've found interesting to include his repo as an additional support.

EXAMPLE TO TEST OPENCV 4.5.2 with GPU in C++

Verify the installation by compiling and executing the following example:

#include <iostream>
#include <ctime>
#include <cmath>
#include "bits/time.h"

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>

#include <opencv2/core/cuda.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudaimgproc.hpp>

#define TestCUDA true

int main() {
    std::clock_t begin = std::clock();

        try {
            cv::String filename = "/home/raul/Pictures/Screenshot_20170317_105454.png";
            cv::Mat srcHost = cv::imread(filename, cv::IMREAD_GRAYSCALE);

            for(int i=0; i<1000; i++) {
                if(TestCUDA) {
                    cv::cuda::GpuMat dst, src;
                    src.upload(srcHost);

                    //cv::cuda::threshold(src,dst,128.0,255.0, CV_THRESH_BINARY);
                    cv::cuda::bilateralFilter(src,dst,3,1,1);

                    cv::Mat resultHost;
                    dst.download(resultHost);
                } else {
                    cv::Mat dst;
                    cv::bilateralFilter(srcHost,dst,3,1,1);
                }
            }

            //cv::imshow("Result",resultHost);
            //cv::waitKey();

        } catch(const cv::Exception& ex) {
            std::cout << "Error: " << ex.what() << std::endl;
        }

    std::clock_t end = std::clock();
    std::cout << double(end-begin) / CLOCKS_PER_SEC  << std::endl;
}

Compile and execute:

$ g++ test.cpp `pkg-config opencv --cflags --libs` -o test
$ ./test

Configuration information

This configuration has been defined without using the virtualenvironment. So, opencv python bindings has been directly installed in the system.

Configuration arguments:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D WITH_TBB=ON \
-D ENABLE_FAST_MATH=1 \
-D CUDA_FAST_MATH=1 \
-D WITH_CUBLAS=1 \
-D WITH_CUDA=ON \
-D BUILD_opencv_cudacodec=OFF \
-D WITH_CUDNN=ON \
-D OPENCV_DNN_CUDA=ON \
-D CUDA_ARCH_BIN=7.5 \
-D WITH_V4L=ON \
-D WITH_QT=OFF \
-D WITH_OPENGL=ON \
-D WITH_GSTREAMER=ON \
-D OPENCV_GENERATE_PKGCONFIG=ON \
-D OPENCV_PC_FILE_NAME=opencv.pc \
-D OPENCV_ENABLE_NONFREE=ON \
-D OPENCV_PYTHON3_INSTALL_PATH=/usr/lib/python3/dist-packages \
-D PYTHON_EXECUTABLE=/usr/bin/python3 \
-D OPENCV_EXTRA_MODULES_PATH=~/Downloads/opencv_contrib-4.5.2/modules \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D BUILD_EXAMPLES=OFF ..

General Configuration output:

-- General configuration for OpenCV 4.5.2 =====================================
--   Version control:               unknown
-- 
--   Extra modules:
--     Location (extra):            /home/raul/Downloads/opencv_contrib-4.5.2/modules
--     Version control (extra):     unknown
-- 
--   Platform:
--     Timestamp:                   2021-06-25T09:31:43Z
--     Host:                        Linux 5.4.0-77-generic x86_64
--     CMake:                       3.16.3
--     CMake generator:             Unix Makefiles
--     CMake build tool:            /usr/bin/make
--     Configuration:               RELEASE
-- 
--   CPU/HW features:
--     Baseline:                    SSE SSE2 SSE3
--       requested:                 SSE3
--     Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX
--       requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
--       SSE4_1 (17 files):         + SSSE3 SSE4_1
--       SSE4_2 (2 files):          + SSSE3 SSE4_1 POPCNT SSE4_2
--       FP16 (1 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX
--       AVX (5 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
--       AVX2 (31 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
--       AVX512_SKX (7 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX
-- 
--   C/C++:
--     Built as dynamic libs?:      YES
--     C++ standard:                11
--     C++ Compiler:                /usr/bin/c++  (ver 9.3.0)
--     C++ flags (Release):         -fsigned-char -ffast-math -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
--     C++ flags (Debug):           -fsigned-char -ffast-math -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
--     C Compiler:                  /usr/bin/cc
--     C flags (Release):           -fsigned-char -ffast-math -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
--     C flags (Debug):             -fsigned-char -ffast-math -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
--     Linker flags (Release):      -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a   -Wl,--gc-sections -Wl,--as-needed  
--     Linker flags (Debug):        -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a   -Wl,--gc-sections -Wl,--as-needed  
--     ccache:                      NO
--     Precompiled headers:         NO
--     Extra dependencies:          m pthread cudart_static dl rt nppc nppial nppicc nppidei nppif nppig nppim nppist nppisu nppitc npps cublas cudnn cufft -L/usr/local/cuda/lib64 -L/usr/lib/x86_64-linux-gnu
--     3rdparty dependencies:
-- 
--   OpenCV modules:
--     To be built:                 alphamat aruco bgsegm bioinspired calib3d ccalib core cudaarithm cudabgsegm cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy gapi hdf hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency sfm shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
--     Disabled:                    cudacodec world
--     Disabled by dependency:      -
--     Unavailable:                 cnn_3dobj cvv java julia matlab ovis python2 viz
--     Applications:                tests perf_tests apps
--     Documentation:               NO
--     Non-free algorithms:         YES
-- 
--   GUI: 
--     GTK+:                        YES (ver 3.24.20)
--       GThread :                  YES (ver 2.64.6)
--       GtkGlExt:                  NO
--     OpenGL support:              NO
--     VTK support:                 NO
-- 
--   Media I/O: 
--     ZLib:                        /usr/lib/x86_64-linux-gnu/libz.so (ver 1.2.11)
--     JPEG:                        /usr/lib/x86_64-linux-gnu/libjpeg.so (ver 80)
--     WEBP:                        build (ver encoder: 0x020f)
--     PNG:                         /usr/lib/x86_64-linux-gnu/libpng.so (ver 1.6.37)
--     TIFF:                        /usr/lib/x86_64-linux-gnu/libtiff.so (ver 42 / 4.1.0)
--     JPEG 2000:                   build (ver 2.4.0)
--     OpenEXR:                     build (ver 2.3.0)
--     HDR:                         YES
--     SUNRASTER:                   YES
--     PXM:                         YES
--     PFM:                         YES
-- 
--   Video I/O:
--     DC1394:                      YES (2.2.5)
--     FFMPEG:                      YES
--       avcodec:                   YES (58.54.100)
--       avformat:                  YES (58.29.100)
--       avutil:                    YES (56.31.100)
--       swscale:                   YES (5.5.100)
--       avresample:                YES (4.0.0)
--     GStreamer:                   YES (1.16.2)
--     v4l/v4l2:                    YES (linux/videodev2.h)
-- 
--   Parallel framework:            TBB (ver 2020.1 interface 11101)
-- 
--   Trace:                         YES (with Intel ITT)
-- 
--   Other third-party libraries:
--     Intel IPP:                   2020.0.0 Gold [2020.0.0]
--            at:                   /home/raul/Downloads/opencv-4.5.2/build/3rdparty/ippicv/ippicv_lnx/icv
--     Intel IPP IW:                sources (2020.0.0)
--               at:                /home/raul/Downloads/opencv-4.5.2/build/3rdparty/ippicv/ippicv_lnx/iw
--     VA:                          YES
--     Lapack:                      NO
--     Eigen:                       YES (ver 3.3.7)
--     Custom HAL:                  NO
--     Protobuf:                    build (3.5.1)
-- 
--   NVIDIA CUDA:                   YES (ver 11.2, CUFFT CUBLAS FAST_MATH)
--     NVIDIA GPU arch:             75
--     NVIDIA PTX archs:
-- 
--   cuDNN:                         YES (ver 8.2.0)
-- 
--   OpenCL:                        YES (INTELVA)
--     Include path:                /home/raul/Downloads/opencv-4.5.2/3rdparty/include/opencl/1.2
--     Link libraries:              Dynamic load
-- 
--   Python 3:
--     Interpreter:                 /usr/bin/python3 (ver 3.8.5)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.8.so (ver 3.8.5)
--     numpy:                       /usr/local/lib/python3.8/dist-packages/numpy/core/include (ver 1.21.0)
--     install path:                /usr/lib/python3/dist-packages/cv2/python-3.8
-- 
--   Python (for build):            /usr/bin/python3
-- 
--   Java:                          
--     ant:                         NO
--     JNI:                         NO
--     Java wrappers:               NO
--     Java tests:                  NO
-- 
--   Install to:                    /usr/local
-- -----------------------------------------------------------------

List of documented problems

If you have problems with unsupported architectures of your graphic card with the minimum requirements from Opencv, you will get the following error:

CUDA backend for DNN module requires CC 5.3 or higher.  Please remove unsupported architectures from CUDA_ARCH_BIN option.

It means that the DNN module needs that your graphic card supports the 5.3 Compute Capability (CC) version; in this link you can fint the CC of your card. Some opencv versions have fixed the minimum version to 3.0 but there is a clear move to filter above 5.3 since the half-precision precision operations are available from 5.3 version. To fix this problem you can modify the CMakeList.txt file located in opencv > modules > dnn > CMakeList.txt and set the minimum version to the one you have, but bear in mind that the correct functioning of this module will be compromised. However, if you only want GPU for the rest of modules, it could work.

You can also select the target CUDA_ARCH_BIN option in the command to generate the makefile for your current target or modify the list of supported architectures:

$ grep -r 'CUDA_ARCH_BIN' .  //That prompts ./CMakeCache.txt

The restriction is to have a higher version than 5.3, so you can modify the file by removing all the inferior arch to 5.3

CUDA_ARCH_BIN:STRING=6.0 6.1 7.0 7.5

Now, the makefile was created succesfully. Before the compilation you must check that CUDA has been enabled in the configuration summary printed on the screen.

--   NVIDIA CUDA:                   YES (ver 10.0, CUFFT CUBLAS NVCUVID FAST_MATH)
--     NVIDIA GPU arch:             60 61 70 75
--     NVIDIA PTX archs:

Some users as TAF2 had problems when configuring CUDNN libraries but it was solved and here is the TAF2's proposal, you can also find it in the comments:

sudo apt install libcudnn7-dev  libcudnn7-doc  libcudnn7 nvidia-container-csv-cudnn
 -D CUDNN_INCLUDE_DIR=/usr/include \
-D CUDNN_LIBRARY=/usr/lib64/libcudnn_static_v7.a \
-D CUDNN_VERSION=7.6.3

If you have any other problem try updating the nvidia drivers.

Source

@t3ga
Copy link

t3ga commented Sep 20, 2019

$ sudo apt install python3-tesTresources

@DSamuylov
Copy link

DSamuylov commented Oct 27, 2019

Thank you a lot for the gist!

@ucals
Copy link

ucals commented Dec 30, 2019

Thank you!

@vwvw
Copy link

vwvw commented Jan 20, 2020

-D OPENCV_EXTRA_MODULES_PATH=~/downloads/opencv/opencv_contrib-4.2.0/modules \ should be -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-4.2.0/modules \ if you followed the unzipping done beforehand

@raulqf
Copy link
Author

raulqf commented Jan 20, 2020

-D OPENCV_EXTRA_MODULES_PATH=~/downloads/opencv/opencv_contrib-4.2.0/modules \ should be -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-4.2.0/modules \ if you followed the unzipping done beforehand

Thank you! I've edited the gist with your comment.

@vwvw
Copy link

vwvw commented Jan 20, 2020

You still have opencv/ too much! Thanks for the great writeup otherwise!

@raulqf
Copy link
Author

raulqf commented Jan 20, 2020

You still have opencv/ too much! Thanks for the great writeup otherwise!

I hope this is the correct one!! Haha Thanks for your comments.

@xiaoniu001
Copy link

xiaoniu001 commented Jan 21, 2020

My environment is gpu 2080, ubuntu18 ,cuda10.2 but I get this error

[100%] Building CXX object samples/gpu/CMakeFiles/example_gpu_surf_keypoint_matcher.dir/surf_keypoint_matcher.cpp.o
[100%] Built target opencv_test_superres
Scanning dependencies of target example_gpu_video_reader
[100%] Building CXX object samples/gpu/CMakeFiles/example_gpu_super_resolution.dir/super_resolution.cpp.o
[100%] Linking CXX executable ../../bin/example_gpu_hog
[100%] Building CXX object samples/gpu/CMakeFiles/example_gpu_video_reader.dir/video_reader.cpp.o
/home/pactera/software/opencv-4.2.0/samples/gpu/surf_keypoint_matcher.cpp:11:10: fatal error: opencv2/xfeatures2d/cuda.hpp: 没有那个文件或目录
 #include "opencv2/xfeatures2d/cuda.hpp"
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
samples/gpu/CMakeFiles/example_gpu_surf_keypoint_matcher.dir/build.make:62: recipe for target 'samples/gpu/CMakeFiles/example_gpu_surf_keypoint_matcher.dir/surf_keypoint_matcher.cpp.o' failed
make[2]: *** [samples/gpu/CMakeFiles/example_gpu_surf_keypoint_matcher.dir/surf_keypoint_matcher.cpp.o] Error 1

@raulqf
Copy link
Author

raulqf commented Jan 21, 2020

My environment is gpu 2080, ubuntu18 ,cuda10.2 but I get this error

[100%] Building CXX object samples/gpu/CMakeFiles/example_gpu_surf_keypoint_matcher.dir/surf_keypoint_matcher.cpp.o
[100%] Built target opencv_test_superres
Scanning dependencies of target example_gpu_video_reader
[100%] Building CXX object samples/gpu/CMakeFiles/example_gpu_super_resolution.dir/super_resolution.cpp.o
[100%] Linking CXX executable ../../bin/example_gpu_hog
[100%] Building CXX object samples/gpu/CMakeFiles/example_gpu_video_reader.dir/video_reader.cpp.o
/home/pactera/software/opencv-4.2.0/samples/gpu/surf_keypoint_matcher.cpp:11:10: fatal error: opencv2/xfeatures2d/cuda.hpp: 没有那个文件或目录
#include "opencv2/xfeatures2d/cuda.hpp"
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
samples/gpu/CMakeFiles/example_gpu_surf_keypoint_matcher.dir/build.make:62: recipe for target 'samples/gpu/CMakeFiles/example_gpu_surf_keypoint_matcher.dir/surf_keypoint_matcher.cpp.o' failed
make[2]: *** [samples/gpu/CMakeFiles/example_gpu_surf_keypoint_matcher.dir/surf_keypoint_matcher.cpp.o] Error 1

The error is not in english and I cannot understand it. Run make VERBOSE=1 to get a more detailed information about the error. Remember that SURF is not free so make sure the flag is correctly defined.

@xiaoniu001
Copy link

xiaoniu001 commented Jan 21, 2020

Meaning that does not have this file or directory "opencv2 / xfeatures2d / cuda.hpp

@vwvw
Copy link

vwvw commented Jan 21, 2020

My environment is gpu 2080, ubuntu18 ,cuda10.2 but I get this error

I'm also running Ubuntu 18.04, Cuda 10.2 and the script ran flawlessly.
Are you sure you cloned the opencv-contrib directory in the right place?

@Gokulakrishnan-96
Copy link

Gokulakrishnan-96 commented Jan 23, 2020

I am facing the following issue: I previously had OpenCV 3.2 in my system (Ubuntu 18.04 LTS, CUDA 10.1) that I installed via: sudo apt-get install libopencv-dev python-opencv without CUDA support. Now that I am looking for CUDA support, I installed OpenCV 4.2.0 following the instructions given by you @raulqf (Thank you so much for this!), except for the virtual environment creation part! Now, the problem I am facing is that pkg-config could not locate OpenCV4.2 and it is still pointing to the older version (OpenCV 3.2). I even removed all the packages pertaining to the older version. Now pkg-config simply cannot locate a package name opencv at all. Suggestion made: Try adding the directory that contains opencv.pc to the environment variable PKG_CONFIG_PATH. Where is this file located?

@raulqf
Copy link
Author

raulqf commented Jan 23, 2020

I am facing the following issue: I previously had OpenCV 3.2 in my system (Ubuntu 18.04 LTS, CUDA 10.1) that I installed via: sudo apt-get install libopencv-dev python-opencv without CUDA support. Now that I am looking for CUDA support, I installed OpenCV 4.2.0 following the instructions given by you @raulqf (Thank you so much for this!), except for the virtual environment creation part! Now, the problem I am facing is that pkg-config could not locate OpenCV4.2 and it is still pointing to the older version (OpenCV 3.2). I even removed all the packages pertaining to the older version. Now pkg-config simply cannot locate a package name opencv at all. Suggestion made: Try adding the directory that contains opencv.pc to the environment variable PKG_CONFIG_PATH. Where is this file located?

Hi. It is really to understand how pkg-config works. Basically the file contains the information to locate the header files and the libs to be used during compilation. The name opencv.pc can be modified in the installation process, in fact, it was defined in this flag **-D OPENCV_PC_FILE_NAME=opencv.pc *. So, you could define any other name. One suggestion would be to include your opencv version within the filename --> opencv420.pc. If you change the name you must use the new file name when invoking pkg-config -> g++ pkg-config opencv420 --cflags --libs -o test test.cpp . To find your opencv.pc you could use locate opencv* (remember to update the database sudo updatedb) or use find --> find /usr/ --name opencv ... The are also some environment variables used by pkg-config pointing to the PKG_CONFIG_PATH

To sum up, you could redo the process defining a new filename for opencv.pc or you could modify the current opencv.pc to point to the correct directory. It is a file text that can be modified by any text editor. Once you open it, you would find that the directories are wrongly defined. According to the installation, they must point to /usr/local/lib for the libraries and /usr/loca/include for the header files.

@Gokulakrishnan-96
Copy link

Gokulakrishnan-96 commented Jan 24, 2020

I am facing the following issue: I previously had OpenCV 3.2 in my system (Ubuntu 18.04 LTS, CUDA 10.1) that I installed via: sudo apt-get install libopencv-dev python-opencv without CUDA support. Now that I am looking for CUDA support, I installed OpenCV 4.2.0 following the instructions given by you @raulqf (Thank you so much for this!), except for the virtual environment creation part! Now, the problem I am facing is that pkg-config could not locate OpenCV4.2 and it is still pointing to the older version (OpenCV 3.2). I even removed all the packages pertaining to the older version. Now pkg-config simply cannot locate a package name opencv at all. Suggestion made: Try adding the directory that contains opencv.pc to the environment variable PKG_CONFIG_PATH. Where is this file located?

Hi. It is really to understand how pkg-config works. Basically the file contains the information to locate the header files and the libs to be used during compilation. The name opencv.pc can be modified in the installation process, in fact, it was defined in this flag **-D OPENCV_PC_FILE_NAME=opencv.pc *. So, you could define any other name. One suggestion would be to include your opencv version within the filename --> opencv420.pc. If you change the name you must use the new file name when invoking pkg-config -> g++ pkg-config opencv420 --cflags --libs -o test test.cpp . To find your opencv.pc you could use locate opencv* (remember to update the database sudo updatedb) or use find --> find /usr/ --name opencv ... The are also some environment variables used by pkg-config pointing to the PKG_CONFIG_PATH

To sum up, you could redo the process defining a new filename for opencv.pc or you could modify the current opencv.pc to point to the correct directory. It is a file text that can be modified by any text editor. Once you open it, you would find that the directories are wrongly defined. According to the installation, they must point to /usr/local/lib for the libraries and /usr/loca/include for the header files.

Thank you so much for the explanation, @raulqf ! It works fine and thank you for taking pains to write this Gist too!

@drewnia
Copy link

drewnia commented Jan 29, 2020

What is the problem? Opencv 3.4.9 has no such problem

[ 7%] Building NVCC (Device) object modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/cuda_compile_1_generated_gpu_mat.cu.o
CMake Error at cuda_compile_1_generated_gpu_mat.cu.o.RELEASE.cmake:221 (message):
Error generating
CMakeFiles/cuda_compile_1.dir/src/cuda/./cuda_compile_1_generated_gpu_mat.cu.o

modules/core/CMakeFiles/opencv_core.dir/build.make:487: recipe for target 'modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/cuda_compile_1_generated_gpu_mat.cu.o' failed
make[2]: *** [modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/cuda_compile_1_generated_gpu_mat.cu.o] Error 1
CMakeFiles/Makefile2:3082: recipe for target 'modules/core/CMakeFiles/opencv_core.dir/all' failed
make[1]: *** [modules/core/CMakeFiles/opencv_core.dir/all] Error 2

@raulqf
Copy link
Author

raulqf commented Jan 30, 2020

Which version of NVCC, CUDA and g++ or gcc are you using? Googling it I found https://answers.opencv.org/question/189712/unable-to-compile-opencv-with-cuda9-and-gcc6/?sort=oldest . They suggest to install certain versions of gcc and g++, so I guess you must update the compilers.

Copy link

ghost commented Feb 9, 2020

Thank you for your tutorial!

How can I sort out the errors?

I tried:
sudo cp ~/opencv/build/unix-install/opencv.pc /usr/local/lib/pkgconfig/
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig

BUT
g++ pkg-config opencv --cflags --libs -o test test.cpp
/tmp/cc3tkJEc.o: In function main': test.cpp:(.text+0x7e): undefined reference to cv::imread(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int)'
test.cpp:(.text+0x9d): undefined reference to cv::cuda::GpuMat::defaultAllocator()' test.cpp:(.text+0xb7): undefined reference to cv::cuda::GpuMat::defaultAllocator()'
...

@raulqf
Copy link
Author

raulqf commented Feb 10, 2020

Thank you for your tutorial!

How can I sort out the errors?

I tried:
sudo cp ~/opencv/build/unix-install/opencv.pc /usr/local/lib/pkgconfig/
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig

BUT
g++ pkg-config opencv --cflags --libs -o test test.cpp
/tmp/cc3tkJEc.o: In function main': test.cpp:(.text+0x7e): undefined reference to cv::imread(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int)'
test.cpp:(.text+0x9d): undefined reference to cv::cuda::GpuMat::defaultAllocator()' test.cpp:(.text+0xb7): undefined reference to cv::cuda::GpuMat::defaultAllocator()'
...

Hi, You have problems in the compiling process when linking the header files. Make sure your includes are correctly defined.

@basit26374
Copy link

basit26374 commented Feb 13, 2020

The file is not created in "~/.virtualenvs/opencv_cuda/lib/python3.6/site-packages/cv2". After cmake the response is like this

opencv_build_5

@raulqf
Copy link
Author

raulqf commented Feb 13, 2020

The file is not created in "~/.virtualenvs/opencv_cuda/lib/python3.6/site-packages/cv2". After cmake the response is like this

opencv_build_5

Which files? Do you mean the binding shared libraries for opencv to be used in python?

@putrasto
Copy link

putrasto commented Feb 14, 2020

Thank you for your tutorial!

How can I sort out the errors?

I tried:
sudo cp ~/opencv/build/unix-install/opencv.pc /usr/local/lib/pkgconfig/
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig

BUT
g++ pkg-config opencv --cflags --libs -o test test.cpp
/tmp/cc3tkJEc.o: In function main': test.cpp:(.text+0x7e): undefined reference to cv::imread(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int)'
test.cpp:(.text+0x9d): undefined reference to cv::cuda::GpuMat::defaultAllocator()' test.cpp:(.text+0xb7): undefined reference to cv::cuda::GpuMat::defaultAllocator()'
...

I had the same error and then i change the order of include files and library like below:
g++ test.cpp pkg-config opencv --cflags --libs
(file source code is at front)

@basit26374
Copy link

basit26374 commented Feb 14, 2020

The file is not created in "~/.virtualenvs/opencv_cuda/lib/python3.6/site-packages/cv2". After cmake the response is like this
opencv_build_5

Which files? Do you mean the binding shared libraries for opencv to be used in python?

like .so file

@pinduzera
Copy link

pinduzera commented Feb 14, 2020

I could not find the Python bindings in ~/.virtualenvs/cv/lib/python3.6/site-packages/cv2 after doing all the process, what migh have happened?

@raulqf
Copy link
Author

raulqf commented Feb 15, 2020

I could not find the Python bindings in ~/.virtualenvs/cv/lib/python3.6/site-packages/cv2 after doing all the process, what migh have happened?

Coud you include your log in verbose mode to check any possible error? You seem to have the same problem as @basit26374.

@basit26374
Copy link

basit26374 commented Feb 19, 2020

@pinduzera how did you fix it?
Please mention, maybe other people getting help from your advice.
I was also doing the same process but .so not generated

@junaidfiaz143
Copy link

junaidfiaz143 commented Feb 19, 2020

cuDNN is NO.....WHY?????

image

@raulqf
Copy link
Author

raulqf commented Feb 19, 2020

@pinduzera how did you fix it?
Please mention, maybe other people getting help from your advice.
I was also doing the same process but .so not generated

Remember to do "make install" after the build process. Check the gist commands and follow thoroughly.

@pinduzera
Copy link

pinduzera commented Feb 19, 2020

@pinduzera how did you fix it?
Please mention, maybe other people getting help from your advice.
I was also doing the same process but .so not generated

I have pretty much run the script, my problem was because I had forgotten to do the make install. Anyway, I have added the following changes added in the cmake:

-D WITH_CUDNN=ON \
-D OPENCV_DNN_CUDA=ON \
-D CUDA_ARCH_BIN=6.2

I've mainly added CUDA_ARCH_BIN=6.2 to specify the cuda compute capability of my Jetson TX2 because the automatic may be troublesome, I've also done the same process in a notebook with a RTX 2080 Max-q and the cuda compute used was 7.5 which you can check on this link: https://developer.nvidia.com/cuda-gpus

@raulqf
Copy link
Author

raulqf commented Feb 20, 2020

@pinduzera how did you fix it?
Please mention, maybe other people getting help from your advice.
I was also doing the same process but .so not generated

I have pretty much run the script, my problem was because I had forgotten to do the make install. Anyway, I have added the following changes added in the cmake:

-D WITH_CUDNN=ON \
-D OPENCV_DNN_CUDA=ON \
-D CUDA_ARCH_BIN=6.2

I've mainly added CUDA_ARCH_BIN=6.2 to specify the cuda compute capability of my Jetson TX2 because the automatic may be troublesome, I've also done the same process in a notebook with a RTX 2080 Max-q and the cuda compute used was 7.5 which you can check on this link: https://developer.nvidia.com/cuda-gpus

I've included the CUDNN flags as an option in case you want to compile OpenCV using CUDNN. Thanks for the comment.

@jenssgb
Copy link

jenssgb commented Mar 14, 2020

In case you get "CMake Error unsupported GNU version! gcc versions later than 6 are not supported!"
try: -DCMAKE_C_COMPILER=/usr/bin/gcc-6 to specify the path of the compiler

@raulqf
Copy link
Author

raulqf commented Mar 14, 2020

-DCMAKE_C_COMPILER=/usr/bin/gcc-6

I will include it. Thanks!

@chirag26495
Copy link

chirag26495 commented Mar 15, 2020

@raulqf Thanks a ton! Everything worked like a charm except during testing the sample c++ code the following lines worked for me:
g++ -o test test.cpp pkg-config opencv --cflags --libs

@HugoHJH
Copy link

HugoHJH commented Apr 7, 2020

What is the problem? Opencv 3.4.9 has no such problem

[ 7%] Building NVCC (Device) object modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/cuda_compile_1_generated_gpu_mat.cu.o
CMake Error at cuda_compile_1_generated_gpu_mat.cu.o.RELEASE.cmake:221 (message):
Error generating
CMakeFiles/cuda_compile_1.dir/src/cuda/./cuda_compile_1_generated_gpu_mat.cu.o

modules/core/CMakeFiles/opencv_core.dir/build.make:487: recipe for target 'modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/cuda_compile_1_generated_gpu_mat.cu.o' failed
make[2]: *** [modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/cuda_compile_1_generated_gpu_mat.cu.o] Error 1
CMakeFiles/Makefile2:3082: recipe for target 'modules/core/CMakeFiles/opencv_core.dir/all' failed
make[1]: *** [modules/core/CMakeFiles/opencv_core.dir/all] Error 2

Did you find a solution to this? I am getting the same error message (using CUDA 10.0, gcc-6, Ubuntu 18.04 - as per the the instructions), I'm trying to run the instillation in a Dockerfile (if that is relevant)

@nahimudeen
Copy link

nahimudeen commented Apr 17, 2020

I had few glitches with matching Nvidia driver-Cuda-CuDnn. I had also glitches with GCC version. And solved everything. Everything worked fine . But when I tried to run the test program I am stuck. I changed the input JPEG to a file @ same location.

**naeem@machine:~/opencv-4.2.0/build$** g++ pkg-config opencv --cflags --libs-o test test.cpp /tmp/ccdOMeho.o: In functionmain':
test.cpp:(.text+0x7e): undefined reference to cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)' test.cpp:(.text+0x9d): undefined reference to cv::cuda::GpuMat::defaultAllocator()'
test.cpp:(.text+0xb7): undefined reference to cv::cuda::GpuMat::defaultAllocator()' test.cpp:(.text+0xfe): undefined reference to cv::cuda::GpuMat::upload(cv::_InputArray const&)'
test.cpp:(.text+0x112): undefined reference to cv::cuda::Stream::Null()' test.cpp:(.text+0x17a): undefined reference to cv::cuda::bilateralFilter(cv::_InputArray const&, cv::_OutputArray const&, int, float, float, int, cv::cuda::Stream&)'
test.cpp:(.text+0x1d3): undefined reference to cv::cuda::GpuMat::download(cv::_OutputArray const&) const' /tmp/ccdOMeho.o: In function cv::Mat::~Mat()':
test.cpp:(.text._ZN2cv3MatD2Ev[_ZN2cv3MatD5Ev]+0x39): undefined reference to cv::fastFree(void*)' /tmp/ccdOMeho.o: In function cv::Mat::release()':
test.cpp:(.text._ZN2cv3Mat7releaseEv[_ZN2cv3Mat7releaseEv]+0x4b): undefined reference to cv::Mat::deallocate()' /tmp/ccdOMeho.o: In function cv::cuda::GpuMat::~GpuMat()':
test.cpp:(.text._ZN2cv4cuda6GpuMatD2Ev[_ZN2cv4cuda6GpuMatD5Ev]+0x14): undefined reference to cv::cuda::GpuMat::release()' /tmp/ccdOMeho.o:(.data.rel.local.DW.ref._ZTIN2cv9ExceptionE[DW.ref._ZTIN2cv9ExceptionE]+0x0): undefined reference to typeinfo for cv::Exception'
collect2: error: ld returned 1 exit status
`

I left coding 6 years back...This is my come back session,Expect big blunders...

@raulqf
Copy link
Author

raulqf commented Apr 18, 2020

Welcome back! :D It seems that your system is not correctly finding the libraries. What's your output when you type: 'pkg-config opencv --cflags --libs'?

Check that you have correctly refreshed the dynamic libraries in your system with 'sudo ldconfig'

@nahimudeen
Copy link

nahimudeen commented Apr 18, 2020

Welcome back! :D It seems that your system is not correctly finding the libraries. What's your output when you type: 'pkg-config opencv --cflags --libs'?

Check that you have correctly refreshed the dynamic libraries in your system with 'sudo ldconfig'

pkg-config opencv --cflags --libs gives
-I/usr/local/include/opencv4/opencv -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_gapi -lopencv_stitching -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_cudabgsegm -lopencv_cudafeatures2d -lopencv_cudaobjdetect -lopencv_cudastereo -lopencv_dnn_objdetect -lopencv_dnn_superres -lopencv_dpm -lopencv_highgui -lopencv_face -lopencv_freetype -lopencv_fuzzy -lopencv_hdf -lopencv_hfs -lopencv_img_hash -lopencv_line_descriptor -lopencv_quality -lopencv_reg -lopencv_rgbd -lopencv_saliency -lopencv_sfm -lopencv_stereo -lopencv_structured_light -lopencv_phase_unwrapping -lopencv_superres -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_dnn -lopencv_plot -lopencv_videostab -lopencv_cudaoptflow -lopencv_optflow -lopencv_cudalegacy -lopencv_videoio -lopencv_cudawarping -lopencv_xfeatures2d -lopencv_shape -lopencv_ml -lopencv_ximgproc -lopencv_video -lopencv_xobjdetect -lopencv_objdetect -lopencv_calib3d -lopencv_imgcodecs -lopencv_features2d -lopencv_flann -lopencv_xphoto -lopencv_photo -lopencv_cudaimgproc -lopencv_cudafilters -lopencv_imgproc -lopencv_cudaarithm -lopencv_core -lopencv_cudev

i had confirmed i had refreshed dynamic libraries. beside when libcudnn did notify about error regarding absence of symbolic link i followed this link to rectify it..

@raulqf
Copy link
Author

raulqf commented Apr 19, 2020

It should work.... But your problem is in the linking process...

@nahimudeen
Copy link

nahimudeen commented Apr 19, 2020

how about reistalling just opencv again ??

@nahimudeen
Copy link

nahimudeen commented Apr 19, 2020

i tried compiling the test program for opencv from here. It works fine. But when i put the verfication program in this tutorial and make Cmake to compile i get this error.

naeem@machine:~/HOME$ make
Scanning dependencies of target test
[ 50%] Building CXX object CMakeFiles/test.dir/test.cpp.o
[100%] Linking CXX executable test
[100%] Built target test
naeem@machine:~/HOME$ ./test
Error: OpenCV(4.2.0) /home/naeem/opencv_contrib-4.2.0/modules/cudaimgproc/src/cuda/bilateral_filter.cu:138: error: (-217:Gpu API call) invalid device function in function 'bilateral_caller'

0.088531
naeem@machine:~/HOME$ 

@nahimudeen
Copy link

nahimudeen commented Apr 21, 2020

hi i rectified the error. it was because My GPU was GTX 1050ti and it supports CC 6.1 and build in this doc is 7.5. so i correctly build according to my GPU Compute capability(CC) its working fine...i would suggest you can update this info in this doc.

@raulqf
Copy link
Author

raulqf commented Apr 23, 2020

hi i rectified the error. it was because My GPU was GTX 1050ti and it supports CC 6.1 and build in this doc is 7.5. so i correctly build according to my GPU Compute capability(CC) its working fine...i would suggest you can update this info in this doc.

How do you recommend to update the info? Along the gist I am describing the CC used, arch bin, etc...

@vladislavdonchev
Copy link

vladislavdonchev commented May 10, 2020

Hi,

I followed the guide line-for-line using the following configuration:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_C_COMPILER=/usr/bin/gcc-6 \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D INSTALL_C_EXAMPLES=OFF \
-D WITH_TBB=ON \
-D WITH_CUDA=ON \
-D BUILD_opencv_cudacodec=OFF \
-D ENABLE_FAST_MATH=1 \
-D CUDA_FAST_MATH=1 \
-D WITH_CUBLAS=1 \
-D WITH_V4L=ON \
-D WITH_QT=OFF \
-D WITH_OPENGL=ON \
-D WITH_GSTREAMER=ON \
-D OPENCV_GENERATE_PKGCONFIG=ON \
-D OPENCV_PC_FILE_NAME=opencv.pc \
-D OPENCV_ENABLE_NONFREE=ON \
-D OPENCV_PYTHON3_INSTALL_PATH=~/anaconda3/envs/cv2/lib/python3.6/site-packages \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.2.0/modules \
-D PYTHON_EXECUTABLE=~/anaconda3/envs/cv2/bin/python \
-D WITH_CUDNN=ON \
-D OPENCV_DNN_CUDA=ON \
-D CUDA_ARCH_BIN=6.1 \
-D BUILD_EXAMPLES=OFF ..

There are no build-time errors, I made sure to do a make install and ldconfig, but still, there are no Python bindings generated in the ~/anaconda3/envs/cv2/lib/python3.6/site-packages directory.

I also tried with virtualenv instead of Anaconda, but the result was the same. All CUDA libraries are detected correctly and I've been able to build and install other libraries (like DLIB) just fine:

--   NVIDIA CUDA:                   YES (ver 10.0, CUFFT CUBLAS FAST_MATH)
--     NVIDIA GPU arch:             61
--     NVIDIA PTX archs:
-- 
--   cuDNN:                         YES (ver 7.6.2)

Is there something else that I might be missing?

Cheers

@raulqf
Copy link
Author

raulqf commented May 11, 2020

Have you tried to find cv2.so in your system? In the build configuration summary did the python3 path appear correctly?

@nhanh9d
Copy link

nhanh9d commented May 17, 2020

image
When i built cmake, i got this error.
I have tried to find a solution for it but nothing worked.

@foxshared
Copy link

foxshared commented May 31, 2020

Did the cuba 9 toolkit need to install? i still not succes the CUDA = NO

@raulqf
Copy link
Author

raulqf commented May 31, 2020

image
When i built cmake, i got this error.
I have tried to find a solution for it but nothing worked.

Have you already solved it? When configuring your compilation using CMAKE check carefully the output summary log and confirm that all the dependencies are found.

@raulqf
Copy link
Author

raulqf commented May 31, 2020

Did the cuba 9 toolkit need to install? i still not succes the CUDA = NO

If you want to compile opencv with cuda support, you must have nvidia drivers and the cuda correctly installed on your system.

@igor-93
Copy link

igor-93 commented Jul 5, 2020

script works well for me, thanks a lot! However, I cloned the latest openCV from the git directly and installed python wrappers in my existing conda environment.

@60999
Copy link

60999 commented Jul 6, 2020

when under ubuntu18.04 arm64 ,jetson nano jetpack 4.4 dev:
`/opencv-4.3.0/build/build$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc-6 -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D WITH_TBB=ON -D WITH_CUDA=ON -D BUILD_opencv_cudacodec=OFF -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_PC_FILE_NAME=opencv.pc -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_PYTHON3_INSTALL_PATH=/.virtualenvs/cv/lib/python3.6/site-packages -D OPENCV_EXTRA_MODULES_PATH=/downloads/opencv/opencv_contrib-4.3.0/modules -D PYTHON_EXECUTABLE=/.virtualenvs/cv/bin/python -D BUILD_EXAMPLES=ON -D BUILD_SHARED_LIBS=OFF ..
-- The C compiler identification is unknown
CMake Error at CMakeLists.txt:106 (enable_language):
The CMAKE_C_COMPILER:

/usr/bin/gcc-6

is not a full path to an existing compiler tool.

Tell CMake where to find the compiler by setting either the environment
variable "CC" or the CMake cache entry CMAKE_C_COMPILER to the full path to
the compiler, or to the compiler name if it is in the PATH.

-- Configuring incomplete, errors occurred!
See also "/home/aistudio/opencv-4.3.0/build/CMakeFiles/CMakeOutput.log".
See also "/home/aistudio/opencv-4.3.0/build/CMakeFiles/CMakeError.log".`

The error is " is not a full path to an existing compiler tool."
How to fix it?Thanks.

@anilsathyan7
Copy link

anilsathyan7 commented Oct 3, 2020

I had to remove the cmake compile option and it automatically works with gcc 7.5.0.
So is it necessary to add this line : -D CMAKE_C_COMPILER=/usr/bin/gcc-6?.
Also i had to run: g++ test.cpp -o test `pkg-config opencv --cflags --libs` (i.e reorder) for compiling the code in ubuntu 18.04 using g++.

@kunalrustagi08
Copy link

kunalrustagi08 commented Oct 10, 2020

@raulqf
Hello. I am trying to follow the same setup on my Pop!_OS system, but with opencv4.4.0, CUDA ToolKit 11 and cuDNN8.0 and Quadro K600 graphics card. The compute capability is 3.0

While executing make -j4, an error appeared

[  8%] Built target gen_opencv_python_source
[  8%] Processing OpenCL kernels (core)
[  8%] Building NVCC (Device) object modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/cuda_compile_1_generated_gpu_mat.cu.o
nvcc fatal   : Unsupported gpu architecture 'compute_30'
CMake Error at cuda_compile_1_generated_gpu_mat.cu.o.RELEASE.cmake:222 (message):
  Error generating
  /home/kunal/opencv/build/modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/./cuda_compile_1_generated_gpu_mat.cu.o


make[2]: *** [modules/core/CMakeFiles/opencv_core.dir/build.make:65: modules/core/CMakeFiles/cuda_compile_1.dir/src/cuda/cuda_compile_1_generated_gpu_mat.cu.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:5584: modules/core/CMakeFiles/opencv_core.dir/all] Error 2

and stopped at

[ 12%] Built target libprotobuf
make: *** [Makefile:163: all] Error 2

Please can you help me? Im stuck on this step since the past 3 days. I am not sure what's wrong.

@raulqf
Copy link
Author

raulqf commented Oct 11, 2020

I had to remove the cmake compile option and it automatically works with gcc 7.5.0.
So is it necessary to add this line : -D CMAKE_C_COMPILER=/usr/bin/gcc-6?.
Also i had to run: g++ test.cpp -o test pkg-config opencv --cflags --libs (i.e reorder) for compiling the code in ubuntu 18.04 using g++.

Hi, It is not necessary but just a reminder in case you were using an old gcc version as it happened to someone who suggested to include the flag. You will find in previous comments.

I will change the re-order of the --cflags and --libs since you are not the first to highlight it, although my system accepts both.

@raulqf
Copy link
Author

raulqf commented Oct 11, 2020

make -j4

It seems that your NVCC (Nvidica Compiler) does not support your Cuda Compability (CC). Do you have CUDA working properly in your computer? Try to find your correct CC, in case 3.0 is not right, and set it when defining the target architecture.

@raulqf
Copy link
Author

raulqf commented Oct 11, 2020

when under ubuntu18.04 arm64 ,jetson nano jetpack 4.4 dev:
`/opencv-4.3.0/build/build$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc-6 -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D WITH_TBB=ON -D WITH_CUDA=ON -D BUILD_opencv_cudacodec=OFF -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_PC_FILE_NAME=opencv.pc -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_PYTHON3_INSTALL_PATH=/.virtualenvs/cv/lib/python3.6/site-packages -D OPENCV_EXTRA_MODULES_PATH=/downloads/opencv/opencv_contrib-4.3.0/modules -D PYTHON_EXECUTABLE=/.virtualenvs/cv/bin/python -D BUILD_EXAMPLES=ON -D BUILD_SHARED_LIBS=OFF ..
-- The C compiler identification is unknown
CMake Error at CMakeLists.txt:106 (enable_language):
The CMAKE_C_COMPILER:

/usr/bin/gcc-6

is not a full path to an existing compiler tool.

Tell CMake where to find the compiler by setting either the environment
variable "CC" or the CMake cache entry CMAKE_C_COMPILER to the full path to
the compiler, or to the compiler name if it is in the PATH.

-- Configuring incomplete, errors occurred!
See also "/home/aistudio/opencv-4.3.0/build/CMakeFiles/CMakeOutput.log".
See also "/home/aistudio/opencv-4.3.0/build/CMakeFiles/CMakeError.log".`

The error is " is not a full path to an existing compiler tool."
How to fix it?Thanks.

You have to modify the flags accordingly with your computer configuration. The flag '-D CMAKE_C_COMPILER=/usr/bin/gcc-6' seems to be wrong in your case. Set it correctly or do not include it, CMAKE will try to guess your version.

@taf2
Copy link

taf2 commented Nov 1, 2020

Thank you for writing this up I discovered to get CUDNN working with your build I had to do the following extra steps.

sudo apt install libcudnn7-dev  libcudnn7-doc  libcudnn7 nvidia-container-csv-cudnn
 -D CUDNN_INCLUDE_DIR=/usr/include \
-D CUDNN_LIBRARY=/usr/lib64/libcudnn_static_v7.a \
-D CUDNN_VERSION=7.6.3

@kremerf
Copy link

kremerf commented Nov 20, 2020

I am trying to get this to work on a Jetson Xavier NX.
The installation goes through without issues.

Upon running ~$ g++ pkg-config opencv --cflags --libs -o test test.cpp

/tmp/ccQ1tpt7.o: In function `main':
test.cpp:(.text+0x5c): undefined reference to `cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)'
test.cpp:(.text+0x70): undefined reference to `cv::cuda::GpuMat::defaultAllocator()'
test.cpp:(.text+0x80): undefined reference to `cv::cuda::GpuMat::defaultAllocator()'
test.cpp:(.text+0xa4): undefined reference to `cv::cuda::GpuMat::upload(cv::_InputArray const&)'
test.cpp:(.text+0xc8): undefined reference to `cv::cuda::Stream::Null()'
test.cpp:(.text+0xec): undefined reference to `cv::cuda::bilateralFilter(cv::_InputArray const&, cv::_OutputArray const&, int, float, float, int, cv::cuda::Stream&)'
test.cpp:(.text+0x11c): undefined reference to `cv::cuda::GpuMat::download(cv::_OutputArray const&) const'
/tmp/ccQ1tpt7.o: In function `cv::Mat::~Mat()':
test.cpp:(.text._ZN2cv3MatD2Ev[_ZN2cv3MatD5Ev]+0x34): undefined reference to `cv::fastFree(void*)'
/tmp/ccQ1tpt7.o: In function `cv::Mat::release()':
test.cpp:(.text._ZN2cv3Mat7releaseEv[_ZN2cv3Mat7releaseEv]+0x58): undefined reference to `cv::Mat::deallocate()'
/tmp/ccQ1tpt7.o: In function `cv::cuda::GpuMat::~GpuMat()':
test.cpp:(.text._ZN2cv4cuda6GpuMatD2Ev[_ZN2cv4cuda6GpuMatD5Ev]+0x10): undefined reference to `cv::cuda::GpuMat::release()'
/tmp/ccQ1tpt7.o:(.data.rel.local.DW.ref._ZTIN2cv9ExceptionE[DW.ref._ZTIN2cv9ExceptionE]+0x0): undefined reference to `typeinfo for cv::Exception'
collect2: error: ld returned 1 exit status

This one seems fine, as the modules I would like to use in the future are there.

pkg-config opencv --cflags --libs
-I/usr/local/include/opencv4/opencv -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_gapi -lopencv_stitching -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_cudabgsegm -lopencv_cudafeatures2d -lopencv_cudaobjdetect -lopencv_cudastereo -lopencv_dnn_objdetect -lopencv_dnn_superres -lopencv_dpm -lopencv_highgui -lopencv_face -lopencv_freetype -lopencv_fuzzy -lopencv_hdf -lopencv_hfs -lopencv_img_hash -lopencv_line_descriptor -lopencv_quality -lopencv_reg -lopencv_rgbd -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_phase_unwrapping -lopencv_superres -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_dnn -lopencv_plot -lopencv_videostab -lopencv_cudaoptflow -lopencv_optflow -lopencv_cudalegacy -lopencv_videoio -lopencv_cudawarping -lopencv_xfeatures2d -lopencv_shape -lopencv_ml -lopencv_ximgproc -lopencv_video -lopencv_xobjdetect -lopencv_objdetect -lopencv_calib3d -lopencv_imgcodecs -lopencv_features2d -lopencv_flann -lopencv_xphoto -lopencv_photo -lopencv_cudaimgproc -lopencv_cudafilters -lopencv_imgproc -lopencv_cudaarithm -lopencv_core -lopencv_cudev

The alternatively suggested version seems to not work in my place.

~$ g++ -o test test.cpp pkg-config opencv --cflags --libs
g++: error: pkg-config: No such file or directory
g++: error: opencv: No such file or directory
g++: error: unrecognized command line option ‘--cflags’
g++: error: unrecognized command line option ‘--libs’

Anyone can point something out?

g++ pkg-config opencv --cflags --libs -o test test.cpp -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_imgcodecs -lopencv_cudaarithm -lopencv_cudaimgproc
This one execute without error.

~$ ./test
Error: OpenCV(4.2.0) /home/xavier/opencv_contrib-4.2.0/modules/cudaimgproc/src/cuda/bilateral_filter.cu:140: error: (-217:Gpu API call) invalid configuration argument in function 'bilateral_caller'

0.28761

@raulqf
Copy link
Author

raulqf commented Nov 21, 2020

I am trying to get this to work on a Jetson Xavier NX.
The installation goes through without issues.

Upon running ~$ g++ pkg-config opencv --cflags --libs -o test test.cpp

/tmp/ccQ1tpt7.o: In function `main':
test.cpp:(.text+0x5c): undefined reference to `cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)'
test.cpp:(.text+0x70): undefined reference to `cv::cuda::GpuMat::defaultAllocator()'
test.cpp:(.text+0x80): undefined reference to `cv::cuda::GpuMat::defaultAllocator()'
test.cpp:(.text+0xa4): undefined reference to `cv::cuda::GpuMat::upload(cv::_InputArray const&)'
test.cpp:(.text+0xc8): undefined reference to `cv::cuda::Stream::Null()'
test.cpp:(.text+0xec): undefined reference to `cv::cuda::bilateralFilter(cv::_InputArray const&, cv::_OutputArray const&, int, float, float, int, cv::cuda::Stream&)'
test.cpp:(.text+0x11c): undefined reference to `cv::cuda::GpuMat::download(cv::_OutputArray const&) const'
/tmp/ccQ1tpt7.o: In function `cv::Mat::~Mat()':
test.cpp:(.text._ZN2cv3MatD2Ev[_ZN2cv3MatD5Ev]+0x34): undefined reference to `cv::fastFree(void*)'
/tmp/ccQ1tpt7.o: In function `cv::Mat::release()':
test.cpp:(.text._ZN2cv3Mat7releaseEv[_ZN2cv3Mat7releaseEv]+0x58): undefined reference to `cv::Mat::deallocate()'
/tmp/ccQ1tpt7.o: In function `cv::cuda::GpuMat::~GpuMat()':
test.cpp:(.text._ZN2cv4cuda6GpuMatD2Ev[_ZN2cv4cuda6GpuMatD5Ev]+0x10): undefined reference to `cv::cuda::GpuMat::release()'
/tmp/ccQ1tpt7.o:(.data.rel.local.DW.ref._ZTIN2cv9ExceptionE[DW.ref._ZTIN2cv9ExceptionE]+0x0): undefined reference to `typeinfo for cv::Exception'
collect2: error: ld returned 1 exit status

This one seems fine, as the modules I would like to use in the future are there.

pkg-config opencv --cflags --libs
-I/usr/local/include/opencv4/opencv -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_gapi -lopencv_stitching -lopencv_aruco -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_cudabgsegm -lopencv_cudafeatures2d -lopencv_cudaobjdetect -lopencv_cudastereo -lopencv_dnn_objdetect -lopencv_dnn_superres -lopencv_dpm -lopencv_highgui -lopencv_face -lopencv_freetype -lopencv_fuzzy -lopencv_hdf -lopencv_hfs -lopencv_img_hash -lopencv_line_descriptor -lopencv_quality -lopencv_reg -lopencv_rgbd -lopencv_saliency -lopencv_stereo -lopencv_structured_light -lopencv_phase_unwrapping -lopencv_superres -lopencv_surface_matching -lopencv_tracking -lopencv_datasets -lopencv_text -lopencv_dnn -lopencv_plot -lopencv_videostab -lopencv_cudaoptflow -lopencv_optflow -lopencv_cudalegacy -lopencv_videoio -lopencv_cudawarping -lopencv_xfeatures2d -lopencv_shape -lopencv_ml -lopencv_ximgproc -lopencv_video -lopencv_xobjdetect -lopencv_objdetect -lopencv_calib3d -lopencv_imgcodecs -lopencv_features2d -lopencv_flann -lopencv_xphoto -lopencv_photo -lopencv_cudaimgproc -lopencv_cudafilters -lopencv_imgproc -lopencv_cudaarithm -lopencv_core -lopencv_cudev

The alternatively suggested version seems to not work in my place.

~$ g++ -o test test.cpp pkg-config opencv --cflags --libs
g++: error: pkg-config: No such file or directory
g++: error: opencv: No such file or directory
g++: error: unrecognized command line option ‘--cflags’
g++: error: unrecognized command line option ‘--libs’

Anyone can point something out?

g++ pkg-config opencv --cflags --libs -o test test.cpp -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_imgcodecs -lopencv_cudaarithm -lopencv_cudaimgproc
This one execute without error.

~$ ./test
Error: OpenCV(4.2.0) /home/xavier/opencv_contrib-4.2.0/modules/cudaimgproc/src/cuda/bilateral_filter.cu:140: error: (-217:Gpu API call) invalid configuration argument in function 'bilateral_caller'

0.28761

Hi,

In your first try, you missed the back quote character `

   $ g++ `pkg-config opencv --cflags --libs` -o test test.cpp
   $ ./test

So, is it already working?

@raulqf
Copy link
Author

raulqf commented Nov 21, 2020

Thank you for writing this up I discovered to get CUDNN working with your build I had to do the following extra steps.

sudo apt install libcudnn7-dev  libcudnn7-doc  libcudnn7 nvidia-container-csv-cudnn
 -D CUDNN_INCLUDE_DIR=/usr/include \
-D CUDNN_LIBRARY=/usr/lib64/libcudnn_static_v7.a \
-D CUDNN_VERSION=7.6.3

I will include at the end of the gist your proposal @taf2.

Thanks.

@kremerf
Copy link

kremerf commented Nov 23, 2020

In your first try, you missed the back quote character `

$ g++ pkg-config opencv --cflags --libs -o test test.cpp
$ ./test

So, is it already working?

I omitted them as they screwed up my comments format. So it is the same result unfortunately.

This one worked.
g++ pkg-config opencv --cflags --libs -o test test.cpp -lm -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_imgcodecs - lopencv_cudaarithm -lopencv_cudaimgproc && ./test

@timsu92
Copy link

timsu92 commented Jan 14, 2021

I am facing the following issue: I previously had OpenCV 3.2 in my system (Ubuntu 18.04 LTS, CUDA 10.1) that I installed via: sudo apt-get install libopencv-dev python-opencv without CUDA support. Now that I am looking for CUDA support, I installed OpenCV 4.2.0 following the instructions given by you @raulqf (Thank you so much for this!), except for the virtual environment creation part! Now, the problem I am facing is that pkg-config could not locate OpenCV4.2 and it is still pointing to the older version (OpenCV 3.2). I even removed all the packages pertaining to the older version. Now pkg-config simply cannot locate a package name opencv at all. Suggestion made: Try adding the directory that contains opencv.pc to the environment variable PKG_CONFIG_PATH. Where is this file located?

Hi. It is really to understand how pkg-config works. Basically the file contains the information to locate the header files and the libs to be used during compilation. The name opencv.pc can be modified in the installation process, in fact, it was defined in this flag **-D OPENCV_PC_FILE_NAME=opencv.pc *. So, you could define any other name. One suggestion would be to include your opencv version within the filename --> opencv420.pc. If you change the name you must use the new file name when invoking pkg-config -> g++ pkg-config opencv420 --cflags --libs -o test test.cpp . To find your opencv.pc you could use locate opencv* (remember to update the database sudo updatedb) or use find --> find /usr/ --name opencv ... The are also some environment variables used by pkg-config pointing to the PKG_CONFIG_PATH

To sum up, you could redo the process defining a new filename for opencv.pc or you could modify the current opencv.pc to point to the correct directory. It is a file text that can be modified by any text editor. Once you open it, you would find that the directories are wrongly defined. According to the installation, they must point to /usr/local/lib for the libraries and /usr/loca/include for the header files.

In this step, I succeeded with g++ -o test test.cpp `pkg-config opencv --cflags --libs`
Otherwise, the c++ test program would get lots of errors start with cv:: while compiling.

@timsu92
Copy link

timsu92 commented Jan 14, 2021

Hi,

I followed the guide line-for-line using the following configuration:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_C_COMPILER=/usr/bin/gcc-6 \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D INSTALL_C_EXAMPLES=OFF \
-D WITH_TBB=ON \
-D WITH_CUDA=ON \
-D BUILD_opencv_cudacodec=OFF \
-D ENABLE_FAST_MATH=1 \
-D CUDA_FAST_MATH=1 \
-D WITH_CUBLAS=1 \
-D WITH_V4L=ON \
-D WITH_QT=OFF \
-D WITH_OPENGL=ON \
-D WITH_GSTREAMER=ON \
-D OPENCV_GENERATE_PKGCONFIG=ON \
-D OPENCV_PC_FILE_NAME=opencv.pc \
-D OPENCV_ENABLE_NONFREE=ON \
-D OPENCV_PYTHON3_INSTALL_PATH=~/anaconda3/envs/cv2/lib/python3.6/site-packages \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.2.0/modules \
-D PYTHON_EXECUTABLE=~/anaconda3/envs/cv2/bin/python \
-D WITH_CUDNN=ON \
-D OPENCV_DNN_CUDA=ON \
-D CUDA_ARCH_BIN=6.1 \
-D BUILD_EXAMPLES=OFF ..

There are no build-time errors, I made sure to do a make install and ldconfig, but still, there are no Python bindings generated in the ~/anaconda3/envs/cv2/lib/python3.6/site-packages directory.

I also tried with virtualenv instead of Anaconda, but the result was the same. All CUDA libraries are detected correctly and I've been able to build and install other libraries (like DLIB) just fine:

--   NVIDIA CUDA:                   YES (ver 10.0, CUFFT CUBLAS FAST_MATH)
--     NVIDIA GPU arch:             61
--     NVIDIA PTX archs:
-- 
--   cuDNN:                         YES (ver 7.6.2)

Is there something else that I might be missing?

Cheers

@vladislavdonchev How about the info below about Python Interpreter just like the info you gave about Nvidia GPU?
I failed to build Python3 binding using Conda(but configuration would say success just like yours); CMake and I can't find Python Library. Instead, I deleted the build folder and used virtualenv to rebuild.

@Quizzarex
Copy link

Quizzarex commented Jan 14, 2021

Thank you for your tutorial!
How can I sort out the errors?
I tried:
sudo cp ~/opencv/build/unix-install/opencv.pc /usr/local/lib/pkgconfig/
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
BUT
g++ pkg-config opencv --cflags --libs -o test test.cpp
/tmp/cc3tkJEc.o: In function main': test.cpp:(.text+0x7e): undefined reference to cv::imread(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int)'
test.cpp:(.text+0x9d): undefined reference to cv::cuda::GpuMat::defaultAllocator()' test.cpp:(.text+0xb7): undefined reference to cv::cuda::GpuMat::defaultAllocator()'
...

I had the same error and then i change the order of include files and library like below:
g++ test.cpp pkg-config opencv --cflags --libs
(file source code is at front)

This should really be changed in the gist, had same issue and had to remove source in front of pkg-config string like this:
g++ test.cpp `pkg-config opencv --cflags --libs` -o test

@raulqf
Copy link
Author

raulqf commented Jan 17, 2021

Thank you for your tutorial!
How can I sort out the errors?
I tried:
sudo cp ~/opencv/build/unix-install/opencv.pc /usr/local/lib/pkgconfig/
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
BUT
g++ pkg-config opencv --cflags --libs -o test test.cpp
/tmp/cc3tkJEc.o: In function main': test.cpp:(.text+0x7e): undefined reference to cv::imread(std::__cxx11::basic_string<char, std::char_traits, std::allocator > const&, int)'
test.cpp:(.text+0x9d): undefined reference to cv::cuda::GpuMat::defaultAllocator()' test.cpp:(.text+0xb7): undefined reference to cv::cuda::GpuMat::defaultAllocator()'
...

I had the same error and then i change the order of include files and library like below:
g++ test.cpp pkg-config opencv --cflags --libs
(file source code is at front)

This should really be changed in the gist, had same issue and had to remove source in front of pkg-config string like this:
g++ test.cpp pkg-config opencv --cflags --libs -o test

I have already changed it.

@AtoLrn
Copy link

AtoLrn commented Jan 20, 2021

Hello, i have the same issue than
@basit26374

I did sudo make install and the issue is still here, I think everything went well but i can't find either
" ../../lib/python3/cv2.cpython-36m-aarch64-linux-gnu.so"
Or
" ~/.virtualenvs/cv/lib/python3.6/site-packages/cv2"

[100%] Linking CXX executable ../../bin/example_tutorial_imgcodecs_imwrite
[100%] Built target example_tutorial_npr_demo
[100%] Built target example_tutorial_core_various
[100%] Built target example_tutorial_goodFeaturesToTrack_Demo
[100%] Built target example_tutorial_imgcodecs_imwrite
[100%] Built target example_tutorial_cloning_gui

[100%] Linking CXX shared module ../../lib/python3/cv2.cpython-36m-aarch64-linux-gnu.so
[100%] Built target opencv_python3

Does anyone have an idea ?
Thanks

@timsu92
Copy link

timsu92 commented Jan 21, 2021

Did you sudo make install ?

@AtoLrn
Copy link

AtoLrn commented Jan 21, 2021

Did you sudo make install ?

Yes

@kfirsa
Copy link

kfirsa commented Feb 9, 2021

@AtoLrn i had the same issue. i have skipped numpy install within venv

@gewi1011
Copy link

gewi1011 commented Feb 18, 2021

When i try to run the test script i get the error: "fatal error: opencv2/cudaarithm.hpp: No such file or directory #include <opencv2/cudaarithm.hpp>"
It obviously don't know the library
Or do i have to put the test.cpp file in a special path?

But i found it at /home/opencv_contrib-4.2.0/modules/cudaarithm
How can i manage this problem? @raulqf

And second: after setting up the python bindings like written in your documentary and running my python script, i always get the error "AttributeError: 'module' object has no attribute 'cuda_GpuMat'", maybe this error is caused by the fact that i'm running this python script in a ROS Node, and everything is not adjust correctly.

Thanks for any help!!
nvidia and cuda are getting on my nerves...

@raulqf
Copy link
Author

raulqf commented Feb 19, 2021

When i try to run the test script i get the error: "fatal error: opencv2/cudaarithm.hpp: No such file or directory #include <opencv2/cudaarithm.hpp>"
It obviously don't know the library
Or do i have to put the test.cpp file in a special path?

But i found it at /home/opencv_contrib-4.2.0/modules/cudaarithm
How can i manage this problem? @raulqf

And second: after setting up the python bindings like written in your documentary and running my python script, i always get the error "AttributeError: 'module' object has no attribute 'cuda_GpuMat'", maybe this error is caused by the fact that i'm running this python script in a ROS Node, and everything is not adjust correctly.

Thanks for any help!!
nvidia and cuda are getting on my nerves...

Hi,

Your problem is that your solutions is not able to locate the header files. Please, run in your terminal the pkg-config command and check the output is correct concerning your installation:

   $ pkg-config opencv --cflags --libs

@raulqf
Copy link
Author

raulqf commented Feb 19, 2021

I am wondering to update this GIST withUbuntu 20.04 and latest version of OpenCV & CUDA or to do it in a new GIST. What do you think?

@utamadonny
Copy link

utamadonny commented Mar 7, 2021

I am wondering to update this GIST withUbuntu 20.04 and latest version of OpenCV & CUDA or to do it in a new GIST. What do you think?

yes please. update this gist

@Sumerov
Copy link

Sumerov commented Mar 15, 2021

When i try to run the test script i get the error: "fatal error: opencv2/cudaarithm.hpp: No such file or directory #include <opencv2/cudaarithm.hpp>"
It obviously don't know the library
Or do i have to put the test.cpp file in a special path?
But i found it at /home/opencv_contrib-4.2.0/modules/cudaarithm
How can i manage this problem? @raulqf
And second: after setting up the python bindings like written in your documentary and running my python script, i always get the error "AttributeError: 'module' object has no attribute 'cuda_GpuMat'", maybe this error is caused by the fact that i'm running this python script in a ROS Node, and everything is not adjust correctly.
Thanks for any help!!
nvidia and cuda are getting on my nerves...

Hi,

Your problem is that your solutions is not able to locate the header files. Please, run in your terminal the pkg-config command and check the output is correct concerning your installation:

   $ pkg-config opencv --cflags --libs

Hey, and when its not what now?, when I am getting this:
-I/usr/include/opencv4/opencv -I/usr/include/opencv4 -lopencv_dnn -lopencv_gapi -lopencv_highgui -lopencv_ml -lopencv_objdetect -lopencv_photo -lopencv_stitching -lopencv_video -lopencv_calib3d -lopencv_features2d -lopencv_flann -lopencv_videoio -lopencv_imgcodecs -lopencv_imgproc -lopencv_core

I also have cuda succesfully installed and libraries are in include path

@lingcong-k
Copy link

lingcong-k commented Mar 28, 2021

Hi, I am trying to build opencv with cuda support in dockerfile together with other stuff.

But no matter what version of opencv, I always have the following error:

Scanning dependencies of target ade
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/alloc.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/assert.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/check_cycles.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/edge.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/execution_engine.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/graph.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/memory_accessor.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/memory_descriptor.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/memory_descriptor_ref.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/memory_descriptor_view.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/metadata.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/metatypes.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/node.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/passes/communications.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/search.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/subgraphs.cpp.o
[ 22%] Building CXX object modules/CMakeFiles/ade.dir/__/3rdparty/ade/ade-0.1.1f/sources/ade/source/topological_sort.cpp.o
[ 23%] Linking CXX static library ../lib/libade.a
[ 23%] Built target ade
Scanning dependencies of target opencv_videoio_plugins
[ 23%] Built target opencv_videoio_plugins
Scanning dependencies of target opencv_cudev
[ 24%] Building CXX object modules/cudev/CMakeFiles/opencv_cudev.dir/src/stub.cpp.o
[ 24%] Linking CXX shared library ../../lib/libopencv_cudev.so
/usr/bin/ld: cannot find -ltrue
/usr/bin/ld: cannot find -ltrue
collect2: error: ld returned 1 exit status
make[2]: *** [modules/cudev/CMakeFiles/opencv_cudev.dir/build.make:105: lib/libopencv_cudev.so.4.5.0] Error 1
make[1]: *** [CMakeFiles/Makefile2:4208: modules/cudev/CMakeFiles/opencv_cudev.dir/all] Error 2
make: *** [Makefile:182: all] Error 2

My environment is:

am using this pytorch container image nvcr.io/nvidia/pytorch:20.12-py3
(I have to use an pytorch container image in order to comply with other stuff)

cuda 11.1.1
python 3.8
ubuntu 20.04
Conda

more detailed info here: https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel_20-12.html#rel_20-12

The cmake outputs looks pretty fine for me (except for one warning):

-- 
-- General configuration for OpenCV 4.5.0 =====================================
--   Version control:               unknown
-- 
--   Extra modules:
--     Location (extra):            /opt/opencv_contrib-4.5.0/modules
--     Version control (extra):     unknown
-- 
--   Platform:
--     Timestamp:                   2021-03-26T21:47:27Z
--     Host:                        Linux 5.8.0-45-generic x86_64
--     CMake:                       3.18.2
--     CMake generator:             Unix Makefiles
--     CMake build tool:            /usr/bin/make
--     Configuration:               RELEASE
-- 
--   CPU/HW features:
--     Baseline:                    SSE SSE2 SSE3
--       requested:                 SSE3
--     Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX
--       requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
--       SSE4_1 (15 files):         + SSSE3 SSE4_1
--       SSE4_2 (1 files):          + SSSE3 SSE4_1 POPCNT SSE4_2
--       FP16 (0 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX
--       AVX (4 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
--       AVX2 (29 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
--       AVX512_SKX (4 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX
-- 
--   C/C++:
--     Built as dynamic libs?:      YES
--     C++ standard:                11
--     C++ Compiler:                /usr/bin/c++  (ver 9.3.0)
--     C++ flags (Release):         -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG  -DNDEBUG
--     C++ flags (Debug):           -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winit-self -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -g  -O0 -DDEBUG -D_DEBUG
--     C Compiler:                  /usr/bin/cc
--     C flags (Release):           -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -O3 -DNDEBUG  -DNDEBUG
--     C flags (Debug):             -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Winit-self -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections  -msse -msse2 -msse3 -fvisibility=hidden -g  -O0 -DDEBUG -D_DEBUG
--     Linker flags (Release):      -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a   -Wl,--gc-sections -Wl,--as-needed  
--     Linker flags (Debug):        -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a   -Wl,--gc-sections -Wl,--as-needed  
--     ccache:                      NO
--     Precompiled headers:         NO
--     Extra dependencies:          m pthread cudart_static dl rt nppc nppial nppicc true nppidei nppif nppig nppim nppist nppisu nppitc npps cublas cudnn cufft -L/usr/local/cuda/lib64 -L/usr/lib/x86_64-linux-gnu
--     3rdparty dependencies:
-- 
--   OpenCV modules:
--     To be built:                 alphamat aruco bgsegm bioinspired calib3d ccalib core cudaarithm cudabgsegm cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python2 python3 quality rapid reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab ximgproc xobjdetect xphoto
--     Disabled:                    cudacodec world xfeatures2d
--     Disabled by dependency:      sfm
--     Unavailable:                 cnn_3dobj cvv hdf java js julia matlab ovis viz
--     Applications:                perf_tests apps
--     Documentation:               NO
--     Non-free algorithms:         NO
-- 
--   GUI: 
--     GTK+:                        YES (ver 2.24.32)
--       GThread :                  YES (ver 2.64.6)
--       GtkGlExt:                  NO
--     OpenGL support:              NO
--     VTK support:                 NO
-- 
--   Media I/O: 
--     ZLib:                        /usr/lib/x86_64-linux-gnu/libz.so (ver 1.2.11)
--     JPEG:                        /usr/lib/x86_64-linux-gnu/libjpeg.so (ver 80)
--     WEBP:                        build (ver encoder: 0x020f)
--     PNG:                         /usr/lib/x86_64-linux-gnu/libpng.so (ver 1.6.37)
--     TIFF:                        build (ver 42 - 4.0.10)
--     JPEG 2000:                   build (ver 2.3.1)
--     OpenEXR:                     build (ver 2.3.0)
--     HDR:                         YES
--     SUNRASTER:                   YES
--     PXM:                         YES
--     PFM:                         YES
-- 
--   Video I/O:
--     DC1394:                      NO
--     FFMPEG:                      YES
--       avcodec:                   YES (58.54.100)
--       avformat:                  YES (58.29.100)
--       avutil:                    YES (56.31.100)
--       swscale:                   YES (5.5.100)
--       avresample:                NO
--     GStreamer:                   NO
--     v4l/v4l2:                    YES (linux/videodev2.h)
-- 
--   Parallel framework:            pthreads
-- 
--   Trace:                         YES (with Intel ITT)
-- 
--   Other third-party libraries:
--     Intel IPP:                   2020.0.0 Gold [2020.0.0]
--            at:                   /opt/opencv-4.5.0/build/3rdparty/ippicv/ippicv_lnx/icv
--     Intel IPP IW:                sources (2020.0.0)
--               at:                /opt/opencv-4.5.0/build/3rdparty/ippicv/ippicv_lnx/iw
--     Lapack:                      YES (/opt/conda/lib/libmkl_intel_lp64.so /opt/conda/lib/libmkl_sequential.so /opt/conda/lib/libmkl_core.so /opt/conda/lib/libmkl_intel_lp64.so /opt/conda/lib/libmkl_sequential.so /opt/conda/lib/libmkl_core.so /opt/conda/lib/libmkl_intel_lp64.so /opt/conda/lib/libmkl_sequential.so /opt/conda/lib/libmkl_core.so -lpthread -lm -ldl)
--     Eigen:                       YES (ver 3.3.7)
--     Custom HAL:                  NO
--     Protobuf:                    build (3.5.1)
-- 
--   NVIDIA CUDA:                   YES (ver 11.1, CUFFT CUBLAS)
--     NVIDIA GPU arch:             35 37 50 52 60 61 70 75 80 86
--     NVIDIA PTX archs:
-- 
--   cuDNN:                         YES (ver 8.0.5)
-- 
--   OpenCL:                        YES (no extra features)
--     Include path:                /opt/opencv-4.5.0/3rdparty/include/opencl/1.2
--     Link libraries:              Dynamic load
-- 
--   Python 2:
--     Interpreter:                 /usr/bin/python2.7 (ver 2.7.18)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.18)
--     numpy:                       /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.16.5)
--     install path:                lib/python2.7/dist-packages/cv2/python-2.7
-- 
--   Python 3:
--     Interpreter:                 /opt/conda/bin/python3.8 (ver 3.8.5)
--     Libraries:                   /opt/conda/lib/libpython3.8m.so
--     numpy:                       /opt/conda/lib/python3.8/site-packages/numpy/core/include (ver 1.19.2)
--     install path:                /opt/conda/lib/python3.8/site-packages/cv2/python-3.8
-- 
--   Python (for build):            /usr/bin/python2.7
-- 
--   Java:                          
--     ant:                         NO
--     JNI:                         NO
--     Java wrappers:               NO
--     Java tests:                  NO
-- 
--   Install to:                    /usr/local
-- -----------------------------------------------------------------
-- 
-- Configuring done
CMake Warning at cmake/OpenCVUtils.cmake:1508 (add_library):
  Cannot generate a safe runtime search path for target opencv_core because
  files in some directories may conflict with libraries in implicit
  directories:

    runtime library [libz.so.1] in /usr/lib/x86_64-linux-gnu may be hidden by files in:
      /opt/conda/lib

  Some of these libraries may not be found correctly.
Call Stack (most recent call first):
  cmake/OpenCVModule.cmake:930 (ocv_add_library)
  cmake/OpenCVModule.cmake:851 (_ocv_create_module)
  modules/core/CMakeLists.txt:104 (ocv_create_module)

the command am using is:

RUN apt-get update && apt-get upgrade -y &&\
    # Install build tools, build dependencies and python
    apt-get install -y \
	    python3-pip \
        build-essential \
        cmake \
        git \
        wget \
        unzip \
        yasm \
        pkg-config \
        libswscale-dev \
        libtbb2 \
        libtbb-dev \
        libjpeg-dev \
        libpng-dev \
        libtiff-dev \
        libavformat-dev \
        libpq-dev \
        libxine2-dev \
        libglew-dev \
        libtiff5-dev \
        zlib1g-dev \
        libjpeg-dev \
        libavcodec-dev \
        libavformat-dev \
        libavutil-dev \
        libpostproc-dev \
        libswscale-dev \
        libeigen3-dev \
        libtbb-dev \
        libgtk2.0-dev \
        pkg-config \
        libopenblas-dev \
        liblapack-dev \
        libatlas-base-dev \
        ## Python
        python-dev \
        python-numpy \
        python3-dev \
        python3-numpy \
        python3.8-dev \
        libpython3-dev \
        libpython3.8-dev \
        libpython2.7-dev \
    && rm -rf /var/lib/apt/lists/*

ARG OPENCV_VERSION=4.5.0

# RUN cd /usr/include &&\
# ln -s python3.6m python3.6

RUN cd /opt/ &&\
    # Download and unzip OpenCV and opencv_contrib and delte zip files
    wget https://github.com/opencv/opencv/archive/$OPENCV_VERSION.zip &&\
    unzip $OPENCV_VERSION.zip &&\
    rm $OPENCV_VERSION.zip &&\
    wget https://github.com/opencv/opencv_contrib/archive/$OPENCV_VERSION.zip &&\
    unzip ${OPENCV_VERSION}.zip &&\
    rm ${OPENCV_VERSION}.zip &&\
    # Create build folder and switch to it
    mkdir /opt/opencv-${OPENCV_VERSION}/build && cd /opt/opencv-${OPENCV_VERSION}/build &&\
    # Cmake configure
    cmake \
        -DBUILD_opencv_python3=yes \
        -DHAVE_opencv_python3=ON \
        -DPYTHON3_EXECUTABLE=/opt/conda/bin/python3.8 \
        -DPYTHON3_LIBRARY=/opt/conda/lib/libpython3.8m.so \
        -DOPENCV_PYTHON3_INSTALL_PATH=/opt/conda/lib/python3.8/site-packages \
        -DPYTHON3_INCLUDE_DIR=/opt/conda/include \
        -DPYTHON3_PACKAGES_PATH= /opt/conda/lib/site-packages \
        -DPYTHON3_NUMPY_INCLUDE_DIR= /opt/conda/lib/python3.8/site-packages/numpy/core/include \
        -DOPENCV_EXTRA_MODULES_PATH=/opt/opencv_contrib-${OPENCV_VERSION}/modules \
        -DWITH_CUDA=ON \
        -DCMAKE_BUILD_TYPE=RELEASE \
        -DWITH_CUDNN=ON \
        -DOPENCV_DNN_CUDA=ON \
        -DWITH_OPENGL=ON \
        -DCUDA_nppicom_LIBRARY=true\
        -DCUDA_nppicom_LIBRARY=true\
        -DENABLE_PRECOMPILED_HEADERS=OFF \
        -DBUILD_TIFF=ON \
        -DBUILD_TESTS=OFF \
#         -DCUDA_ARCH_BIN=7.5 \
        # Install path will be /usr/local/lib (lib is implicit)
        -DCMAKE_INSTALL_PREFIX=/usr/local \
        -DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda \
        -DBUILD_opencv_cudacodec=OFF \
        -DBUILD_opencv_xfeatures2d=OFF \
#         -DCMAKE_INSTALL_PREFIX=$(python3.6 -c "import sys; print(sys.prefix)") \
#         -DPYTHON_EXECUTABLE=$(which python3.6) \
#         -DPYTHON_INCLUDE_DIR=$(python3.6 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
#         -DPYTHON_PACKAGES_PATH=$(python3.6 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
        .. &&\
    # Make
    make && \
    # Install to /usr/local/lib
    make install && \
    ldconfig &&\
    # Remove OpenCV sources and build folder
    rm -rf /opt/opencv-${OPENCV_VERSION} && rm -rf /opt/opencv_contrib-${OPENCV_VERSION}

It seems it cant find libtrue.so but I googled and checked many ino, couldnt find what i should install for that?

Can someone please help, being stuck for 2 days ;( Thank you!

@dylode
Copy link

dylode commented Apr 7, 2021

-DCUDA_nppicom_LIBRARY=true\

Replace -DCUDA_nppicom_LIBRARY=true\ with -DCUDA_nppicom_LIBRARY=ON\

@lingcong-k

@lingcong-k
Copy link

lingcong-k commented Apr 8, 2021

-DCUDA_nppicom_LIBRARY=true\

Replace -DCUDA_nppicom_LIBRARY=true\ with -DCUDA_nppicom_LIBRARY=ON\

@lingcong-k

thanks.. yes that was the issue :)

@Almeida-a
Copy link

Almeida-a commented May 16, 2021

When i try to run the test script i get the error: "fatal error: opencv2/cudaarithm.hpp: No such file or directory #include <opencv2/cudaarithm.hpp>"
It obviously don't know the library
Or do i have to put the test.cpp file in a special path?

But i found it at /home/opencv_contrib-4.2.0/modules/cudaarithm
How can i manage this problem? @raulqf

I'm having the same problem

@PhuongNDVN
Copy link

PhuongNDVN commented May 17, 2021

Plz help me solve this bug. I built opencv successfully but when I tried to run test.cpp, it failed

This is my config (my gpu is Nvidia Geforce 1080 Ti):

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc-7 -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=ON -D WITH_TBB=ON -D WITH_CUDA=ON -D BUILD_opencv_cudacodec=OFF -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_PC_FILE_NAME=opencv.pc -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_EXTRA_MODULES_PATH= ~/opencv_contrib-4.4.0/modules -D BUILD_EXAMPLES=ON -D WITH_CUDNN=ON -D OPENCV_DNN_CUDA=ON -D CUDA_ARCH_BIN=6.1 -D CUDA_ARCH_PTX=6.1 -D OPENCV_PYTHON3_INSTALL_PATH= ~/ML/venv/lib/python3.6/site-packages -D PYTHON_EXECUTABLE= ~/ML/venv/bin/python ..

-- Could NOT find OpenJPEG (minimal suitable version: 2.0, recommended version >= 2.3.1)
-- Could NOT find Jasper (missing: JASPER_LIBRARIES JASPER_INCLUDE_DIR)
-- Found ZLIB: /usr/lib/x86_64-linux-gnu/libz.so (found version "1.2.11")
-- Found TBB (env): /usr/lib/x86_64-linux-gnu/libtbb.so
-- found Intel IPP (ICV version): 2020.0.0 [2020.0.0 Gold]
-- at: /home/phuongnd/opencv-4.4.0/build/3rdparty/ippicv/ippicv_lnx/icv
-- found Intel IPP Integration Wrappers sources: 2020.0.0
-- at: /home/phuongnd/opencv-4.4.0/build/3rdparty/ippicv/ippicv_lnx/iw
-- CUDA detected: 10.2
-- CUDA: Using CUDA_ARCH_BIN=6.1
-- CUDA NVCC target flags: -gencode;arch=compute_61,code=sm_61;-D_FORCE_INLINES;-gencode;arch=compute_61,code=compute_61
-- Could not find OpenBLAS include. Turning OpenBLAS_FOUND off
-- Could not find OpenBLAS lib. Turning OpenBLAS_FOUND off
-- Could NOT find Atlas (missing: Atlas_CLAPACK_INCLUDE_DIR)

-- NVIDIA CUDA: YES (ver 10.2, CUFFT CUBLAS FAST_MATH)
-- NVIDIA GPU arch: 61
-- NVIDIA PTX archs: 61

-- cuDNN: YES (ver 7.6.5)

When I tried to run the test.cpp I get the following error:

Error: OpenCV(4.4.0) /home/phuongnd/opencv-4.4.0/modules/core/src/cuda/gpu_mat.cu:224: error: (-217:Gpu API call) unknown error in function 'upload'

Thanks

@raulqf
Copy link
Author

raulqf commented Jul 9, 2021

Hi all, I've recently updated the gist. Kindly Regards!

@asandberg17
Copy link

asandberg17 commented Jul 23, 2021

Hi, I am compiling on a Nvidia Xavier AGX which has CC 7.2 so I build with the following flags:
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_CUDA=ON -D BUILD_opencv_cudacodec=OFF -D WITH_CUDNN=ON -D OPENCV_DNN_CUDA=ON -D CUDA_ARCH_BIN=7.2 -D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_PC_FILE_NAME=opencv.pc -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_PYTHON3_INSTALL_PATH=/.virtualenvs/cv/lib/python3.6/site-packages -D PYTHON_EXECUTABLE=/.virtualenvs/cv/bin/python -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules -D INSTALL_PYTHON_EXAMPLES=OFF -D INSTALL_C_EXAMPLES=OFF -D BUILD_EXAMPLES=OFF ..

However come test time I am getting this error:
Error: OpenCV(4.5.3-dev) /home/andrew/opencv_contrib/modules/cudaimgproc/src/cuda/bilateral_filter.cu:140: error: (-217:Gpu API call) invalid configuration argument in function 'bilateral_caller'

0.292014

Does anyone know what's happening? Thanks

@raulqf
Copy link
Author

raulqf commented Jul 24, 2021

Hi, I am compiling on a Nvidia Xavier AGX which has CC 7.2 so I build with the following flags:
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D WITH_CUBLAS=1 -D WITH_CUDA=ON -D BUILD_opencv_cudacodec=OFF -D WITH_CUDNN=ON -D OPENCV_DNN_CUDA=ON -D CUDA_ARCH_BIN=7.2 -D WITH_V4L=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_GSTREAMER=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_PC_FILE_NAME=opencv.pc -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_PYTHON3_INSTALL_PATH=/.virtualenvs/cv/lib/python3.6/site-packages -D PYTHON_EXECUTABLE=/.virtualenvs/cv/bin/python -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules -D INSTALL_PYTHON_EXAMPLES=OFF -D INSTALL_C_EXAMPLES=OFF -D BUILD_EXAMPLES=OFF ..

However come test time I am getting this error:
Error: OpenCV(4.5.3-dev) /home/andrew/opencv_contrib/modules/cudaimgproc/src/cuda/bilateral_filter.cu:140: error: (-217:Gpu API call) invalid configuration argument in function 'bilateral_caller'

0.292014

Does anyone know what's happening? Thanks

I think it's because opencv suppor to this platform. Check this other link in which a guy has a similiar problem, but using the resize function. Maybe, you could try proposed solution to check your compilation:

https://forums.developer.nvidia.com/t/opencv-gpu-invalid-configuration-argument-in-function-call/64604/2

@smn06
Copy link

smn06 commented Aug 9, 2021

When i try to run the test script i get the error: "fatal error: opencv2/cudaarithm.hpp: No such file or directory #include <opencv2/cudaarithm.hpp>"
It obviously don't know the library
Or do i have to put the test.cpp file in a special path?
But i found it at /home/opencv_contrib-4.2.0/modules/cudaarithm
How can i manage this problem? @raulqf

I'm having the same problem

have you solved it?

@raulqf
Copy link
Author

raulqf commented Aug 10, 2021

When i try to run the test script i get the error: "fatal error: opencv2/cudaarithm.hpp: No such file or directory #include <opencv2/cudaarithm.hpp>"
It obviously don't know the library
Or do i have to put the test.cpp file in a special path?
But i found it at /home/opencv_contrib-4.2.0/modules/cudaarithm
How can i manage this problem? @raulqf

I'm having the same problem

have you solved it?

You have problems while compiling test.cpp because the compiler is not finding the respective header files. Which is the output that you get from pkg-config? (Type pkg-config opencv --cflags --libs)

@kuazhangxiaoai
Copy link

kuazhangxiaoai commented Aug 19, 2021

-DCUDA_nppicom_LIBRARY=真\

将 -DCUDA_nppicom_LIBRARY=true\ 替换为 -DCUDA_nppicom_LIBRARY=ON\

@lingcong-k

请问,修改哪哥文件呢?我找不到CUDA_nppicom_LIBRARY这个设置的地方

@Anastasija-T
Copy link

Anastasija-T commented Sep 10, 2021

Hello everyone!
Thank you for this gist. I followed this guide. I didn't forget to run the "sudo make install"command. But the cv2 directory was not created. Perhaps someone will be helped by a solution that eventually worked for me. So, the initial data:

CUDA 11.4
cuDNN 8.2.2 
Ubuntu 20.04
OpenCV 4.5.3-dev

After I failed with this guide, I executed the following commands:

git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
cd ~/opencv_build/opencv
mkdir -p build && cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_GENERATE_PKGCONFIG=ON \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
    -D ENABLE_FAST_MATH=1 \
    -D CUDA_FAST_MATH=1 \
    -D WITH_CUBLAS=1 \
    -D WITH_CUDA=ON \
    -D BUILD_opencv_cudacodec=OFF \
    -D WITH_CUDNN=ON \
    -D OPENCV_DNN_CUDA=ON \
    -D CUDA_ARCH_BIN=7.0 \
    -D BUILD_EXAMPLES=ON ..
make -j8
sudo make install
make -j8
sudo make install

After that, the cv2 directory was finally created! The path to it is as follows:
/usr/local/lib/python3.8/dist-packages/cv2
Good luck to you!

@raulqf
Copy link
Author

raulqf commented Sep 11, 2021

Hello everyone!
Thank you for this gist. I followed this guide. I didn't forget to run the "sudo make install"command. But the cv2 directory was not created. Perhaps someone will be helped by a solution that eventually worked for me. So, the initial data:

CUDA 11.4
cuDNN 8.2.2 
Ubuntu 20.04
OpenCV 4.5.3-dev

After I failed with this guide, I executed the following commands:

git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
cd ~/opencv_build/opencv
mkdir -p build && cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_GENERATE_PKGCONFIG=ON \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
    -D ENABLE_FAST_MATH=1 \
    -D CUDA_FAST_MATH=1 \
    -D WITH_CUBLAS=1 \
    -D WITH_CUDA=ON \
    -D BUILD_opencv_cudacodec=OFF \
    -D WITH_CUDNN=ON \
    -D OPENCV_DNN_CUDA=ON \
    -D CUDA_ARCH_BIN=7.0 \
    -D BUILD_EXAMPLES=ON ..
make -j8
sudo make install
make -j8
sudo make install

After that, the cv2 directory was finally created! The path to it is as follows:
/usr/local/lib/python3.8/dist-packages/cv2
Good luck to you!

Hi Anastasija-T,

Have you checked the path defined during the configuration? In the proposed example, it is defined as virtual environment just created to contain cv2: OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages . If you do not define this directive, then it should be installed in your dist-package of yout system.

Regards,
Raul

@Anastasija-T
Copy link

Anastasija-T commented Sep 11, 2021

Hello everyone!
Thank you for this gist. I followed this guide. I didn't forget to run the "sudo make install"command. But the cv2 directory was not created. Perhaps someone will be helped by a solution that eventually worked for me. So, the initial data:

CUDA 11.4
cuDNN 8.2.2 
Ubuntu 20.04
OpenCV 4.5.3-dev

After I failed with this guide, I executed the following commands:

git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
cd ~/opencv_build/opencv
mkdir -p build && cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_GENERATE_PKGCONFIG=ON \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
    -D ENABLE_FAST_MATH=1 \
    -D CUDA_FAST_MATH=1 \
    -D WITH_CUBLAS=1 \
    -D WITH_CUDA=ON \
    -D BUILD_opencv_cudacodec=OFF \
    -D WITH_CUDNN=ON \
    -D OPENCV_DNN_CUDA=ON \
    -D CUDA_ARCH_BIN=7.0 \
    -D BUILD_EXAMPLES=ON ..
make -j8
sudo make install
make -j8
sudo make install

After that, the cv2 directory was finally created! The path to it is as follows:
/usr/local/lib/python3.8/dist-packages/cv2
Good luck to you!

Hi Anastasija-T,

Have you checked the path defined during the configuration? In the proposed example, it is defined as virtual environment just created to contain cv2: OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages . If you do not define this directive, then it should be installed in your dist-package of yout system.

Regards,
Raul

Hello, Raul!

This is indeed the case. For me, a system installation is more convenient. As I said above, the cv2 directory in my case has the following path:
/usr/local/lib/python3.8/dist-packages/cv2
With OpenCV 4.5.2, I was unable to make an installation in the dist-packages of the system, the cv2 directory was also not created. Perhaps the problem is in the OpenCV version. I hope this idea will be useful to someone.

With best wishes, Anastasia

@raulqf
Copy link
Author

raulqf commented Sep 12, 2021

Hello everyone!
Thank you for this gist. I followed this guide. I didn't forget to run the "sudo make install"command. But the cv2 directory was not created. Perhaps someone will be helped by a solution that eventually worked for me. So, the initial data:

CUDA 11.4
cuDNN 8.2.2 
Ubuntu 20.04
OpenCV 4.5.3-dev

After I failed with this guide, I executed the following commands:

git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
cd ~/opencv_build/opencv
mkdir -p build && cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_GENERATE_PKGCONFIG=ON \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
    -D ENABLE_FAST_MATH=1 \
    -D CUDA_FAST_MATH=1 \
    -D WITH_CUBLAS=1 \
    -D WITH_CUDA=ON \
    -D BUILD_opencv_cudacodec=OFF \
    -D WITH_CUDNN=ON \
    -D OPENCV_DNN_CUDA=ON \
    -D CUDA_ARCH_BIN=7.0 \
    -D BUILD_EXAMPLES=ON ..
make -j8
sudo make install
make -j8
sudo make install

After that, the cv2 directory was finally created! The path to it is as follows:
/usr/local/lib/python3.8/dist-packages/cv2
Good luck to you!

Hi Anastasija-T,
Have you checked the path defined during the configuration? In the proposed example, it is defined as virtual environment just created to contain cv2: OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages . If you do not define this directive, then it should be installed in your dist-package of yout system.
Regards,
Raul

Hello, Raul!

This is indeed the case. For me, a system installation is more convenient. As I said above, the cv2 directory in my case has the following path:
/usr/local/lib/python3.8/dist-packages/cv2
With OpenCV 4.5.2, I was unable to make an installation in the dist-packages of the system, the cv2 directory was also not created. Perhaps the problem is in the OpenCV version. I hope this idea will be useful to someone.

With best wishes, Anastasia

OpenCV versions should not be the problem. Just a reminder, cv2 could be located in dist-packages or site-packages depending how you install it. So, in case of a virtual environment it is located in site-packages, I think.

Regards,
Raul

@smn06
Copy link

smn06 commented Sep 15, 2021

Why can't i delete opencv-4.5.2 and opencv-contrib-4.5.2 folders from Download after installation? It seems, If i delete one of this, my program doesn't work. But the installation is done properly.

@raulqf
Copy link
Author

raulqf commented Sep 16, 2021

Why can't i delete opencv-4.5.2 and opencv-contrib-4.5.2 folders from Download after installation? It seems, If i delete one of this, my program doesn't work. But the installation is done properly.

No, you can delete both. Once you do "sudo make install", respective libraries (*.so or *.a) have been installed in your system, as well as the header files. Try to move the folders to other directory for a fast check.

@smn06
Copy link

smn06 commented Sep 16, 2021

Why can't i delete opencv-4.5.2 and opencv-contrib-4.5.2 folders from Download after installation? It seems, If i delete one of this, my program doesn't work. But the installation is done properly.

No, you can delete both. Once you do "sudo make install", respective libraries (*.so or *.a) have been installed in your system, as well as the header files. Try to move the folders to other directory for a fast check.

Thanks for the reply,
I moved the folders from my Download folder and after that opencv program stopped working.And the programs started working later If i put back those into the Download folder again. Though the header and libraries are stored in /usr/local/include/ and /usr/lib/python3/dist-packages/ path.

@puppinoo
Copy link

puppinoo commented Nov 13, 2021

Hi,
Can anyone help, I've been struggling for 2 days now. I followed the tutorial. Just modified the cmake command in the one below otherwise compilation failed. I'm 100% sure it worked jsut after installation cause I could compile and execute test.cpp and many other examples. I just turned off or rebooted and now I nothing works anymore. IMPORTANT. My driver version is Driver Version: 495.44, my Ubuntu is 20.04 and my CUDA version is 11.4 (maybe there's some sort of incompatibility?) On the test example I receive this error:

`~/src/machine_learning/testcuda$ ./test
Error: OpenCV(4.5.2) /home/pinuccio/src/machine_learning/opencv/opencv_contrib-4.5.2/modules/cudaimgproc/src/cuda/bilateral_filter.cu:140: error: (-217:Gpu API call) invalid configuration argument in function 'bilateral_caller'

0.07816
I tried many things. For example I added these in .bashrc# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

export PATH=/usr/lib/x86_64-linux-gnu:$PATH
export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
export CPATH=/usr/local/cuda-11.4/targets/x86_64-linux/include${CPATH:+:${CPATH}}
`
but I'm losing a bit confidence and lucidity so probably making things worse.
Any help is appreciated.

This is my CMAKE:

cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D WITH_TBB=ON \ -D ENABLE_FAST_MATH=1 \ -D CUDA_FAST_MATH=1 \ -D WITH_CUBLAS=1 \ -D WITH_CUDA=ON \ -D BUILD_opencv_cudacodec=OFF \ -D WITH_CUDNN=ON \ -D OPENCV_DNN_CUDA=ON \ -D CUDA_ARCH_BIN=7.5 \ -D WITH_V4L=ON \ -D WITH_QT=OFF \ -D WITH_OPENGL=ON \ -D WITH_GSTREAMER=ON \ -D OPENCV_GENERATE_PKGCONFIG=ON \ -D OPENCV_PC_FILE_NAME=opencv.pc \ -D OPENCV_ENABLE_NONFREE=ON \ -D OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages \ -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \ -D OPENCV_EXTRA_MODULES_PATH=~/src/machine_learning/opencv/opencv_contrib-4.5.2/modules \ -D INSTALL_PYTHON_EXAMPLES=OFF \ -D INSTALL_C_EXAMPLES=OFF \ -D CUDNN_INCLUDE_DIR="/usr/lib/cuda/include/" \ -D CUDNN_LIBRARY="~/src/machine_learning/opencv/cudnn/cuda/lib64/libcudnn.so.8.2.4" \ -D BUILD_EXAMPLES=OFF ..

@raulqf
Copy link
Author

raulqf commented Nov 18, 2021

Hi, Can anyone help, I've been struggling for 2 days now. I followed the tutorial. Just modified the cmake command in the one below otherwise compilation failed. I'm 100% sure it worked jsut after installation cause I could compile and execute test.cpp and many other examples. I just turned off or rebooted and now I nothing works anymore. IMPORTANT. My driver version is Driver Version: 495.44, my Ubuntu is 20.04 and my CUDA version is 11.4 (maybe there's some sort of incompatibility?) On the test example I receive this error:

`~/src/machine_learning/testcuda$ ./test Error: OpenCV(4.5.2) /home/pinuccio/src/machine_learning/opencv/opencv_contrib-4.5.2/modules/cudaimgproc/src/cuda/bilateral_filter.cu:140: error: (-217:Gpu API call) invalid configuration argument in function 'bilateral_caller'

0.07816 I tried many things. For example I added these in .bashrc# virtualenv and virtualenvwrapper export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 source /usr/local/bin/virtualenvwrapper.sh

export PATH=/usr/lib/x86_64-linux-gnu:$PATH export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH export CPATH=/usr/local/cuda-11.4/targets/x86_64-linux/include${CPATH:+:${CPATH}} ` but I'm losing a bit confidence and lucidity so probably making things worse. Any help is appreciated.

This is my CMAKE:

cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D WITH_TBB=ON \ -D ENABLE_FAST_MATH=1 \ -D CUDA_FAST_MATH=1 \ -D WITH_CUBLAS=1 \ -D WITH_CUDA=ON \ -D BUILD_opencv_cudacodec=OFF \ -D WITH_CUDNN=ON \ -D OPENCV_DNN_CUDA=ON \ -D CUDA_ARCH_BIN=7.5 \ -D WITH_V4L=ON \ -D WITH_QT=OFF \ -D WITH_OPENGL=ON \ -D WITH_GSTREAMER=ON \ -D OPENCV_GENERATE_PKGCONFIG=ON \ -D OPENCV_PC_FILE_NAME=opencv.pc \ -D OPENCV_ENABLE_NONFREE=ON \ -D OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages \ -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \ -D OPENCV_EXTRA_MODULES_PATH=~/src/machine_learning/opencv/opencv_contrib-4.5.2/modules \ -D INSTALL_PYTHON_EXAMPLES=OFF \ -D INSTALL_C_EXAMPLES=OFF \ -D CUDNN_INCLUDE_DIR="/usr/lib/cuda/include/" \ -D CUDNN_LIBRARY="~/src/machine_learning/opencv/cudnn/cuda/lib64/libcudnn.so.8.2.4" \ -D BUILD_EXAMPLES=OFF ..

Hi Puppinoo,

I would delete the environment variable that you have defined. The problem seems to be related with the opencv library. Could you try another example with opencv for CUDA?

Best Regards,
Raul

@puppinoo
Copy link

puppinoo commented Nov 18, 2021

Hi, Can anyone help, I've been struggling for 2 days now. I followed the tutorial. Just modified the cmake command in the one below otherwise compilation failed. I'm 100% sure it worked jsut after installation cause I could compile and execute test.cpp and many other examples. I just turned off or rebooted and now I nothing works anymore. IMPORTANT. My driver version is Driver Version: 495.44, my Ubuntu is 20.04 and my CUDA version is 11.4 (maybe there's some sort of incompatibility?) On the test example I receive this error:
~/src/machine_learning/testcuda$ ./test Error: OpenCV(4.5.2) /home/pinuccio/src/machine_learning/opencv/opencv_contrib-4.5.2/modules/cudaimgproc/src/cuda/bilateral_filter.cu:140: error: (-217:Gpu API call) invalid configuration argument in function 'bilateral_caller' 0.07816 I tried many things. For example I added these in .bashrc# virtualenv and virtualenvwrapper export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 source /usr/local/bin/virtualenvwrapper.sh export PATH=/usr/lib/x86_64-linux-gnu:$PATH export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH export CPATH=/usr/local/cuda-11.4/targets/x86_64-linux/include${CPATH:+:${CPATH}} but I'm losing a bit confidence and lucidity so probably making things worse. Any help is appreciated.
This is my CMAKE:
cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D WITH_TBB=ON \ -D ENABLE_FAST_MATH=1 \ -D CUDA_FAST_MATH=1 \ -D WITH_CUBLAS=1 \ -D WITH_CUDA=ON \ -D BUILD_opencv_cudacodec=OFF \ -D WITH_CUDNN=ON \ -D OPENCV_DNN_CUDA=ON \ -D CUDA_ARCH_BIN=7.5 \ -D WITH_V4L=ON \ -D WITH_QT=OFF \ -D WITH_OPENGL=ON \ -D WITH_GSTREAMER=ON \ -D OPENCV_GENERATE_PKGCONFIG=ON \ -D OPENCV_PC_FILE_NAME=opencv.pc \ -D OPENCV_ENABLE_NONFREE=ON \ -D OPENCV_PYTHON3_INSTALL_PATH=~/.virtualenvs/cv/lib/python3.8/site-packages \ -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \ -D OPENCV_EXTRA_MODULES_PATH=~/src/machine_learning/opencv/opencv_contrib-4.5.2/modules \ -D INSTALL_PYTHON_EXAMPLES=OFF \ -D INSTALL_C_EXAMPLES=OFF \ -D CUDNN_INCLUDE_DIR="/usr/lib/cuda/include/" \ -D CUDNN_LIBRARY="~/src/machine_learning/opencv/cudnn/cuda/lib64/libcudnn.so.8.2.4" \ -D BUILD_EXAMPLES=OFF ..

Hi Puppinoo,

I would delete the environment variable that you have defined. The problem seems to be related with the opencv library. Could you try another example with opencv for CUDA?

Best Regards, Raul

Hi,
It seems I fixed after so many attempts.
I'm not sure what fixed but I write here what I probably did different when it started working:

  1. added python2 executable path into cmake string (not sure it did any different but I dit do that)
    -D PYTHON2_EXECUTABLE=/usr/bin/python2.7 \
  2. I noticed that I had 2 different ldconfig binaries in path. The default was /usr/sbin/ldconfig but as soon as I used the other one which is "sudo /sbin/ldconfig" the app started workign correctly.
    Not sure this is the cause of the issue but maybe it can help.
  3. I used correctly the virtualenv environment launching workon opencv_cuda (my created virtualenv) before installing.
    Basically I did
    a) workon openv_cuda
    b) pip install numpy
    c) followed the rest of the tutorial
    but this is well explained in the tutorial as well. It was my fault if I did something wrong.

P.s.: Also, installing darknet repo I noticed my cudnnn installation was not correct cause I had multible libraries installed and the wrong ones pointed to alternatives so I used the dpkg to install the right one for cura 11.4 which is 8.2.4 (if im not wrong) and after that darknet compiled successfully. BTW this issues happened after I fixed the issue with cpp import.

Thanks and regards.

@keaneflynn
Copy link

keaneflynn commented Jan 1, 2022

Hi all,
Just finished my build for OpenCV and thought I would leave a github link to the repository with a bash file and that worked for me with a python script to test if the build worked. Like a few other people in this thread I encountered an issue with the version of gcc/++ used to compile OpenCV and ultimately had to downgrade from gcc/g++ to gcc/++ 10 for the build to process successfully. From what I found on Nvidia's forums it sounds like gcc/++ 11 is not compatible with CUDA 11.4.x but will work with CUDA 11.5.x (I have yet to test this) but gcc/++ 10 will work with CUDA 11.4.x.
This build is not for a virtual environment but can easily be configured to do so. I was able to crank out between 100-150 fps inference using yolov4-tiny object detection and seems to handle most of everything I need to throw at it. Cheers.

Hardware/software specs:
Laptop: Razer Blade 14
CPU: AMD 5900hx
GPU: Nvidia 3080 8gb vram
NVIDIA DRIVERS: 470.86
CUDA: 11.4
CUDNN: 8.4.2
UBUNTU: 21.10
KERNEL: 5.13
OPENCV: 4.5.3

@raulqf
Copy link
Author

raulqf commented Jan 10, 2022

Hi keaneflynn,

Nice bash script. May I include a reference to your repo in the example section with a brief introduction?

CUDA points to the default versions of gcc/g++ regarding the OS in their installation guides, but you are working with latest versions even for Ubuntu distribution. Anyway, you find a compatible version 👌 .

@keaneflynn
Copy link

keaneflynn commented Jan 12, 2022

@raulqf Go ahead! Happy to help anyone through this process if they have a similar system to me and this is compatible

@e101sg
Copy link

e101sg commented Jan 12, 2022

Dear All, I am trying to install Darknet / YOLOv4 on Jetson Xavier. Using Jetpack 4.5.1 /Anaconda base environment
I have installed CUDA
My installation looks like this (Jetson utilities screen shot ) - the CUDNN: NOT_INSTALLED
Default GCC installed version is 7.5.0/ I have installed in GCC 10.1. Can see usr/bin/gcc-10. It has short to aarch64-linux-gnu-gcc-10.
https://1drv.ms/u/s!AgQa8i37A0sihYZsAZ1EnOBAJdeyoA?e=YmRNpK
Then when i run the above script, i get the following errors (screen shot)

https://1drv.ms/u/s!AgQa8i37A0sihYZtPxmyTHy3XxuGsQ
https://1drv.ms/u/s!AgQa8i37A0sihYZuOibIYRgxWTY7Gg

Last 2 days, i am trying...any thoughts highly useful. Thanks.

Cheers!
Chandra

@pinduzera
Copy link

pinduzera commented Jan 12, 2022

@e101sg
Looks like your Cudnn is not installed or is installed in the wrong path. Try looking for cudnn solutions specifically. Maybe it is just a matter of a symbolic link or may require a installation.
https://docs.nvidia.com/jetson/jetpack/install-jetpack/index.html

@e101sg
Copy link

e101sg commented Jan 12, 2022

Hi Pinduzera,
Thanks a lot. hmm...i too think some issue with cuDNN. I have seen the link you mentioned above. After cuDNN, i have to OpenCV /Darknet/ Yolo as well. (this needs GCC 10). I wondering how to upgrade the Jetpack from 4.5 to 4.6 (seems it is not very straight forward)

@keaneflynn
Copy link

keaneflynn commented Jan 13, 2022

@e101sg
The default jetpack installation of Jetpack should have everything in the correct place as far as CUDA & CUDNN are concerned. You should be able to build OpenCV with CUDA dependencies rather easily and then migrate onto the Darknet build from there (if you are building Darknet from source you should have opencv built with CUDA first).

I haven't personally tried to build darknet on a Jetson Xavier, but I have built OpenCV with CUDA & CUDNN and have a script that will work with an Xavier out of the box with the current Jetpack version. Hope this helps.

@e101sg
Copy link

e101sg commented Jan 13, 2022

After some efforts, I have installed CUDNN 8.0 installed. I have trying to build the OpenCV 4.5.3 but getting error
CMake Error at modules/dnn/CMakeLists.txt:39 (message):
DNN: CUDA backend requires cuDNN. Please resolve dependency or disable
OPENCV_DNN_CUDA=OFF

NVIDIA Jetson AGX Xavier [16GB]
L4T 32.5.2 [ JetPack UNKNOWN ]
Ubuntu 18.04.5 LTS
Kernel Version: 4.9.201-tegra
CUDA 10.2.89
CUDA Architecture: 7.2
OpenCV version: 3.2.0
OpenCV Cuda: NO
CUDNN: 8.0.0.180
TensorRT: 7.1.3.0
Vision Works: 1.6.0.501
VPI: ii libnvvpi1 1.0.15 arm64 NVIDIA Vision Programming Interface library
Vulcan: 1.2.70
+++++++++++++++++++
cmake -D CMAKE_BUILD_TYPE=RELEASE
-D CMAKE_INSTALL_PREFIX=/usr
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules
-D EIGEN_INCLUDE_PATH=/usr/include/eigen3
-D WITH_OPENCL=OFF
-D WITH_CUDA=ON
-D CUDA_ARCH_BIN=8.0
-D CUDA_ARCH_PTX=""
-D WITH_CUDNN=ON
-D OPENCV_DNN_CUDA=ON
-D WITH_CUBLAS=ON
-D ENABLE_FAST_MATH=ON
-D CUDA_FAST_MATH=ON
-D OPENCV_DNN_CUDA=ON
-D ENABLE_NEON=ON
-D WITH_QT=OFF
-D WITH_OPENMP=ON
-D BUILD_TIFF=ON
-D WITH_FFMPEG=ON
-D WITH_GSTREAMER=ON
-D WITH_TBB=ON
-D BUILD_TBB=ON
-D BUILD_TESTS=OFF
-D WITH_EIGEN=ON
-D WITH_V4L=ON
-D WITH_LIBV4L=ON
-D OPENCV_ENABLE_NONFREE=ON
-D INSTALL_C_EXAMPLES=OFF
-D INSTALL_PYTHON_EXAMPLES=OFF
-D BUILD_opencv_python3=TRUE
-D OPENCV_GENERATE_PKGCONFIG=ON
-D CUDNN_VERSION='8.0'
-D BUILD_opencv_python3=ON
-D CMAKE_BUILD_TYPE=RELEASE
-D BUILD_EXAMPLES=OFF ..

Not sure what am i missing :)

@pinduzera
Copy link

pinduzera commented Jan 13, 2022

@e101sg Xavier's compute capability is 7.2 not 8.0. (https://developer.nvidia.com/cuda-gpus) (Cuda compute =/= CUDNN)
This may be source of the conflict for cudnn.
Try CUDA_ARCH_BIN=7.2

@e101sg
Copy link

e101sg commented Jan 20, 2022

@pinduzera:yes. corrected mistake. I have updated the Jetson Xavier AGX memory with 512GB SSD. ( following Jetsonhacks YT channel) and installed JetPack 4.6 on new L4T /Ubuntu 18.04 image. Will try again. Will CUDA 10.2 instead of latest 11.X. Any thoughts! Cheers !! - Chandra

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment