Linking OpenCV to Python

Let's follow these steps to link OpenCV to Python:

  1. Open the python 3.5 folder (/usr/local/python/cv2/python-3.5): 

Inside this folder, you should see a file named cv2.so or cv2.cpython-35m-arm-linux-gnueabihf.soIf the filename is cv2.so, you do not need to make any changes. If the filename is cv2.cpython-35m-arm-linux-gnueabihf.so, you have to rename it to cv2.so. To rename this file, change the directory to python 3.5 by entering the following command:

cd /usr/local/python/cv2/python-3.5

To rename this file from cv2.cpython-35m-arm-linux-gnueabihf.so to cv2.so, enter the following command:

sudo mv /usr/local/python/cv2/python3.5/cv2.cpython-35m-arm-linux-gnueabihf.so cv2.so
  1. Move this file to the dist-package folder (/usr/local/lib/python3.5/dist-packages/) using the following command:
sudo mv /usr/local/python/cv2/python-3.5/cv2.so /usr/local/lib/python3.5/dist-packages/cv2.so
  1. To test whether OpenCV 4.0.0 is linked properly to Python 3, go to the pi directory by typing cd ~ in the Terminal windowNext, type python3:

  1. You should see a three-corner bracket. Type import cv2.
  2. To check the OpenCV version, type cv2.__version__. If you see opencv 4.0.0, this means that OpenCV is successfully installed and linked with the Python packages:

  1. Type exit() and press Enter:

After installing OpenCV, we need to reset CONF_SWAPSIZE back to 100:

  1. Open swapfile:
sudo nano /etc/dphys-swapfile
  1. Change CONF_SWAPSIZE to 100:

  1. To apply these changes, enter the following commands:
sudo /etc/init.d/dphys-swapfile stop
sudo /etc/init.d/dphys-swapfile start

You have successfully installed OpenCV 4.0.0 on your Raspberry Pi. We are now ready to attach the RPi camera to the RPi.