Compiler OpenCV 4.10 Ubuntu 20.04
Table of contents
Qu'est-ce que OpenCV ?
OpenCV (Open Source Computer Vision Library) est une bibliothèque open-source largement utilisée pour la vision par ordinateur et l'intelligence artificielle. Elle fournit des outils puissants pour traiter et analyser des images et des vidéos, en permettant des tâches telles que la détection de visages, la reconnaissance d'objets, et la segmentation d'images. OpenCV est populaire dans des domaines comme la robotique, la réalité augmentée et la véhicule autonome, grâce à sa rapidité, sa flexibilité et son support multiplateforme.
Avant de commencer l'installation d'OpenCV, assurez-vous d'avoir Python (+numpy) déjà installé sur votre machine, et les dépendances.
1. Check les dépendances avant la compilation de la librairie
sudo apt update
sudo apt install build-essential cmake git pkg-config libgtk-3-dev \
libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \
libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \
gfortran openexr libatlas-base-dev python3-dev python3-numpy \
libtbb2 libtbb-dev libdc1394-22-dev libopenexr-dev \
libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev
python3.13 --version
sudo python3.13 -m pip install --upgrade pip
sudo python3.13 -m pip install numpy
python3.13 -c "import numpy; print(numpy.__version__)"
2. Télécharger les fichiers sources
Suivez les étapes ci-dessous afin de préparer l'installation d'OpenCV 4.10.0 avec les modules contrib.
# Créer le répertoire d'installation d'OpenCV
cd /home/user_data/Bureau
mkdir Proj_OpenCV
cd Proj_OpenCV
# Télécharger les fichiers sources de la librairie principale OpenCV + modules complémentaires non obligatoire
unzip 4.10.0.zip
wget https://github.com/opencv/opencv/archive/refs/tags/4.10.0.zip
mv 4.10.0 opencv_build
wget https://github.com/opencv/opencv_contrib/archive/refs/tags/4.10.0.zip
unzip 4.10.0_contrib.zip
mv 4.10.0 opencv_contrib
cd opencv_main/opencv-4.10.0
# Créer le dossier build pour la compilation
mkdir build
cd build
# Créer un fichier bash CMake pour donner les instructions compilation
touch CMake.sh
# Accorder les droits d'éxecution sur le fichier bash
chmod a+x CMake.sh
3. Préparation la compilation de la librairie
Afin que les dépendances et les modules nécessaires soient correctement liés. Voici les étapes à suivre :
Assurez vous que dans le script CMake.sh
, les chemins vers les dossiers opencv_main
(le dossier principal d'OpenCV) et opencv_contrib
(les modules supplémentaires d'OpenCV) soient correctement configurés. Modifiez les variables correspondantes dans le script pour pointer vers vos dossiers locaux :
cmake \
-D WITH_CUDA=OFF \
-D BUILD_TIFF=ON \
-D BUILD_opencv_java=OFF \
-D WITH_OPENGL=ON \
-D WITH_OPENCL=ON \
-D WITH_IPP=ON \
-D WITH_TBB=ON \
-D WITH_EIGEN=ON \
-D WITH_V4L=ON \
-D WITH_VTK=OFF \
-D BUILD_TESTS=OFF \
-D BUILD_PERF_TESTS=OFF \
-D CMAKE_BUILD_TYPE=RELEASE \
-D BUILD_opencv_python2=OFF \
-D CMAKE_INSTALL_PREFIX=/home/user_data/Bureau/Proj_OPENCV/install_build .. \
-D PYTHON3_INCLUDE_DIR=$(python3.13 -c "import sysconfig; print(sysconfig.get_path('include'))") \
-D PYTHON3_PACKAGES_PATH=$(python3.13 -c "import sysconfig; print(sysconfig.get_path('purelib'))") \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_ENABLE_NONFREE=ON \
-D OPENCV_GENERATE_PKGCONFIG=ON \
-D PYTHON3_EXECUTABLE=$(which python3.13) \
-D PYTHON_DEFAULT_EXECUTABLE=$(which python3.13) \
-D OPENCV_EXTRA_MODULES_PATH=/home/user_data/Bureau/Proj_OPENCV/opencv_contrib/modules \
-D BUILD_EXAMPLES=ON \
/home/user_data/Bureau/Proj_OPENCV/opencv_build
Une fois le script de compilation prêt, il faut l'executer comme suivant:
sh CMake.sh
Avant de passer à l'étape suivante de la compilation, il est important d'inspecter attentivement les messages affichés dans le terminal. Recherchez toute anomalie ou erreur potentielle. Si aucune erreur manifeste n'apparaît et que toutes les bibliothèques et dépendances spécifiées dans le script de compilation soient correctement trouvées, vous pourrez alors procéder à la compilation. Vous avez un exemple de configuration ci-dessous:
-- Ouput configuration OpenCV 4.10 --
--
-- General configuration for OpenCV 4.10.0 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /home/user_data/Bureau/Proj_OPENCV/opencv_contrib/modules
-- Version control (extra): unknown
--
-- Platform:
-- Timestamp: 2024-12-16T10:25:18Z
-- Host: Linux 5.15.0-126-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 (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 (8 files): + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
-- AVX2 (36 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 9.4.0)
-- C++ flags (Release): -fsigned-char -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 -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 -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 -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,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined
-- Linker flags (Debug): -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies: dl m pthread rt
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: aruco bgsegm bioinspired calib3d ccalib core 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 shape signal stereo stitching structured_light superres surface_matching text tracking video videoio videostab wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: world
-- Disabled by dependency: -
-- Unavailable: alphamat cannops cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv java julia matlab ovis python2 sfm ts viz
-- Applications: examples apps
-- Documentation: NO
-- Non-free algorithms: YES
--
-- GUI: GTK3
-- GTK+: YES (ver 3.24.20)
-- GThread : YES (ver 2.64.6)
-- GtkGlExt: NO
-- OpenGL 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.6.0)
-- JPEG 2000: build (ver 2.5.0)
-- OpenEXR: /usr/lib/x86_64-linux-gnu/libImath.so /usr/lib/x86_64-linux-gnu/libIlmImf.so /usr/lib/x86_64-linux-gnu/libIex.so /usr/lib/x86_64-linux-gnu/libHalf.so /usr/lib/x86_64-linux-gnu/libIlmThread.so (ver 2_3)
-- 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.3)
-- 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: 2021.11.0 [2021.11.0]
-- at: /home/user_data/Bureau/Proj_OPENCV/opencv_build/build/3rdparty/ippicv/ippicv_lnx/icv
-- Intel IPP IW: sources (2021.11.0)
-- at: /home/user_data/Bureau/Proj_OPENCV/opencv_build/build/3rdparty/ippicv/ippicv_lnx/iw
-- VA: NO
-- Lapack: NO
-- Eigen: NO
-- Custom HAL: NO
-- Protobuf: build (3.19.1)
-- Flatbuffers: builtin/3rdparty (23.5.9)
--
-- OpenCL: YES (no extra features)
-- Include path: /home/user_data/Bureau/Proj_OPENCV/opencv_build/3rdparty/include/opencl/1.2
-- Link libraries: Dynamic load
--
-- Python 3:
-- Interpreter: /usr/bin/python3.13 (ver 3.13.1)
-- Libraries: /usr/lib/x86_64-linux-gnu/libpython3.13.so (ver 3.13.1)
-- Limited API: NO
-- numpy: /usr/local/lib/python3.13/dist-packages/numpy/_core/include (ver 2.2.0)
-- install path: /usr/local/lib/python3.13/dist-packages/cv2/python-3.13
--
-- Python (for build): /usr/bin/python3.13
--
-- Java:
-- ant: NO
-- Java: NO
-- JNI: NO
-- Java wrappers: NO
-- Java tests: NO
--
-- Install to: /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /home/user_data/Bureau/Proj_OPENCV/opencv_build/build
4. Lancer la Compilation
Pour ce faire, placez-vous dans le répertoire build
et lancez la commande suivante :
make -j$(nproc)
Les deux dernières lignes à l'écran doivent se finir de la sorte:
[100%] Linking CXX shared module ../../lib/python3/cv2.cpython-313-x86_64-linux-gnu.so
[100%] Built target opencv_python3
5. Installation d'OpenCV
Cette section explique comment installer OpenCV après avoir terminé la compilation, et détaille différentes approches pour l'utiliser dans vos projets Python.
Étape 1 : Installation d'OpenCV
Une fois la compilation terminée, installez OpenCV sur votre système avec les droits root :
sudo make install
Pendant l'installation, un message comme celui-ci s'affichera dans le terminal :
-- Set runtime path of "/usr/local/lib/python3.13/dist-packages/cv2/python-3.13/cv2.cpython-313-x86_64-linux-gnu.so" to "/usr/local/lib"
Le fichier cv2.cpython-313-x86_64-linux-gnu.so est un binaire généré pour la bibliothèque Python OpenCV. Il a été configuré pour chercher ses dépendances à l'exécution dans le répertoire /usr/local/lib, comme spécifié dans le script CMake.
Pour vérifier si l'installation a réussi, exécutez la commande suivante, cela devrait afficher la version d'OpenCV :
python3.13 -c "import cv2; print(cv2.__version__)"
4.10.0
Étape 2 : Utilisation avec un environnement virtuel
Si vous utilisez des environnements virtuels pour vos projets, vous pouvez inclure OpenCV dans l'environnement grâce à l'option --system-site-packages. Voici comment procéder :
Créez l'environnement virtuel :
python3.13 -m venv --system-site-packages mon_env
Activez l'environnement virtuel :
source mon_env/bin/activate
Vérifiez la disponibilité de la bibliothèque OpenCV :
python -c "import cv2; print(cv2.__version__)"
4.10.0
Vous devriez voir à nouveau la version d'OpenCV (par exemple 4.10.0).
Étape 3 : Utilisation directe du fichier binaire
Une autre option consiste à copier le fichier binaire .so généré par OpenCV directement dans votre répertoire de travail : Copiez le fichier .so dans le répertoire courant, et renommez le fichier pour simplifier son utilisation :
cp /usr/local/lib/python3.13/dist-packages/cv2/python-3.13/cv2.cpython-313-x86_64-linux-gnu.so .
mv cv2.cpython-313-x86_64-linux-gnu.so cv2
Créez votre script Python dans ce répertoire et importez OpenCV directement :
import cv2
print(cv2.__version__)
Cette méthode est utile si vous voulez éviter de modifier des configurations globales ou si vous travaillez sur un projet isolé.
Conclusion
Avec ces étapes, vous pouvez installer et utiliser OpenCV de manière flexible, que ce soit via une installation globale, un environnement virtuel, ou un fichier binaire local. Adaptez la méthode selon vos besoins pour tirer parti d'OpenCV dans vos projets Python !