cv2 import error on Jupyter notebook

I didn't have the openCV installation in my Python3 kernel, so I installed it by activating the specific environment and running this in the command prompt:

pip install opencv-python

How to find and activate my environment?

To list all of Your conda environments, run this command:

conda info --envs

You will get something like this:

ipykernel_py2            D:\Anaconda\envs\ipykernel_py2
root                     D:\Anaconda

After that, activate the environment that is complaining for the missing cv2 and run the pip install opencv-python command.

How to activate an environment?

Just run the command:

activate env_name

where env_name is the wanted environment (for example, You could type activate ipykernel_py2 if You wanted to access the first of the two environments listed above).

Note: If You are on Linux, You need to type source activate env_name.


Go to your notebook, in menu section

kernel -> Change kernel -> Python<desired version>

Now in the notebook run following command to install opencv2 in the selected environment kernel

python2:

!pip install opencv-python

python3:

!pip3 install opencv-python


Is your python path looking in the right place? Check where python is looking for the module. Within the notebook try:

import os
os.sys.path

Is the cv2 module located in any of those directories? If not your path is looking in the wrong place. If it is overlooking the install location, append it to your python path. You can follow the instructions here.


Binmosa's explanation is great and to the point. As an alternative (easier, but I'm pretty sure it's just a band-aid fix), if you write:

    import sys
    !{sys.executable} -m pip install opencv-python

directly into your notebook, you'll be able to actually install the module in the notebook itself.

The longer explanation is interesting and informative, though. Link: https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/