반응형

WSL2에 CUDA 사용하도록 OpenCV 설치하는 방법을 다룹니다.

 

2022. 11. 26  최초작성



1. WSL2를 설치하는 방법은 다음 링크를 참고하세요.

 

WSL2를 설치하여 Ubuntu 22.04 사용하는 방법

https://webnautes.tistory.com/1847



2. WSL2에 CUDA를 설치하는 방법은 다음 링크를 참고하세요.

 

WSL2에 CUDA 설치하는 방법

https://webnautes.tistory.com/1848



3. 다음 명령을 차례로 실행하여 WSL2에서 pip3 명령을 사용할 수 있도록 해줘야 합니다. 

참고 https://learn.microsoft.com/ko-kr/windows/python/web-frameworks 

 

sudo apt-get update && sudo apt-get upgrade

sudo apt-get install python3-pip



4.추가로 필요한 패키지들을 설치합니다. 

 

$ sudo apt-get install build-essential cmake

$ sudo apt-get install pkg-config

$ sudo apt-get install libjpeg-dev libtiff5-dev libpng-dev

$ sudo apt-get install ffmpeg libavcodec-dev libavformat-dev libswscale-dev libxvidcore-dev libx264-dev libxine2-dev

$ sudo apt-get install libv4l-dev v4l-utils

$ sudo apt-get install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev 

$ sudo apt-get install libgtk-3-dev

$ sudo apt-get install libatlas-base-dev gfortran libeigen3-dev

$ sudo apt-get install python3-dev python3-numpy

$ sudo apt install unzip



5. OpenCV를 다운로드 받습니다.

 

홈 디렉토리로 우선 이동합니다. 윈도우에서 사용하는 /mnt/c 아래 경로에서 진행하면 느립니다.

$ cd ~

 

$ mkdir opencv-sources

$ cd opencv-sources

$ wget -O opencv.zip https://github.com/opencv/opencv/archive/4.6.0.zip

$ unzip opencv.zip

$ wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.6.0.zip

$ unzip opencv_contrib.zip

$ cd opencv-4.6.0

$ mkdir build

$ cd build



6. Python이 라이브러리를 인식하는 위치를 확인합니다. 여기에선  dist-packages가 포함된 경로입니다. 

 

$ python3 -m site

sys.path = [

    '/mnt/c/Users/webnautes',

    '/usr/lib/python310.zip',

    '/usr/lib/python3.10',

    '/usr/lib/python3.10/lib-dynload',

    '/home/webnautes/.local/lib/python3.10/site-packages',

    '/usr/local/lib/python3.10/dist-packages',

    '/usr/lib/python3/dist-packages',

]

USER_BASE: '/home/webnautes/.local' (exists)

USER_SITE: '/home/webnautes/.local/lib/python3.10/site-packages' (exists)

ENABLE_USER_SITE: True



7. cmake를 실행합니다. 중간에 다운로드를 하므로 인터넷이 연결된 상태에서 진행해야 합니다.

 

주의할 점은 아래에서 파란색으로 표시한 CUDA_ARCH_BIN, CUDA_ARCH_PTX는 https://developer.nvidia.com/cuda-gpus 의 Compute Capability를 참고하여 본인의 GPU에 따라 바꿔야 합니다.  

목록에 없다면 구글에서 “gtx 1660 ti Compute Capability” 식으로 검색하여 찾으세요. 이 값을 잘못 입력하면 CUDA가 정상 동작하지 않습니다. 

gtx 1660 ti 의 경우에는 7.5입니다. 

 

CUDNN_LIBRARY 부분은 앞에서 설치한 cuDNN의 버전으로 변경해야 합니다. 현재는 cuDNN 8.6.0을 사용합니다.

 

OPENCV_EXTRA_MODULES_PATH 부분은 다운로드한 OpenCV 버전이 변경된 경우 수정해야 합니다.  현재는 OpenCV 4.6.0을 사용합니다. 

 

PYTHON3_PACKAGES_PATH 부분은 Python의 라이브러리 찾는 경로로 7번에서 확인한 경로로 변경해야 합니다. 

 

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=ON -D BUILD_DOCS=OFF -D BUILD_PERF_TESTS=OFF -D BUILD_TESTS=OFF -D BUILD_PACKAGE=OFF -D BUILD_EXAMPLES=OFF -D WITH_TBB=ON -D ENABLE_FAST_MATH=1 -D CUDA_FAST_MATH=1 -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda -D WITH_CUDA=ON -D WITH_CUBLAS=ON -D WITH_CUFFT=ON -D WITH_NVCUVID=ON -D WITH_IPP=OFF -D WITH_V4L=ON -D WITH_1394=OFF -D WITH_GTK=ON -D WITH_QT=OFF -D WITH_OPENGL=ON -D WITH_EIGEN=ON -D WITH_FFMPEG=ON -D WITH_GSTREAMER=ON -D BUILD_JAVA=OFF -D BUILD_opencv_python3=ON -D BUILD_opencv_python2=OFF -D BUILD_NEW_PYTHON_SUPPORT=ON -D OPENCV_SKIP_PYTHON_LOADER=ON -D OPENCV_GENERATE_PKGCONFIG=ON -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib-4.6.0/modules -D WITH_CUDNN=ON -D OPENCV_DNN_CUDA=ON -D CUDA_ARCH_BIN=7.5  -D CUDA_ARCH_PTX=7.5 -D CUDNN_LIBRARY=/usr/local/cuda/lib64/libcudnn.so.8.6.0 -D CUDNN_INCLUDE_DIR=/usr/local/cuda/include  -D PYTHON3_PACKAGES_PATH=/usr/local/lib/python3.10/dist-packages  .. 



다음은 cmake 실행 결과에서 빨간색 부분처럼 CUDA가 활성화 되었는지 확인하세요. 

-- General configuration for OpenCV 4.6.0 =====================================
--   Version control:               unknown
--
--   Extra modules:
--     Location (extra):            /home/webnautes/opencv-sources/opencv_contrib-4.6.0/modules
--     Version control (extra):     unknown
--
--   Platform:
--     Timestamp:                   2022-11-26T11:10:04Z
--     Host:                        Linux 5.15.74.2-microsoft-standard-WSL2 x86_64
--     CMake:                       3.22.1
--     CMake generator:             Unix Makefiles
--     CMake build tool:            /usr/bin/gmake
--     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 (16 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 (31 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
--       AVX512_SKX (5 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 11.3.0)
--     C++ flags (Release):         -fsigned-char -ffast-math -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-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 -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-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 -Wreturn-type -Waddress -Wsequence-point -Wformat -Wformat-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 -Wreturn-type -Waddress -Wsequence-point -Wformat -Wformat-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,--gc-sections -Wl,--as-needed -Wl,--no-undefined
--     Linker flags (Debug):        -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined
--     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 barcode bgsegm bioinspired calib3d ccalib core cudaarithm cudabgsegm cudacodec 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 python3 quality rapid reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking video videoio videostab wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
--     Disabled:                    world
--     Disabled by dependency:      -
--     Unavailable:                 cvv hdf java julia matlab ovis python2 sfm ts viz
--     Applications:                apps
--     Documentation:               NO
--     Non-free algorithms:         YES
--
--   GUI:                           GTK3
--     GTK+:                        YES (ver 3.24.33)
--       GThread :                  YES (ver 2.72.1)
--       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.3.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:
--     FFMPEG:                      YES
--       avcodec:                   YES (58.134.100)
--       avformat:                  YES (58.76.100)
--       avutil:                    YES (56.70.100)
--       swscale:                   YES (5.9.100)
--       avresample:                NO
--     GStreamer:                   YES (1.20.3)
--     v4l/v4l2:                    YES (linux/videodev2.h)
--
--   Parallel framework:            pthreads
--
--   Trace:                         YES (with Intel ITT)
--
--   Other third-party libraries:
--     VA:                          NO
--     Lapack:                      NO
--     Eigen:                       YES (ver 3.4.0)
--     Custom HAL:                  NO
--     Protobuf:                    build (3.19.1)
--
--   NVIDIA CUDA:                   YES (ver 11.8, CUFFT CUBLAS FAST_MATH)
--     NVIDIA GPU arch:             75
--     NVIDIA PTX archs:            75
--
--   cuDNN:                         YES (ver 8.6.0)
--
--   OpenCL:                        YES (no extra features)
--     Include path:                /home/webnautes/opencv-sources/opencv-4.6.0/3rdparty/include/opencl/1.2
--     Link libraries:              Dynamic load
--
--   Python 3:
--     Interpreter:                 /usr/bin/python3 (ver 3.10.6)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.10.so (ver 3.10.6)
--     numpy:                       /home/webnautes/.local/lib/python3.10/site-packages/numpy/core/include (ver 1.23.5)
--     install path:                /usr/local/lib/python3.10/dist-packages
--
--   Python (for build):            /usr/bin/python3
--
--   Install to:                    /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /home/webnautes/opencv-sources/opencv-4.6.0/build




8. 빌드 및 설치를 합니다. 

 

$ time make -j$(nproc)

$ sudo make install




9. 라이브러리를 인식할 수 있도록 해줍니다. 

$ sudo ldconfig

 

아래  문제가 발생했습니다. 

~/opencv-sources/opencv-4.6.0/build$ sudo ldconfig

/sbin/ldconfig.real: /usr/lib/wsl/lib/libcuda.so.1 is not a symbolic link

 

찾아보고 다음처럼 해결했습니다.

https://github.com/microsoft/WSL/issues/5663 

 

관리자 권한으로 명령 프롬프트 실행한 후, 다음 명령들을 차례로 실행합니다. 

C:\Windows\system32>cd lxss\lib

C:\Windows\System32\lxss\lib>del libcuda.so

C:\Windows\System32\lxss\lib>del libcuda.so.1

C:\Windows\System32\lxss\lib>mklink libcuda.so libcuda.so.1.1

libcuda.so <<===>> libcuda.so.1.1에 대한 기호화된 링크를 만들었습니다.

C:\Windows\System32\lxss\lib>mklink libcuda.so.1 libcuda.so.1.1

libcuda.so.1 <<===>> libcuda.so.1.1에 대한 기호화된 링크를 만들었습니다.

 

wsl 터미널에서 다시 해보니 해결이 되었습니다. 

sudo ldconfig

 

에러가 계속 나는 경우 컴퓨터를 재부팅후 해보세요.




10. 다음 코드를 컴파일하여 CUDA를 OpenCV에서 사용할 수 있는지 테스트합니다. 

 

$ g++ -o test test.cpp $(pkg-config opencv4 --libs --cflags)

 

#include <iostream>
using namespace std;

#include <opencv2/core.hpp>
using namespace cv;

#include <opencv2/cudaarithm.hpp>
using namespace cv::cuda;

int main()
{
    printShortCudaDeviceInfo(getDevice());


    int cuda_devices_number = getCudaEnabledDeviceCount();
    cout << "CUDA Device(s) Number: "<< cuda_devices_number << endl;
    DeviceInfo _deviceInfo;


    bool _isd_evice_compatible = _deviceInfo.isCompatible();
    cout << "CUDA Device(s) Compatible: " << _isd_evice_compatible << endl;


    return 0;
}

 

실행 결과 두 항목 모두 1이 나와야 합니다. 

 

$ ./test

Device 0:  "NVIDIA GeForce GTX 1660 Ti"  6144Mb, sm_75, Driver/Runtime ver.11.40/11.80

CUDA Device(s) Number: 1

CUDA Device(s) Compatible: 1

 

둘다 1이 보이지 않으면 cmake의 다음 두 옵션에 숫자를 잘못 적은겁니다. 

그래픽 카드에 해당되는 숫자를 적어야 합니다. 

 

-D CUDA_ARCH_BIN=7.5 -D CUDA_ARCH_PTX=7.5 



11. 파이썬 모듈을 로드해봅니다.

 

$ python3

Python 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> import cv2

>>>


반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts