How to Install OpenCV (opencv-python) in CI Without Build Failures
OpenCV installs fine but crashes on import cv2 because the runner is missing the OpenGL and glib shared libraries the wheel links against.
The opencv-python wheel ships the OpenCV binaries but dynamically links to a handful of system libraries (libGL, glib) that slim CI images do not include. The classic failure is ImportError: libGL.so.1: cannot open shared object file. Install the right apt packages and you are done.
Why it fails in CI
The prebuilt opencv-python wheel installs cleanly, so pip succeeds - but at runtime import cv2 dlopen()s libGL.so.1 and libglib-2.0.so.0. Minimal images (python:3.x-slim, many container bases) ship neither, so the import aborts even though nothing about your code is wrong.
ImportError: libGL.so.1: cannot open shared object file- no OpenGL runtime.ImportError: libgthread-2.0.so.0/libglib-2.0.so.0- glib missing.- On a slim image there is no compiler either, so falling back to a source build fails too.
Install it reliably
Keep the prebuilt wheel (never build OpenCV from source in CI) and add the system libraries it needs. On a truly headless runner, opencv-python-headless drops the GUI/GL dependency entirely and is the better default for CI.
# Debian/Ubuntu: add the shared libs the wheel links to
apt-get update && apt-get install -y libgl1 libglib2.0-0
pip install opencv-python
# Headless runners: no GUI/GL dependency at all (recommended for CI)
pip install opencv-python-headlessCache & speed
The wheel is large (tens of MB). Cache the pip download cache so it is not re-downloaded every run, and bake the apt packages into a custom runner image so you are not running apt-get on every job.
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: pip-opencv-${{ hashFiles('requirements*.txt') }}Common errors
| Error | Cause | Fix |
|---|---|---|
| libGL.so.1: cannot open shared object file | No OpenGL runtime | apt-get install libgl1 (or use -headless) |
| libglib-2.0.so.0 not found | glib missing | apt-get install libglib2.0-0 |
| Two cv2 versions / odd behavior | opencv-python + headless both installed | Keep only one |
| Building wheel for opencv-python ... error | No wheel for this Python; source build | Pin a Python with a wheel |
Key takeaways
- Use the prebuilt wheel; never compile OpenCV in CI.
- Add libgl1 + libglib2.0-0, or use opencv-python-headless on headless runners.
- Cache ~/.cache/pip and bake the apt libs into the image.