Pip3 install python opencv error

«pip install opencv-python» fails to find opencv-python #102 Comments Expected behaviour «pip install opencv-python» should install opencv-python, as it has on my Windows machine. Actual behaviour I am sshing into a CentOS machine and «pip install opencv-python» does not find it, instead I get the message: Collecting opencv-python Could not find a version that […]

Содержание

  1. «pip install opencv-python» fails to find opencv-python #102
  2. Comments
  3. Expected behaviour
  4. Actual behaviour
  5. Steps to reproduce
  6. Footer
  7. ERROR: Failed building wheel for opencv-python #18359
  8. Comments
  9. Problem with the CMake installation, aborting build. CMake executable is cmake
  10. installation is stuck at building wheel #391
  11. Comments
  12. Expected behaviour
  13. Actual behaviour
  14. Steps to reproduce
  15. Problem with the CMake installation, aborting build. CMake executable is cmake
  16. Pip install opencv python error
  17. «ModuleNotFoundError: No module named ‘cv2’ in Python» #
  18. Conclusion #

«pip install opencv-python» fails to find opencv-python #102

Expected behaviour

«pip install opencv-python» should install opencv-python, as it has on my Windows machine.

Actual behaviour

I am sshing into a CentOS machine and «pip install opencv-python» does not find it, instead I get the message:
Collecting opencv-python Could not find a version that satisfies the requirement opencv-python (from versions: ) No matching distribution found for opencv-python

My pip and wheel installations are all up to date, which seemed to be the issue for other people with the same problem. The manylinux wheels do not work for me either, I get a message back saying:

opencv_python-3.4.1.15-cp36-cp36m-manylinux1_x86_64.whl is not a supported wheel on this platform.

I have used manylinux wheels for other things in the past and they have worked, so I am fairly confident that I should be able to use it. Is opencv known to not be compatible with CentOS, or am I missing something?

Steps to reproduce

«pip install opencv-python» on a CentOS machine.

  • operating system:
    CentOS Linux release 7.4.1708
  • architecture: 64 bit
    Python Version: 3.6.3

The text was updated successfully, but these errors were encountered:

Can you install any other wheels like numpy? To my knowledge, pip checks only the wheel filename tags and if they not match your system and Python it will throw that error. This seems like the same issue as in here: #83 (comment) (have a look at the latest comments).

[(‘cp36’, ‘cp36m’, ‘linux_x86_64’), (‘cp36’, ‘abi3’, ‘linux_x86_64’), (‘cp36’, ‘none’, ‘linux_x86_64’), (‘cp35’, ‘abi3’, ‘linux_x86_64’), (‘cp34’, ‘abi3’, ‘linux_x86_64’), (‘cp33’, ‘abi3’, ‘linux_x86_64’), (‘cp32’, ‘abi3’, ‘linux_x86_64’), (‘py3’, ‘none’, ‘linux_x86_64’), (‘cp36’, ‘none’, ‘any’), (‘cp3’, ‘none’, ‘any’), (‘py36’, ‘none’, ‘any’), (‘py3’, ‘none’, ‘any’), (‘py35’, ‘none’, ‘any’), (‘py34’, ‘none’, ‘any’), (‘py33’, ‘none’, ‘any’), (‘py32’, ‘none’, ‘any’), (‘py31’, ‘none’, ‘any’), (‘py30’, ‘none’, ‘any’)] is what I get by checking the supported tags. I thought manylinux would work because I thought I had used them before, but I just checked the PyTorch wheel I had used and it is actually linux_x86_64, so my mistake. I guess CentOS is not compatible with manylinux. If I cannot use the manylinux wheels, and I cannot use pip as it cannot find opencv-python, am I just not able to use opencv-python? I don’t think there was a linux_x86_64 wheel available.

Upon further research it seems like CentOS should be compatible with manylinux as the criteria for making a wheel manylinux compatible seems to be building it on CentOS 5. I found a workaround that I will try, but I am really not sure why manylinux wheels would not build on CentOS 7.

Yes, CentOS is compatible with manylinux wheels. There’s something odd going on with your Python installation. Are you sure you are using correct pip to install the wheels? On some systems Python 3 pip is called pip3 . Also, if you try to install manually for example this numpy wheel https://files.pythonhosted.org/packages/68/1e/116ad560de97694e2d0c1843a7a0075cc9f49e922454d32f49a80eb6f1f2/numpy-1.14.5-cp36-cp36m-manylinux1_x86_64.whl, does it have the same issue?

I am sure I am using the correct pip, the pip I am using corresponds to the virtualenv I am using. I tried pip3 and it gives me the same error : pip3 install https://files.pythonhosted.org/packages/7c/78/bc95e29057e80d1da71912426113e85f20752b1031193f51750322354937/opencv_python-3.4.1.15-cp36-cp36m-manylinux1_x86_64.whl opencv_python-3.4.1.15-cp36-cp36m-manylinux1_x86_64.whl is not a supported wheel on this platform. .
Same for the numpy wheel, I get the same issue:
pip install https://files.pythonhosted.org/packages/68/1e/116ad560de97694e2d0c1843a7a0075cc9f49e922454d32f49a80eb6f1f2/numpy-1.14.5-cp36-cp36m-manylinux1_x86_64.whl numpy-1.14.5-cp36-cp36m-manylinux1_x86_64.whl is not a supported wheel on this platform. .

The issue seems to be the same with all wheel packages which means that your Python installation is not compatible with manylinux1 wheels. I’m afraid this issue is not really related to opencv-python .

Fair enough. Thank you for your time, I will try to investigate as to why my python distribution is not compatible with manylinux wheels.

What about cygwin installations of python (2.7 or 3.6)? It appears as if there is no way to install opencv-python?

%pip2.7 install opencv-python
Collecting opencv-python
Could not find a version that satisfies the requirement opencv-python (from versions: )
No matching distribution found for opencv-python

%pip3.6 install opencv-python
Collecting opencv-python
Could not find a version that satisfies the requirement opencv-python (from versions: )
No matching distribution found for opencv-python

@udbraumann I doubt the opencv-python wheels are compatible with Cygwin, which probably isn’t compatible with the «manylinux» spec, and also isn’t compatible with wheels built for regular Windows Python. I suspect you’ll have to build OpenCV manually for Cygwin.

@waveform80 I need to say that OpenCV 3.4.1 itself is being shipped with Cygwin. opencv-python however seems to be not just an interface to OpenCV, but rather some combination of installation and interface. Could you please give some hints how to build opencv-python «on foot»?

Bear in mind that this opencv-python repository has little to do with the OpenCV project itself; it exists to build and provide the pre-compiled wheels of OpenCV (in a variety of configurations) to the PyPI archive for use by compatible platforms (my assumption above is that Cygwin is not a compatible platform).

You’re probably best off looking at instructions for building the OpenCV library itself (which should include the Python 2/3 bindings), bearing in mind that Cygwin is likely to be closer to a Linux build than a Windows build. Hence the OpenCV build instructions for Linux may help (although they assume an Ubuntu style package manager; you’ll need to translate those bits as necessary for Cygwin). Alternatively there appear to be some Cygwin specific instructions from a quick Google, though they don’t appear to include the necessary options to build the Python bindings (might be worth combining those instructions with some bits from the official guide).

If you run into issues building OpenCV itself, these are best directed to the OpenCV repository itself rather than here.

What about cygwin installations of python (2.7 or 3.6)? It appears as if there is no way to install opencv-python?

%pip2.7 install opencv-python
Collecting opencv-python
Could not find a version that satisfies the requirement opencv-python (from versions: )
No matching distribution found for opencv-python

%pip3.6 install opencv-python
Collecting opencv-python
Could not find a version that satisfies the requirement opencv-python (from versions: )
No matching distribution found for opencv-python

did you solve the problem?

unfortunately not, but admittedly I did not try too long, as I felt I am the only one missing opencv-python for python.

unfortunately not, but admittedly I did not try too long, as I felt I am the only one missing opencv-python for python.

You’re not alone.
I’m trying to start AnimeGAN and I’m struggling with the opencv python issue.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

ERROR: Failed building wheel for opencv-python #18359

hi i am running on python3.7 and pip 20.2.3 on ubuntu 18.04, arm64.
when i am trying to install opencv using pip3 install opencv-python
i am getting following error.

ERROR: Command errored out with exit status 1:
command: /usr/bin/python3 /home/smartagri/.local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmpfga9p4k1
cwd: /tmp/pip-install-fmfauafs/opencv-python
Complete output (9 lines):
File «/tmp/pip-build-env-jorjrbsz/overlay/lib/python3.7/site-packages/skbuild/setuptools_wrap.py», line 560, in setup
cmkr = cmaker.CMaker(cmake_executable)
File «/tmp/pip-build-env-jorjrbsz/overlay/lib/python3.7/site-packages/skbuild/cmaker.py», line 95, in __init__
self.cmake_version = get_cmake_version(self.cmake_executable)
File «/tmp/pip-build-env-jorjrbsz/overlay/lib/python3.7/site-packages/skbuild/cmaker.py», line 82, in get_cmake_version
Problem with the CMake installation, aborting build. CMake executable is %s» % cmake_executable) Traceback (most recent call last):

Problem with the CMake installation, aborting build. CMake executable is cmake

ERROR: Failed building wheel for opencv-python
Failed to build opencv-python
ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly

i checked my setup tool wheels using pip3 install —upgrade pip setuptools wheel
but it is already up-to-date

The text was updated successfully, but these errors were encountered:

Источник

installation is stuck at building wheel #391

Expected behaviour

I expected to module to install very fast.

Actual behaviour

Building wheel for opencv-python (PEP 517) takes forever to run.

Steps to reproduce

  • OS — ubuntu 18.04 LTS
  • architecture — x86
  • opencv-python version — 4.4.0.44
Issue submission checklist
  • This is not a generic OpenCV usage question (looking for help for coding, other usage questions, homework etc.)
  • I have read the README of this repository and understand that this repository provides only an automated build toolchain for OpenCV Python packages (there is no actual OpenCV code here)
  • The issue is related to the build scripts in this repository, to the pre-built binaries or is a feature request (such as «please enable this additional dependency»)
  • I’m using the latest version of opencv-python

The text was updated successfully, but these errors were encountered:

@Abhranta ok so coincidently I too faced the similar issue just now 👇

I am a Windows 64 — bit user

  • When I checked on pypi.org, I came to know that, people who all are installing openCV they are installing the latest version that is released just 3 hours back 👇

TEMPORARY SOLUTION ✅

So for now you can download the previous version (i.e opencv-python 4.4.0.42) and it will work fine and your job gets done.

Hope this helps 😊
Do drop a like if your issue gets solved by this.
Thank you 🙏

hi @TheDudeThatCode ,
i tried installing the older version as you said but i am getting the same error still.
i am running on ubuntu 18.04, arm64.

python3.7 -m pip install opencv-python==4.4.0.42 Defaulting to user installation because normal site-packages is not writeable Collecting opencv-python==4.4.0.42 Using cached opencv-python-4.4.0.42.tar.gz (88.9 MB) Installing build dependencies . done Getting requirements to build wheel . done Preparing wheel metadata . done Requirement already satisfied: numpy>=1.14.5 in ./.local/lib/python3.7/site-packages (from opencv-python==4.4.0.42) (1.19.2) Building wheels for collected packages: opencv-python Building wheel for opencv-python (PEP 517) . error ERROR: Command errored out with exit status 1: command: /usr/bin/python3.7 /home/farbot/.local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmp2mtq9r3_ cwd: /tmp/pip-install-88qrptpk/opencv-python Complete output (9 lines): File «/tmp/pip-build-env-xque07ot/overlay/lib/python3.7/site-packages/skbuild/setuptools_wrap.py», line 560, in setup cmkr = cmaker.CMaker(cmake_executable) File «/tmp/pip-build-env-xque07ot/overlay/lib/python3.7/site-packages/skbuild/cmaker.py», line 95, in __init__ self.cmake_version = get_cmake_version(self.cmake_executable) File «/tmp/pip-build-env-xque07ot/overlay/lib/python3.7/site-packages/skbuild/cmaker.py», line 82, in get_cmake_version «Problem with the CMake installation, aborting build. CMake executable is %s» % cmake_executable)
Traceback (most recent call last):

Problem with the CMake installation, aborting build. CMake executable is cmake

ERROR: Failed building wheel for opencv-python Failed to build opencv-python ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly

You can’t install the packages because the builds were (and still are) in progress. Please pin your dependencies as @TheDudeThatCode wrote above. When builds are finished, you can safely upgrade (the new release contains only bug fixes and drops Python 3.5 support). The releases are usually ready when there are release notes at https://github.com/skvark/opencv-python/releases.

@siddharthcb This project does not support ARM platforms. Therefore your installation will always fail. Source build fails because cmake has issues with ARM platforms also.

Источник

Pip install opencv python error

Reading time В· 4 min

«ModuleNotFoundError: No module named ‘cv2’ in Python» #

The Python «ModuleNotFoundError: No module named ‘cv2′» occurs when we forget to install the opencv-python module before importing it or install it in an incorrect environment. To solve the error, install the module by running the pip install opencv-python command.

Open your terminal in your project’s root directory and install the opencv-python module.

After you install the opencv-python package, try importing it like:

The Python error «ModuleNotFoundError: No module named ‘cv2′» occurs for multiple reasons:

  1. Not having the opencv-python package installed by running pip install opencv-python .
  2. Installing the package in a different Python version than the one you’re using.
  3. Installing the package globally and not in your virtual environment.
  4. Your IDE running an incorrect version of Python.
  5. Naming your module cv2.py which would shadow the official module.
  6. Declaring a variable named cv2 which would shadow the imported variable.

If the error persists, get your Python version and make sure you are installing the package using the correct Python version.

For example, my Python version is 3.10.4 , so I would install the opencv-python package with pip3.10 install opencv-python .

Notice that the version number corresponds to the version of pip I’m using.

If the PATH for pip is not set up on your machine, replace pip with python3 -m pip :

If the «No module named ‘cv2′» error persists, try restarting your IDE and development server/script.

You can check if you have the opencv-python package installed by running the pip show opencv-python command.

The pip show opencv-python command will either state that the package is not installed or show a bunch of information about the package, including the location where the package is installed.

If the package is not installed, make sure your IDE is using the correct version of Python.

For example, In VSCode, you can press CTRL + Shift + P or ( ⌘ + Shift + P on Mac) to open the command palette.

Then type «Python select interpreter» in the field.

Then select the correct python version from the dropdown menu.

If you are using a virtual environment, make sure you are installing opencv-python in your virtual environment and not globally.

You can try creating a virtual environment if you don’t already have one.

If the python3 -m venv venv command doesn’t work, try the following 2 commands:

  • python -m venv venv
  • py -m venv venv

Your virtual environment will use the version of Python that was used to create it.

You also shouldn’t be declaring a variable named opencv-python as that would also shadow the original module.

If the error is not resolved, try to uninstall the opencv-python package and then install it.

Try restarting your IDE and development server/script.

You can also try to upgrade the version of the opencv-python package.

This one is for using virtual environments (VENV) on Windows :

This one is for using virtual environments (VENV) on MacOS and Linux :

Conclusion #

The Python «ModuleNotFoundError: No module named ‘cv2′» occurs when we forget to install the opencv-python module before importing it or install it in an incorrect environment. To solve the error, install the module by running the pip install opencv-python command.

Источник

Пытаюсь установить opencv на Ubuntu 18.04
$ pip install opencv-python
Выдает:

Collecting opencv-python
  Using cached https://files.pythonhosted.org/packages/77/f5/49f034f8d109efcf9b7e98fbc051878b83b2f02a1c73f92bbd37f317288e/opencv-python-4.4.0.42.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-2n2lpc17/opencv-python/setup.py", line 9, in <module>
        import skbuild
    ModuleNotFoundError: No module named 'skbuild'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-2n2lpc17/opencv-python/

Понимаю, что проблема в отсутствии модуля skbuild, загружаю его:

много теста

$ pip install skbuild
Collecting skbuild
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python3/dist-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python3/dist-packages/pip/index.py", line 795, in get_page
    resp.raise_for_status()
  File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/models.py", line 935, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/skbuild/

Оказывается теперь skbuild’a нет. И что мне спрашивается делать? может кто сталкивался с таким?
Примечание:

$ python --version
Python 3.6.9
$ pip -V
pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6)

gordon77

Posts: 7066
Joined: Sun Aug 05, 2012 3:12 pm

sudo pip3 install opencv-python fails…

using latest Raspbian…

Code: Select all

sudo  pip3 install opencv-python
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting opencv-python


  Could not find a version that satisfies the requirement opencv-python (from versions: )
No matching distribution found for opencv-python

Anyone know /explain why ?





gordon77

Posts: 7066
Joined: Sun Aug 05, 2012 3:12 pm

Re: sudo pip3 install opencv-python fails…

Wed Jun 26, 2019 7:03 am

Thanks, modified my install..

Code: Select all

sudo apt-get install python3-opencv
sudo apt-get install libhdf5-dev
sudo apt-get install libhdf5-serial-dev
sudo apt-get install libatlas-base-dev
sudo apt-get install libjasper-dev 
sudo apt-get install libqtgui4 
sudo apt-get install libqt4-test

opencv now works, but gives a few anomalies on the image, lines, which I need to investigate.

but works OK when using pygame to display, opencv to capture (screen.jpg)

Attachments
screen.jpg
screen.jpg (33.92 KiB) Viewed 6592 times
Untitled.jpg
Untitled.jpg (64.36 KiB) Viewed 6598 times


ggNoOpenCV

Posts: 1
Joined: Wed Jun 26, 2019 12:46 pm

Re: sudo pip3 install opencv-python fails…

Wed Jun 26, 2019 12:49 pm

This command is only for version 3.2.0, is there no way to get a higher version on buster currently? Is there any stable os that supports new versions of opencv?


gordon77

Posts: 7066
Joined: Sun Aug 05, 2012 3:12 pm

Re: sudo pip3 install opencv-python fails…

Wed Jun 26, 2019 5:10 pm

ggNoOpenCV wrote: ↑

Wed Jun 26, 2019 12:49 pm


This command is only for version 3.2.0, is there no way to get a higher version on buster currently? Is there any stable os that supports new versions of opencv?

Jessie and pip3 install opencv-python used to install v 3.4.4


tkasidakis

Posts: 2
Joined: Tue Jun 30, 2020 10:40 am

Re: sudo pip3 install opencv-python fails…

Wed Jul 22, 2020 12:34 pm

Hello.

How i can install opencv 3.3 or anothere newer version ?

I have a raspberry pie 4 B 64 bit and ubuntu 18.04 as an OS .

When i am doing pip3 install opencv-contrib-python==3.4.6.27

i am taking this error

Code: Select all

ERROR: Could not find a version that satisfies the requirement opencv-contrib-python==3.4.6.27 (from versions: none)
ERROR: No matching distribution found for opencv-contrib-python==3.4.6.27

Finally i install opencv from github etc.

Is there a way doing this with pip3 ? I am seraching for a version > 3.3 . Is there something for arm architecture at Pypi ?

Thanks in advance for the help


decades

Posts: 6
Joined: Wed Jan 17, 2018 7:30 pm

Re: sudo pip3 install opencv-python fails…

Tue Nov 17, 2020 1:35 pm

You could try another version, like pip3 install opencv-python==3.4.10.37

But for me this also didn’t work. It failed while it was building


Return to “Python”

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
  • 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 opencvpython

Если вы используете LinuxOS, вы можете ввести следующее.

pip install opencvpython

Если он все еще не работает, вы можете использовать следующую команду.

sudo apt install pythonopencv

Если вы используете ОС Windows для установки используйте следующий код.

pip install opencvpython

Следующий шаг — открыть редактор кода, такой как Visual Studio Code, и импортировать модуль cv2 в файл кода Python.

Теперь, если вы запустите файл, вы получите такую ошибку: Модуль Python cv2 не найден.

Ошибка «модуль cv2 не найден» возникла из-за того, что интерпретатор Python каким-то образом не находит путь к модулю opencv-python.

Python cv2 модуль не найден

Устранение ошибки: модуль 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 anacondanavigator  

conda update navigatorupdater

Если ваша Anaconda вообще не содержит OpenCV, вы можете установить ее с помощью следующей команды.

Если вы хотите установить opencv в виртуальной среде, выполните следующую команду в терминале, чтобы получить список виртуальных сред.

Или команда Jupyter Notebook следующая.

Затем обновите Anaconda.

conda update anacondanavigator

conda update navigatorupdater

Установите opencv по выбранному вами пути среды.

conda install c [‘environment path’] opencv

Автор статей и разработчик, делюсь знаниями.

Понравилась статья? Поделить с друзьями:
  • Pip ошибка при установке пакетов
  • Pip update error
  • Pip pyodbc error
  • Pip proxy error
  • Pip numpy install error