Advertisement
Advertisement


Cannot find module cv2 when using OpenCV


Question

I have installed OpenCV on the Occidentalis operating system (a variant of Raspbian) on a Raspberry Pi, using jayrambhia's script found here. It installed version 2.4.5.

When I try import cv2 in a Python program, I get the following message:

[email protected]~$ python cam.py
Traceback (most recent call last)
File "cam.py", line 1, in <module>
    import cv2
ImportError: No module named cv2

The file cv2.so is stored in /usr/local/lib/python2.7/site-packages/...

There are also folders in /usr/local/lib called python3.2 and python2.6, which could be a problem but I'm not sure.

Is this a path error perhaps? Any help is appreciated, I am new to Linux.

2019/03/28
1
276
3/28/2019 9:01:15 AM


This happens when python cannot refer to your default site-packages folder where you have kept the required python files or libraries

Add these lines in the code:

import sys

sys.path.append('/usr/local/lib/python2.7/site-packages')

or before running the python command in bash move to /usr/local/lib/python2.7/site-packages directory. This is a work around if you don't want to add any thing to the code.

2014/02/05

I solved my issue using the following command :

conda install opencv
2016/02/22

Try to add the following line in ~/.bashrc

export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH
2016/07/24

Python3.x User

sudo pip3 install opencv-python
2018/10/29

None of the above answers worked for me. I was going crazy until I found this solution below!

Simply run:

sudo apt install python-opencv
2018/05/27