After install ROS Kinetic, cannot import OpenCV After install ROS Kinetic, cannot import OpenCV python python

After install ROS Kinetic, cannot import OpenCV


It looks like this problem is caused by ROS adding /opt/ros/kinetic/lib/python2.7/dist-packages to the python path. This actually happens when you activate ROS with the command source /opt/ros/kinetic/setup.bash. This line is often added at the end of your bashrc file, in /home/username/.bashrc.

A workaround is to remove this line from the bashrc file. This way the python3 opencv packages will be correctly used, and you can still run source /opt/ros/kinetic/setup.bash to use ROS. However, this does mean you cannot use ROS and python3 from the same environment.

Hopefully someone can come up with a better answer, but this should work until then.


If you are working with anaconda, activate the environment you want to work from, and remove the culprit from sys.path.

To do so, open a python3 console, from which:

>>> import sys>>> print(sys.path)

You will see several path, among which you should notice:

'/opt/ros/kinetic/lib/python2.7/dist-packages'

Then remove it:

>>> sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')

Tested with python3.5 on anaconda3 with locally compiled opencv. This is likely applicable to virtualenvs as well.

For a permanent solution, remove the path '/opt/ros/kinetic/lib/python2.7/dist-packages' from ~/.bashrc as mentioned in @Paul's answer.


As pointed out, the source /opt/ros/kinetic/setup.bash command in your .bashrc modifies the PYTHONPATH to be:

> echo $PYTHONPATH/opt/ros/kinetic/lib/python2.7/dist-packages

In my case, since I am using a virtualenv for my Python 3 projects, I just ran the following command to clear the PYTHONPATH variable, while the virtualenv is activated.

unset PYTHONPATH

Now, importing cv2 in Python 3 virtualenv works cleanly. I verified the path of cv2:

In [1]: import cv2In [2]: cv2.__file__Out[2]: '<path_to_virtualenv>/lib/python3.5/site-packages/cv2/cv2.cpython-35m-x86_64-linux-gnu.so'

To avoid having to run this command every time I activate that virtualenv, I added it to the /bin/activate file in the virtualenv directory, as follows:

...# unset irrelevant variablesdeactivate nondestructiveunset PYTHONPATHVIRTUAL_ENV="/home/kaiyuzh/pyenv/py3"export VIRTUAL_ENV...