Once the packages you need for OpenCV are ready, you can begin to compile it. To help with this, however, you’ll need to tweak the swap file on your Raspberry Pi.
The swap file is used when physical memory has been exhausted, ensuring your Raspberry Pi doesn’t crash when it runs out of RAM. Instead, it saves some data to your SD card, allowing it to prioritize other running processes.
To do this, type the following in a terminal window or over SSH:
sudo nano /etc/dphys-swapfile
In the nano file editor, replace CONF_SWAPSIZE=100 with CONF_SWAPSIZE=2048. Once the file has been edited, press Ctrl + X on your keyboard, then hit the Y + Enter keys to confirm and save.
You’ll then need to restart the swap file service. To do this, type the following in the terminal or over SSH:
sudo systemctl restart dphys-swapfile
This will recreate the swap file, giving you more memory to use while compiling OpenCV. Once that’s completed, type the following in a terminal or over SSH to download the source code and generate the necessary makefile for OpenCV on your Raspberry Pi:
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
mkdir ~/opencv/build
cd ~/opencv/build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \
-D ENABLE_NEON=ON \
-D ENABLE_VFPV3=ON \
-D BUILD_TESTS=OFF \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D CMAKE_SHARED_LINKER_FLAGS=-latomic \
-D BUILD_EXAMPLES=OFF ..
If the makefile is created successfully, you can then begin to compile OpenCV. To do this, type the following in a terminal or over SSH:
make -j$(nproc)
Using the
-j$(nproc)
argument will massively speed up the compilation process, especially if you have a newer Raspberry Pi with multiple CPU cores available. The older the Raspberry Pi, the longer the compilation process, which could take several hours to complete.
Once the compilation process has completed (and assuming it completed successfully), you can then move to install the compiled OpenCV package. To do this, type the following in a terminal or over SSH:
sudo make install
sudo ldconfig
This will install OpenCV and allow it to run after it’s been installed. Once OpenCV is installed, repeat the steps above to return your swap file to a normal size by typing the following in a terminal window or over SSH:
sudo nano /etc/dphys-swapfile
Return CONF_SWAPSIZE=2048 back to the default CONF_SWAPSIZE=100, then press Ctrl + X, Y and Enter on your keyboard to save. To restart the swap file service, type the following in a terminal or over SSH:
sudo systemctl restart dphys-swapfile
This will return the swap file to normal. At this point, you’re ready to begin using OpenCV.