---
# System prepended metadata

title: 自建opencv有ffmpeg及cuda

---

自建opencv有ffmpeg及cuda
===

參考資料：

https://www.cerebrumedge.com/single-post/2017/12/26/Compiling-OpenCV-with-CUDA-and-FFMpeg-on-Ubuntu-1604

這個更完整，沒試過
https://medium.com/@sb.jaduniv/how-to-install-opencv-4-2-0-with-cuda-10-1-on-ubuntu-20-04-lts-focal-fossa-bdc034109df3

## 先安裝必要的庫
```
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install build-essential cmake pkg-config
sudo apt-get install libjpeg8-dev libtiff5-dev libjasper-dev libpng12-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
udo apt-get install libxvidcore-dev libx264-dev
sudo apt-get install libgtk-3-dev
sudo apt-get install libatlas-base-dev gfortran
sudo apt-get install ffmpeg
```

## 下載`opencv`及`opencv_contrib`
```
git clone https://github.com/opencv/opencv.git
cd opencv
git checkout <最新的版本，如4.5.0>
cd ..
git clone https://github.com/opencv/opencv_contrib.git
cd opencv_contrib
git checkout <最新的版本，如4.5.0，必須和opencv一樣>
cd ..
```

## 建立`open_cv`下的`build`目錄
```
cd ~/opencv
mkdir build
cd build
```

## `make`的參數

最重要的就是`opencv_contrib`和有關python套件的目錄，這是已經安裝了`anaconda`的參數，沒裝就不一樣了

```
cmake -D CMAKE_BUILD_TYPE=RELEASE \
            -D CMAKE_INSTALL_PREFIX=/usr/local \
            -D INSTALL_C_EXAMPLES=ON \
            -D INSTALL_PYTHON_EXAMPLES=ON \
            -D OPENCV_EXTRA_MODULES_PATH=/home/joshhu/opencv_contrib/modules \
            -D BUILD_EXAMPLES=ON \
            -D WITH_FFMPEG=1 \
            -D WITH_CUDA=ON \
            -D CUDA_GENERATION=Turing \
            -D ENABLE_FAST_MATH=1 \
            -D CUDA_FAST_MATH=1 \
            -D WITH_CUBLAS=1 \
            -D PYTHON_DEFAULT_EXECUTABLE=/home/joshhu/anaconda3/bin/python \
            -D PYTHON3_INCLUDE_DIR=/home/joshhu/anaconda3/include/python3.7m \
            -D PYTHON3_LIBRARY=/home/joshhu/anaconda3/lib/libpython3.7m.so \
            -D PYTHON3_PACKAGES_PATH=/home/joshhu/anaconda3/lib/python3.7 \
            -D WITH_LAPACK=OFF \
            -D PYTHON3_NUMPY_INCLUDE_DIRS=/home/joshhu/anaconda/lib/python3.7/site-packages/numpy/core/include ..
```

## 建立`opencv`
```
make -j16
sudo make install
```