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
ffmpegin 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:ffmpegbinafter 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:ffmpegbinin 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 missingerror, 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!

В заголовке известная ошибка python3.
Интерпретатор python2 импортирует opencv без ошибок при установке совместно с python3 в единой среде исполнения.
Краткая инструкция по локализации ошибки далее.
Среда исполнения
Дистрибутив линукс с длинным циклом поддержки.
Установлены все стабильные обновления.
Все пакеты развёрнуты системным менеджером ( apt ) или сборкой в среде исполнения из исходных текстов штатными средствами.
Установлены штатным способом два интерпретатора: python-2.7 и python-3.5.
Пакетов со стороны, пакетов собранных вне среды исполнения, нарушенных зависимостей, конфликтов версий нет.
Признаки ошибки
Ошибка возникает на этапе загрузки библиотеки opencv в интерпретаторе python‑3.5.

Причина ошибки
Причина ошибки — разные файловые структуры у python‑2.7 и python‑3.5; отличие системы индексов версий в именовании каталогов и файлов.
В одном случае, python‑2.7, один индекс версии — 2.7.
В другом случае, python‑3.5, три индекса версии — 3, 3.5 и 3.5m.
Конфигуратор сборки opencv устанавливает файловые пути python3 подобно python2.
Сборка и установка модулей opencv для python3 производится с ошибками файловой структуры.
Локализация ошибки
Ошибка исправляется через уточнение связанных параметров cmake с последующей установкой opencv из исходных текстов.
CMAKE_BUILD_TYPE:STRING=Release
OPENCV_FORCE_PYTHON_LIBS:BOOL=ON
OPENCV_PYTHON3_VERSION:BOOL=ON
PYTHON2_EXECUTABLE:FILEPATH=/usr/bin/python2.7
PYTHON2_INCLUDE_DIR:PATH=/usr/include/python2.7
PYTHON2_INCLUDE_DIR2:PATH=/usr/include/x86_64-linux-gnu/python2.7
PYTHON2_LIBRARY:FILEPATH=/usr/lib/x86_64-linux-gnu/libpython2.7.so
PYTHON2_LIBRARY_DEBUG:FILEPATH=
PYTHON2_NUMPY_INCLUDE_DIRS:PATH=/usr/lib/python2.7/dist-packages/numpy/core/include
PYTHON2_PACKAGES_PATH:PATH=/usr/lib/python2.7/dist-packages
PYTHON3_EXECUTABLE:FILEPATH=/usr/bin/python3
PYTHON3_INCLUDE_DIR:PATH=/usr/include/python3.5m
PYTHON3_INCLUDE_DIR2:PATH=/usr/include/x86_64-linux-gnu/python3.5m
PYTHON3_LIBRARY:FILEPATH=/usr/lib/x86_64-linux-gnu/libpython3.5m.so
PYTHON3_LIBRARY_DEBUG:FILEPATH=
PYTHON3_NUMPY_INCLUDE_DIRS:PATH=/usr/lib/python3/dist-packages/numpy/core/include
PYTHON3_PACKAGES_PATH:PATH=/usr/lib/python3/dist-packages
Заключение
Ошибка локализована параметрами cmake.

Для других сред исполнения и версий python3 уточнять параметры cmake по‑обстоятельствам.
- OpenCV = latest
- Operating System / Platform => Windows 64 Bit
- Compiler => Visual Studio 2017
- Python 3.7.7
Detailed description
Please help, I had no luck on the opencv forum. I was able to succesfully install opencv with CUDA 10.2, but for the framework I am running it with, I needed CUDA 10.0. I am experiencing errors when importing cv2.
Steps to reproduce
I built opencv with cmake, and experienced no errors but «CMake Warning at cmake/OpenCVGenSetupVars.cmake:54 (message):» in which I unchecked it and the error resolved. After successfully building in VS, these are the commands and errors that followed:
C:>python
Python 3.7.7 (tags/v3.7.7:d7c567b08f, Mar 10 2020, 10:41:24) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:Python37cv2__init__.py", line 96, in <module>
bootstrap()
File "C:Python37cv2__init__.py", line 86, in bootstrap
import cv2
ImportError: DLL load failed: The specified module could not be found.
>>>
How can I resolve these or any idea what causes this? I made sure the correct path was in my path in systems variable (C:opencvbuildinstallx64vc15bin).
Opencv is a library that is very helpful in image pre or post-processing. If you are a python programmer and you are unable to install OpenCV, then this post is for you. importerror no module named cv2 error occurs when cv2 module is not properly installed or its path is not properly set or configured. The straight way fix for this error (no module named cv2) is to reinstall this module (OpenCV-python).
In some scenario reinstalling this module automatically remove the older version. But in some scenarios, We need to manually delete the older or incompatible version of cv2 module (OpenCV-python). In this article, We will encounter these ways one by one.
There are so many ways to install this packager. Let’s see one by one.
Method 1: Using pip package Manager-
1.1 Use the below command to fix this issue.

pip install opencv-python

1.2 In the case of the Python 3. x version, You may use the below command.
pip3 install opencv-python
If the above command is not working. There may be a strong possibility that the pip package manager is not updated. So install it.
python -m pip install --upgrade pip
Method 2: Using conda package Manager-
In the above section, we have used the pip package manager. The conda manager is the same as pip. So we can also use conda to install the OpenCV or cv2 module. Here is the way to do so.
conda install opencv

Note –
Well, At the beginning of the article, I have mentioned that reinstall any module will first uninstall the older version. But you manually do it with the below command also.
pip uninstall opencv-python
It will manually uninstall the module.
Conclusion –
“importerror no module named cv2” is a very common error. Also, the import errors whether for cv2 or any other module has the same solution. Sometimes you get this error when you wrongly type the import statement. For example, instead of writing import cv2 , you write import cv . This leads to an import error when you run the code. I hope once you read this article, You may easily fix this error. Still, If you think, You are stuck. Please contact us or comment below on the comment box. We will surely assist in this.
No Module Named cv2 ( Other Specifications ) –
We have already provided the generic solution for No Module Named cv2 error. Since this error can be produced in different environment like Linux, Mac, Windows etc. On the other hand the same error No Module Named cv2 can be produced in any of the IDE like jupyter, Pycharm, Spyder or with any package bundle like anaconda. But the solution in most of the cases will be common irrespective of OS, Platform, IDE etc.
Similar Errors :
1. Importerror attempted relative import with no known parent package
2. Importerror: no module named requests – Lets Fix step by step
3. ImportError: numpy.core.multiarray failed to import [cv2, matplotlib, PyTorch, pyinstaller ]
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.
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 |
Автор статей и разработчик, делюсь знаниями.

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!
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
1 |
|
|
20.10.2018, 17:31. Показов 17834. Ответов 16
Доброго дня! Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
__________________
0 |
|
1288 / 905 / 479 Регистрация: 05.12.2013 Сообщений: 3,036 |
|
|
20.10.2018, 23:50 |
2 |
|
Вы в IDLE запускаете, возьмите нормальный редактор
0 |
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
21.10.2018, 20:11 [ТС] |
3 |
|
Это понятно, писать код можно хоть в блокноте, а исполнять код как тогда? не редактором ведь.. или я чего то не знаю?
0 |
|
Garry Galler
5403 / 3827 / 1214 Регистрация: 28.10.2013 Сообщений: 9,554 Записей в блоге: 1 |
||||
|
22.10.2018, 00:17 |
4 |
|||
|
Наберите в консоли cmd команду:
Примерный вывод, если библиотека установлена: Код Name: opencv-python Version: 3.4.3.18 Summary: Wrapper package for OpenCV python bindings. Home-page: https://github.com/skvark/opencv-python Author: None Author-email: None License: MIT Location: d:installpython37-32libsite-packages Requires: numpy Required-by: Если нет — очевидно, что вы неверно(не в тот python — если их несколько, то легко ошибиться) установили. Код py -3.7 -m pip модуль чтобы работал pip из той установки python, которая требуется. Код D:INSTALLPython37-32>py -3.7 Python 3.7.0b3 (v3.7.0b3:4e7efa9c6f, Mar 29 2018, 17:46:48) [MSC v.1913 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import cv2 >>> cv2.__version__ '3.4.3' >>> P.S. Хотя, может быть у вас opencv_ffmpeg343.dll не установилась?
0 |
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
23.10.2018, 09:01 [ТС] |
5 |
|
Добрый день. Судя по выданному листингу, библиотека встала как надо, все совпадает строчка в строчку. Что делать если да? а библиотека не импортируется Миниатюры
0 |
|
1288 / 905 / 479 Регистрация: 05.12.2013 Сообщений: 3,036 |
|
|
23.10.2018, 09:40 |
6 |
|
Наберите в командной строке import cv2
0 |
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
23.10.2018, 12:52 [ТС] |
7 |
|
py -3.7 — такой команды не существует Миниатюры
0 |
|
1288 / 905 / 479 Регистрация: 05.12.2013 Сообщений: 3,036 |
|
|
23.10.2018, 13:20 |
8 |
|
тогда так python и затем import cv2
0 |
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
23.10.2018, 18:58 [ТС] |
9 |
|
Такая же ошибка. Миниатюры
0 |
|
5403 / 3827 / 1214 Регистрация: 28.10.2013 Сообщений: 9,554 Записей в блоге: 1 |
|
|
23.10.2018, 19:13 |
10 |
|
Проверьте наличие opencv_ffmpeg343.dll в директории libsite-packagescv2
0 |
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
23.10.2018, 19:17 [ТС] |
11 |
|
библиотека на месте Миниатюры
0 |
|
5403 / 3827 / 1214 Регистрация: 28.10.2013 Сообщений: 9,554 Записей в блоге: 1 |
|
|
23.10.2018, 19:24 |
12 |
|
Ну тут сказать нечего — не иначе как барабашка виноват 🙂
0 |
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
23.10.2018, 19:31 [ТС] |
13 |
|
Да пробовал уже переустанавливать, и 64-битный ставил, и версию ниже, на 8 или 10 винде ребята проверяли все нормально ставится, но из-за этого не хочется ломать нормально работающую систему к которой уже привык. Может в реестре установщик где что какие пути прописывает…
0 |
|
5403 / 3827 / 1214 Регистрация: 28.10.2013 Сообщений: 9,554 Записей в блоге: 1 |
|
|
24.10.2018, 15:41 |
14 |
|
Может в реестре установщик где что какие пути прописывает. pip не делает в реестре никаких записей. По сути whl архив, который качает pip, это просто zip файл — можно все распаковать и установить вручную.
0 |
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
24.10.2018, 18:45 [ТС] |
15 |
|
Ставил то же самое на 7 компов, там тоже винда7 и тот же баг, проблема может быть и в винде, но ошибка связана (DLL load failed: Не найден указанный модуль. ) с загрузкой dll -ки. В ошибке ссылка на 3 строку файла __init__.py из директории ..cv2 from .cv2 import * если открыто это файл и исполнить вылазит ошибка: Неужели винда 7 состарилась и opencv в принципе там терь не работает. Но ведь на одному ноуте работает, там раньше был питон2.7, я его деинсталлировал и поставил то же 3.7. все так же. Вопрос что не так?
0 |
|
5403 / 3827 / 1214 Регистрация: 28.10.2013 Сообщений: 9,554 Записей в блоге: 1 |
|
|
24.10.2018, 19:46 |
16 |
|
Неужели винда 7 состарилась и opencv в принципе там терь не работает Я вам показывал пример своей установки именно на win 7 (но, правда, x32 разрядности).
если открыто это файл и исполнить вылазит ошибка: Не надо это делать. Ошибка No module named ‘__main__ обычная и говорит, о том что человек ее вызвавший не разбирается в системе импорта python.
0 |
|
0 / 0 / 0 Регистрация: 20.10.2018 Сообщений: 10 |
|
|
09.12.2018, 19:09 [ТС] |
17 |
|
Всем привет! Я все таки решил для себя проблему с ошибкой dll в винде 7. Может кому пригодится. Пока только с версией python 2.7.x Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32 Не знаю почему работает. С 3 версией питона разбираюсь. Всем кто помогал спасибо. И я действительно не разбираюсь в системе импорта питон. p.s. Винда 64х, установлены все обновления и библиотеки vc_redist.x64.exe и vc_redist.x86.exe
0 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
09.12.2018, 19:09 |
|
17 |
In this post, We will see how to resolve ModuleNotFoundError No module named 'cv2' in Python.
Table of Contents
- Reason for No module named ‘cv2’
- Resolution for No module named ‘cv2’
- Windows user
- Linux user
- Add site-packages to PYTHONPATH
Reason for No module named ‘cv2’
Let’s first reproduce this error, and then we will see how to resolve ModuleNotFoundError No module named 'cv2'.
We will run cv2 imread example over here.
|
# import computer vision library(cv2) in this code import cv2 # main code if __name__ == «__main__» : # mentioning absolute path of the image img_path = «C:\Users\user\Desktop\flower.jpg» # using imread() method of cv2 image = cv2.imread(img_path) # show the image on the newly created image window cv2.imshow(‘image window’,image) |
When you run above program, you might get below output:
|
————————————————————————— ModuleNotFoundError Traceback (most recent call last) <ipython—input—1—aa8cedc4ccbe> in <module> 1 # import computer vision library(cv2) in this code —-> 2 import cv2 3 4 # main code 5 if __name__ == «__main__» : ModuleNotFoundError: No module named ‘cv2’ |
You will get this error when cv2 module is not properly installed on your machine.
Resolution for No module named ‘cv2’
Let’s see how we can solve this error.
Windows user
If you are windows user, then follow the below steps:
- Open command prompt
- Run following command:
$ python -m pip install –upgrade pip
- Install opencv using following command:
$ pip install opencv-python
In case you are using Anaconda, then follow below steps.
- Open command prompt
- Update conda navigator with following command:
$ conda update anaconda-navigator
$ conda update navigator-updater - Install opencv using following command:
$ conda install -c conda-forge opencv
or
$ conda install -c https://conda.binstar.org/menpo opencv
Linux user
If you are linux user, then follow the below steps:
- Open terminal
- Run following command:
$ sudo pip3 install opencv-python
or
$ sudo apt install python-opencv
Add site-packages to PYTHONPATH
It might be possible that PYTHONPATH does not have site-packages.
- Open ~/.bashrc
- Add following line:
$ export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH
That’s all about ModuleNotFoundError: No module named ‘cv2’ in Python.
