How do I install OpenCV using pip (pip install cv2)?
I need to install cv2 for a script, but when I try pip install cv2
or pip install open_cv
, I get errors about missing dependencies like zlib. I also tried pip install pyopencv
and pip install opencv-python
, but nothing worked.
I then downloaded the OpenCV installer from the official site, but it generated multiple subdirectories and a makefile.
Instead of pip install cv2, use opencv-python, which is the correct package name:
pip install opencv-python
This installs OpenCV without extra dependencies like GUI support.
Verify Installation
After installation, check if OpenCV is working:
import cv2
print(cv2.version)
If you need additional OpenCV functionalities like SIFT, SURF, and other extra modules, install:
For minimal installation (no GUI support, good for servers)
pip install opencv-python-headless
For extra functionalities like SIFT, SURF, and non-free modules
pip install opencv-contrib-python
If pip install cv2 and the above solutions don’t work, manually compiling OpenCV ensures maximum compatibility.
Steps to Build OpenCV from Source:
1. Install Dependencies:
sudo apt update && sudo apt install cmake g++ python3-dev python3-numpy
2. Clone the OpenCV repository:
git clone https://github.com/opencv/opencv.git
cd opencv
3. Build and install OpenCV:
mkdir build && cd build
cmake ..
make -j4
sudo make install
4. Verify the installation:
import cv2
print(cv2.__version__)