IF YOU ARE BUILDING FROM SCRATCH, GO THROUGH THIS
You get No module named cv2.cv
.
Son, you did all step right, since your sudo make install
gave no errors.
However look at this step
$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
$ ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so
THE VERY IMPORTANT STEP OF ALL THESE IS TO LINK IT.
ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so
or
ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so
The moment you choose wise linking, or by brute force just find the cv2.so file if that exist or not
Here I am throwing my output.
Successfully installed numpy-1.15.3
(cv) demonLover-desktop:~$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ pip list
Package Version
---------- -------
numpy 1.15.3
pip 18.1
setuptools 40.5.0
wheel 0.32.2
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ python
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named cv2
>>>
[2]+ Stopped python
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls /usr/local/lib/python2.7/site-packages/c
ls: cannot access '/usr/local/lib/python2.7/site-packages/c': No such file or directory
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls /usr/local/lib/python2.7/site-packages/
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ deactivate
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls /usr/local/lib/python2.7/site-packages/
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls
cv2.so easy_install.py easy_install.pyc numpy numpy-1.15.3.dist-info pip pip-18.1.dist-info pkg_resources setuptools setuptools-40.5.0.dist-info wheel wheel-0.32.2.dist-info
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls /usr/local/lib/python2.7/site-packages/
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls -l /usr/local/lib/python2.7/site-packages/
total 0
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls
cv2.so easy_install.py easy_install.pyc numpy numpy-1.15.3.dist-info pip pip-18.1.dist-info pkg_resources setuptools setuptools-40.5.0.dist-info wheel wheel-0.32.2.dist-info
demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ workon cv
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ python
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named cv2
>>>
[3]+ Stopped python
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ find / -name "cv2.so"
find: ‘/lost+found’: Permission denied
find: ‘/run/udisks2’: Permission denied
find: ‘/run/docker’: Permission denied
find: ‘/run/exim4’: Permission denied
find: ‘/run/lightdm’: Permission denied
find: ‘/run/cups/certs’: Permission denied
find: ‘/run/sudo’: Permission denied
find: ‘/run/samba/ncalrpc/np’: Permission denied
find: ‘/run/postgresql/9.5-main.pg_stat_tmp’: Permission denied
find: ‘/run/postgresql/10-main.pg_stat_tmp’: Permission denied
find: ‘/run/lvm’: Permission denied
find: ‘/run/systemd/inaccessible’: Permission denied
find: ‘/run/lock/lvm’: Permission denied
find: ‘/root’: Permission denied
^C
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ sudofind / -name "cv2.so"
sudofind: command not found
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ^C
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ sudo find / -name "cv2.so"
[sudo] password for app:
find: ‘/run/user/1000/gvfs’: Permission denied
^C
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ sudo find /usr/ -name "cv2.so"
/usr/local/lib/python2.7/dist-packages/cv2.so
^C
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ln -s /usr/local/lib/python2.7/dist-packages/ccv2.so cv2.so
click/ clonevirtualenv.pyc configparser-3.5.0.dist-info/ configparser.py cv2.so cycler.py
clonevirtualenv.py concurrent/ configparser-3.5.0-nspkg.pth configparser.pyc cycler-0.10.0.dist-info/ cycler.pyc
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so
ln: failed to create symbolic link 'cv2.so': File exists
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ rm cv2.so
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ ls
cv2.so easy_install.py easy_install.pyc numpy numpy-1.15.3.dist-info pip pip-18.1.dist-info pkg_resources setuptools setuptools-40.5.0.dist-info wheel wheel-0.32.2.dist-info
(cv) demonLover-desktop:~/.virtualenvs/cv/lib/python2.7/site-packages$ python
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>
My step will only help, if your built is done right.
Although you’ll find a lot of tutorials that help you install opencv and ffmpeg (both go hand in hand almost always) out there, I will post what worked for me here.
Steps for installing ffmpeg correctly
- Download the latest static version of ffmpeg from the download page depending on your os.
- Extract the installed zip file using 7-zip. The folder will be named something like «ffmpeg-20130731-git-69fe25c-win32-static».
- Create a new folder named
ffmpeg
in yourC:
and copy the contents of the extracted folder into this new one. - Now click the start button, right-click on computer. Select Properties from the right-click menu. In the System window, click on the “Advanced system settings” link.
- Click the Environmental Variables button in the System Properties window. It will be located at the bottom of the window.
- Select the PATH entry in the «User variables» section. Click the Edit button.
In the “Variable value” field, enter;c:ffmpegbin
after anything that’s already written there. If you copied it to a different drive, change the drive letter.
Click OK to save your changes.
If there is no PATH entry in the «User variables» setting, click the New button and create one. Enter PATH for the variable name.
This method will enable FFmpeg for the current user. Other Windows users will not be able to run it from the command line. To enable it for everyone, enter;c:ffmpegbin
in the PATH entry in «System variables». Be very careful not to delete anything that is already in this variable. - Open the command prompt. Enter the command
ffmpeg –version
. If the command prompt returns the version information for FFmpeg, then the installation was successful, and FFmpeg can be accessed from any folder in the command prompt.
If you receive alibstdc++ -6 is missing
error, you may need to install the Microsoft Visual C++ Redistributable Package, which is available for free from Microsoft.
I followed these steps from a site I don’t remember but this worked just as fine.
Now to install opencv and get it working, I followed the following steps:
- Download the self-extracting executable from the OpenCV website.
- Run the Executable which will in turn extract the executable.
- Create a folder in
C:
calledopencv
- Copy the contents of the extracted files into
opencv
- Edit your PATH environment variable. This will be dependent on the version you want installed (i.e. 32 or 64 bit) and also the version of visual studio you have installed (express editions are fine).
—-Installing OpenCV Python
I use Anaconda. So, I copied the cv2.pyd
file from this OpenCV directory (the beginning part might be slightly different on your machine):
Python 2.7 and 32-bit machine:
C:opencvbuildpython2.7x84
Python 2.7 and 64-bit machine:
C:opencvbuildpython2.7x64
To this Anaconda directory (the beginning part might be slightly different on your machine):
C:UsersxxxAnacondaLibsite-packages
OpenCV also requires that numpy be installed as well. matplolib is also recommended to be installed.
You’ll also have to locate the two .dll
files in the bin
folder of your opencv
folder. And copy and paste them into the ffmpeg/bin
folder as well as into the site-packages folder in your Anaconda folder. When I installed opencv, I didn’t have the bin folder installed (weird, I know). So, I copied my friend’s .dll
files and renamed them to the version of opencv that I was using and it worked!
After installing both OpenCV and ffmpeg you’ll need to restart your computer to add the paths to the system path.
Hope this helps! For a lot of people, most of the steps above were not necessary. But for me, this worked! I use Windows 10, Opencv 3.0, Python 2.7!
i run test code
get error
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-8-950f128db003> in <module>
1 import numpy as np
----> 2 import cv2
3
4 cap = cv2.VideoCapture(0)
5
~AppDataRoamingPythonPython37site-packagescv2__init__.py in <module>
1 import importlib
2
----> 3 from .cv2 import *
4 from .data import *
5
ModuleNotFoundError: No module named 'cv2.cv2'
my code
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
if cap.isOpened():
print("Webcam online.")
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
my os win10
- 64 but i using anaconda 32
- opencv-python version (4.0.0.21)
Sounds like you have a conflicting / another cv2 installation somewhere in your current environment. Create a fresh virtualenv and try to install opencv-python
there. Also check that there is a cv2 .pyd file at ~AppDataRoamingPythonPython37site-packagescv2
.
Sounds like you have a conflicting / another cv2 installation somewhere in your current environment. Create a fresh virtualenv and try to install
opencv-python
there. Also check that there is a cv2 .pyd file at~AppDataRoamingPythonPython37site-packagescv2
.
Thank for the help
Sounds like you have a conflicting / another cv2 installation somewhere in your current environment. Create a fresh virtualenv and try to install
opencv-python
there. Also check that there is a cv2 .pyd file at~AppDataRoamingPythonPython37site-packagescv2
.
Hi, i don’t have the cv2.pyd ? I’m using conda env, and i already install all dependencies in a fresh env, but i still get the same error: ModuleNotFoundError: No module named ‘cv2.cv2’
Sounds like you have a conflicting / another cv2 installation somewhere in your current environment. Create a fresh virtualenv and try to install
opencv-python
there. Also check that there is a cv2 .pyd file at~AppDataRoamingPythonPython37site-packagescv2
.Hi, i don’t have the cv2.pyd ? I’m using conda env, and i already install all dependencies in a fresh env, but i still get the same error: ModuleNotFoundError: No module named ‘cv2.cv2’
Hi i am also face same issue can u help me
I had the same issue, turned out I was still in the source directory of opencv-python (which has cv2 dir as well).
Move to another dir, start python and import cv2.
I had the same issue, is there anyone shed some light on this?My env is macos 10.15.7, python 3.9, pip 20.2.4, opencv-python 4.4.0.46;
ok, finally, I solved the issue. The reason is there’s no compatible version of opencv-python for python3.9, I downgrade python to 3.8 to fix this issue.
same issue, python 3.8.1
ModuleNotFoundError: No module named ‘cv2.cv2’
HELP
Hi ! I got the same problem as well.
I installed a conda environnement to use pypy3.7. I am using python 3.7. I used the line command in my environnement
pypy3 -m pip install opencv-python
It worked very well, however when I launched a pypy script which import cv2, I get the same issue than you guys :
I tried to uninstall and reinstall with pip adapted for pypy, the same command as above. With python, it works without problem but pypy3 shows issues with opencv
A common error you may encounter when using Python is modulenotfounderror: no module named ‘cv2’. This error occurs when Python cannot detect the OpenCV library in your current environment.
You can install OpenCV
using pip
as follows:
python3 -m pip install opencv-python
You can install OpenCV
using conda
as follows:
conda install -c conda-forge opencv
This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.
Table of contents
- ModuleNotFoundError: no module named ‘cv2’
- What is ModuleNotFoundError?
- What is cv2?
- Always Use a Virtual Environment to Install Packages
- How to Install cv2 on Windows Operating System
- cv2 installation on Windows Using pip and virtualenv
- How to Install cv2 on Mac Operating System
- cv2 installation on Mac Using pip and virtualenv
- How to Install cv2 on Linux Operating Systems
- Installing pip for Ubuntu, Debian, and Linux Mint
- Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
- Installing pip for CentOS 6 and 7, and older versions of Red Hat
- Installing pip for Arch Linux and Manjaro
- Installing pip for OpenSUSE
- cv2 installation on Linux Using pip and virtualenv
- Installing cv2 Using Anaconda
- Check cv2 Version
- How to Install cv2 on Windows Operating System
- Summary
ModuleNotFoundError: no module named ‘cv2’
What is ModuleNotFoundError?
The ModuleNotFoundError occurs when the module you want to use is not present in your Python environment. There are several causes of the modulenotfounderror:
The module’s name is incorrect, in which case you have to check the name of the module you tried to import. Let’s try to import the re module with a double e to see what happens:
import ree
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) 1 import ree ModuleNotFoundError: No module named 'ree'
To solve this error, ensure the module name is correct. Let’s look at the revised code:
import re print(re.__version__)
2.2.1
You may want to import a local module file, but the module is not in the same directory. Let’s look at an example package with a script and a local module to import. Let’s look at the following steps to perform from your terminal:
mkdir example_package cd example_package mkdir folder_1 cd folder_1 vi module.py
Note that we use Vim to create the module.py file in this example. You can use your preferred file editor, such as Emacs or Atom. In module.py, we will import the re module and define a simple function that prints the re version:
import re def print_re_version(): print(re.__version__)
Close the module.py, then complete the following commands from your terminal:
cd ../ vi script.py
Inside script.py, we will try to import the module we created.
import module if __name__ == '__main__': mod.print_re_version()
Let’s run python script.py from the terminal to see what happens:
Traceback (most recent call last): File "script.py", line 1, in ≺module≻ import module ModuleNotFoundError: No module named 'module'
To solve this error, we need to point to the correct path to module.py, which is inside folder_1. Let’s look at the revised code:
import folder_1.module as mod if __name__ == '__main__': mod.print_re_version()
When we run python script.py
, we will get the following result:
2.2.1
Lastly, you can encounter the modulenotfounderror when you import a module that is not installed in your Python environment.
What is cv2?
It may be unclear to see cv, cv2, and OpenCV used interchangeably online. OpenCV stands for Open Source Computer Vision Library, and it provides a common infrastructure for computer vision applications. OpenCV is written in C/C++ and has two Python interfaces, CV and CV2. CV2 is the latest Python interface. OpenCV does not come automatically installed with Python. The simplest way to install OpenCV is to use the package manager for Python called pip. The following installation instructions are for the major Python version 3.
Always Use a Virtual Environment to Install Packages
It is always best to install new libraries within a virtual environment. You should not install anything into your global Python interpreter when you develop locally. You may introduce incompatibilities between packages, or you may break your system if you install an incompatible version of a library that your operating system needs. Using a virtual environment helps compartmentalize your projects and their dependencies. Each project will have its environment with everything the code needs to run. Most ImportErrors and ModuleNotFoundErrors occur due to installing a library for one interpreter and trying to use the library with another interpreter. Using a virtual environment avoids this. In Python, you can use virtual environments and conda environments. We will go through how to install cv2 with both.
How to Install cv2 on Windows Operating System
First, you need to download and install Python on your PC. Ensure you select the install launcher for all users and Add Python to PATH checkboxes. The latter ensures the interpreter is in the execution path. Pip is automatically on Windows for Python versions 2.7.9+ and 3.4+.
You can check your Python version with the following command:
python3 --version
You can install pip on Windows by downloading the installation package, opening the command line and launching the installer. You can install pip via the CMD prompt by running the following command.
python get-pip.py
You may need to run the command prompt as administrator. Check whether the installation has been successful by typing.
pip --version
cv2 installation on Windows Using pip and virtualenv
To install cv2, first create the virtual environment. The environment can be any name, in this we choose “env”:
virtualenv env
You can activate the environment by typing the command:
envScriptsactivate
You will see “env” in parenthesis next to the command line prompt. You can install cv2 within the environment by running the following command from the command prompt.
python3 -m pip install opencv-python
We use python -m pip to execute pip using the Python interpreter we specify as Python. Doing this helps avoid ImportError when we try to use a package installed with one version of Python interpreter with a different version. You can use the command which python to determine which Python interpreter you are using.
How to Install cv2 on Mac Operating System
Open a terminal by pressing command (⌘) + Space Bar
to open the Spotlight search. Type in terminal and press enter. To get pip, first ensure you have installed Python3:
python3 --version
Python 3.8.8
Download pip by running the following curl command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
The curl command allows you to specify a direct download link. Using the -o option sets the name of the downloaded file.
Install pip by running:
python3 get-pip.py
cv2 installation on Mac Using pip and virtualenv
To install cv2, first create the virtual environment:
python3 -m venv env
Then activate the environment using:
source env/bin/activate
You will see “env” in parenthesis next to the command line prompt. You can install cv2 within the environment by running the following command from the command prompt.
python3 -m pip install opencv-python
How to Install cv2 on Linux Operating Systems
All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip. Open a terminal and use the commands relevant to your Linux distribution to install pip.
Installing pip for Ubuntu, Debian, and Linux Mint
sudo apt install python-pip3
Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
sudo dnf install python-pip3
Installing pip for CentOS 6 and 7, and older versions of Red Hat
sudo yum install epel-release sudo yum install python-pip3
Installing pip for Arch Linux and Manjaro
sudo pacman -S python-pip
Installing pip for OpenSUSE
sudo zypper python3-pip
cv2 installation on Linux Using pip and virtualenv
To install cv2, first create the virtual environment:
python3 -m venv env
Then activate the environment using:
source env/bin/activate
You will see “env” in parenthesis next to the command line prompt. You can install cv2 within the environment by running the following command from the command prompt.
python3 -m pip install opencv-python
Installing cv2 Using Anaconda
Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have Anaconda installed, you can create a conda virtual environment to install cv2.
First, create a conda environment to install cv2.
conda create -n project python=3.6
Then activate the project container. You will see “project” in parentheses next to the command line prompt.
source activate project
Now you’re ready to install cv2 using conda.
conda install -c conda-forge opencv
Check cv2 Version
Once you have successfully installed cv2, you can use two methods to check the version of cv2. First, you can use pip show from your terminal. Remember that the name of the package is opencv-python.
pip show opencv-python
Name: opencv-python Version: 4.5.5.62 Summary: Wrapper package for OpenCV python bindings.
Second, within your python program, you can import cv2 and then reference the __version__ attribute:
import cv2 print(cv2.__version__)
4.5.5
Summary
Congratulations on reading to the end of this tutorial. The modulenotfounderror occurs if you misspell the module name, incorrectly point to the module path or do not have the module installed in your Python environment. If you do not have the module installed in your Python environment, you can use pip to install the package. However, you must ensure you have pip installed on your system. You can also install Anaconda on your system and use the conda install command to install OpenCV.
For further reading on installing data science and machine learning libraries, you can go to the articles:
- Requests: How to Solve Python ModuleNotFoundError: no module named ‘requests’
- Pandas: How to Solve Python ModuleNotFoundError: no module named ‘pandas’
- Matplotlib: How to Solve Python ModuleNotFoundError: no module named ‘matplotlib’
- Pygame: How to Solve Python ModuleNotFoundError: no module named ‘pygame’
- PyTorch: How to Solve Python ModuleNotFoundError: no module named ‘torch’
- openpyxl: How to Solve Python ModuleNotFoundError: no module named ‘openpyxl’
Go to the online courses page on Python to learn more about Python for data science and machine learning.
Have fun and happy researching!
OpenCV — это библиотека для программирования, ориентированная на компьютерное зрение в реальном времени. Для языка Python OpenCV — это библиотека, которую вы можете использовать для решения проблем компьютерного зрения.
Чтобы установить OpenCV в MacOS, введите следующую команду.
python3 pip install —m opencv—python |
Если вы используете LinuxOS, вы можете ввести следующее.
pip install opencv—python |
Если он все еще не работает, вы можете использовать следующую команду.
sudo apt install python—opencv |
Если вы используете ОС Windows для установки используйте следующий код.
pip install opencv—python |
Следующий шаг — открыть редактор кода, такой как Visual Studio Code, и импортировать модуль cv2 в файл кода Python.
Теперь, если вы запустите файл, вы получите такую ошибку: Модуль Python cv2 не найден.
Ошибка «модуль cv2 не найден» возникла из-за того, что интерпретатор Python каким-то образом не находит путь к модулю opencv-python.
Устранение ошибки: модуль Python cv2 не найден
Эта ошибка возникает, когда Python не может обратиться к вашей папке пакетов сайтов по умолчанию, в которой вы сохранили необходимые файлы или библиотеки Питон.
Чтобы устранить эту ошибку (Модуль Python cv2 не найден): добавьте следующий код в начало файла.
import sys sys.path.append(‘/usr/local/lib/python3.9/site-packages’) |
или перед запуском команды Python в bash перейдите в каталог /usr/local/lib/python3.9/site-packages. Это не лучший способ, так как это выглядит ненужным кодом для нашей программы. Но есть обходной путь. Используйте его, если не хотите ничего добавлять в код.
Если вы используете Anaconda Navigator, вы можете устранить ошибку модуля cv2, не найденную с помощью следующей команды.
conda update anaconda—navigator conda update navigator—updater |
Если ваша Anaconda вообще не содержит OpenCV, вы можете установить ее с помощью следующей команды.
Если вы хотите установить opencv в виртуальной среде, выполните следующую команду в терминале, чтобы получить список виртуальных сред.
Или команда Jupyter Notebook следующая.
Затем обновите Anaconda.
conda update anaconda—navigator conda update navigator—updater |
Установите opencv по выбранному вами пути среды.
conda install —c [‘environment path’] opencv |
Автор статей и разработчик, делюсь знаниями.