Computer-vision work on Ubuntu usually begins with a Python binding that can load images and expose OpenCV routines to scripts. The distribution package gives the system Python interpreter a ready cv2 module without requiring a source build.
The APT package for the Python binding is python3-opencv, and python3-numpy supplies the array type that most OpenCV examples use. This path fits scripts that run with Ubuntu system Python and need security and library updates from the enabled Ubuntu repositories.
Use a project virtual environment with a PyPI wheel such as opencv-python only when a project needs a newer OpenCV release, contrib modules, or a headless package that avoids desktop window support. A completed APT install should import cv2, print the installed OpenCV version, and write and read a small test image from a writable directory.
Steps to install OpenCV on Ubuntu from APT:
- Open a terminal with sudo privileges.
- Refresh the local package index.
$ sudo apt update
- Install the OpenCV Python binding and NumPy.
$ sudo apt install python3-opencv python3-numpy Reading package lists... Done Building dependency tree... Done ##### snipped ##### Setting up python3-numpy (1:2.3.5+ds-3ubuntu1) ... Setting up python3-opencv (4.10.0+dfsg-7ubuntu5) ...
The exact package versions change as Ubuntu updates its repositories. Install libopencv-dev separately only when compiling C++ code against OpenCV headers and libraries.
- Confirm that Python can import cv2.
$ python3 -c "import cv2; print(cv2.__version__)" 4.10.0
- Run a small image write and read smoke test from a writable directory.
$ python3 - <<'PY' import cv2 import numpy as np image = np.zeros((120, 160, 3), dtype=np.uint8) image[:, :80] = (0, 128, 255) image[:, 80:] = (0, 255, 0) cv2.imwrite("opencv-smoke.png", image) loaded = cv2.imread("opencv-smoke.png") print(loaded.shape) PY (120, 160, 3)The printed shape confirms that OpenCV wrote the PNG file and read it back as a 120 by 160 pixel, three-channel image.
Related: How to read and write an image with OpenCV - Remove the smoke-test image.
$ rm opencv-smoke.png
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.