Import cv2 python ошибка

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.

Время на прочтение
2 мин

Количество просмотров 7.4K

В заголовке известная ошибка 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 по‑обстоятельствам.

Hello stackoverflow community :)
I need some help. I’ve written a simple program from the python website and when I run the program, it says :

ImportError: No module named cv2

import cv2
import numpy as np

#read image into matrix.
m =  cv2.imread("python.png")

#get image properties.
w,h,bpp = np.shape(m)

#print image properties.
print "width: " + str(w)
print "height: " + str(h)
print "bpp: " + str(bpp)

I already tried to install openCV but it seems that I didn’t install properly, this is the tutorial I followed to install it. When I tried to installed the dependencies it said:

Installing OpenCV 2.4.9 in Ubuntu 14.04 LTS

E:Package 'libtbb-dev' has no installation candidate
E: unable to locate package libfaac-dev

I ignored that package and procced to the next step (download the openCV 2.4.9).

When I tried to generated the Makefile using cmake I got the next warnings

Could not find a package configuration file provided by  "Qt5Core" with any of the following names:
    Qt5CoreConfig.cmake
    qt5core-config.cmake

    Add the installation prefix of "Qt5Core" to CMAKE_PREFIX_PATH or set "Qt5Core_DIR" to a directory containing one of the above files. If "Qt5Core" provides a separate development package or SDK, be sure it has been installed.
    Call Stack (most recent call first)
    CMakeLists.txt:466 (include)

The same happens with the next packages:

  • Qt5GuiConfig.cmake
  • qt5gui-config.cmake
  • Qt5WidgetsConfig.cmake
  • qt5widgets-config.cmake
  • Qt5TestConfig.cmake
  • qt5test-config.cmake
  • Qt5ConcurrentConfig.cmake
  • qt5concurrent-config.cmake

and at the end this Error shows up:

CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:97 (MESSAGE):
  Could NOT find Qt4 (missing: QT_QMAKE_EXECUTABLE QT_MOC_EXECUTABLE
  QT_RCC_EXECUTABLE QT_INCLUDE_DIR QT_LIBRARY_DIR QT_QTCORE_INCLUDE_DIR
  QT_QTCORE_LIBRARY QT_QTGUI_INCLUDE_DIR QT_QTGUI_LIBRARY
  QT_QTTEST_INCLUDE_DIR QT_QTTEST_LIBRARY QT_UIC_EXECUTABLE)
Call Stack (most recent call first):
  /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:288 (_FPHSA_FAILURE_MESSAGE)
  /usr/share/cmake-2.8/Modules/FindQt4.cmake:1200 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  cmake/OpenCVFindLibsGUI.cmake:34 (find_package)
  CMakeLists.txt:466 (include)

I’ve searched all the file system but couldn’t find the above files. I also read that If anything goes wrong, I have to go back, correct the errors by maybe installing extra packages and then run cmake again. BUT, how do I install those extra packages?

I ran the next commands and all the libraries are installed and updated to the newest version.

sudo apt-get update
sudo apt-get updgrade
sudo apt-get install libopencv-dev
sudo apt-get install python-opencv

Can someone please help me get a usable install of OpenCV as simply as possible. I would really appreciate it. I’m stuck in this project.

PS. I also couldn’t find a cv2.so file I searched everywhere… I used the next command:

sudo find/name "cv2*"

Thank you.

  • 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).

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

  1. Download the latest static version of ffmpeg from the download page depending on your os.
  2. Extract the installed zip file using 7-zip. The folder will be named something like «ffmpeg-20130731-git-69fe25c-win32-static».
  3. Create a new folder named ffmpeg in your C: and copy the contents of the extracted folder into this new one.
  4. 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.
  5. Click the Environmental Variables button in the System Properties window. It will be located at the bottom of the window.
  6. 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.
  7. 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 a libstdc++ -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:

  1. Download the self-extracting executable from the OpenCV website.
  2. Run the Executable which will in turn extract the executable.
  3. Create a folder in C: called opencv
  4. Copy the contents of the extracted files into opencv
  5. 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!

Возможно, вам также будет интересно:

  • Immergas e01 ошибка на газовом котле
  • Impactor cydia ошибка 173
  • Immediate stop ошибка рено мидлум
  • Impact майнкрафт при загрузке файлов произошла ошибка
  • Immediate stop ошибка рено магнум

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии