Opencv как установить anaconda jupiter
Перейти к содержимому

Opencv как установить anaconda jupiter

  • автор:

Import OpenCV on jupyter notebook

I tried installing OpenCV on Windows 10 using pip. I used this command- pip install opencv-contrib-python After that when I tried importing cv2 on command prompt, it was successfully imported- Importing cv2 successfully through command prompt When I tried importing it on jupyter notebook, this error popped up- Error when importing cv2 on jupyter notebook This is the python version I’m using- Python version that I am using This is pip list and as I’ve highlighted, opencv-contrib-python version 3.4.3.18 is installed- pip list Then why can’t I import OpenCV on jupyter notebook, like tensorflow or numpy are also in pip list and I’m able to import them both through command prompt and also on jupyter notebook. Please help. Thanks a lot.

asked Oct 16, 2018 at 10:06
guptasaanika guptasaanika
137 1 1 gold badge 3 3 silver badges 10 10 bronze badges

Please show the output of import sys; print(sys.prefix) for both the cmdline python and your notebook python.

Oct 16, 2018 at 10:09
Are you sure you installed opencv in the same virtual environment you are using with Jupyer?
Oct 16, 2018 at 10:11

Hello Deets, thanks for replying. On cmdline, output is- C:\ProgramData\Anaconda3 On jupyter notebook, output is- C:\Users\HP\Anaconda3

Oct 16, 2018 at 10:53

Hello Ed. Thanks for replying. Earlier when I installed tensorflow, I used- pip install tensorflow and after that I could import tensorflow both on command prompt and on Jupyter notebook. Then why for OpenCV, I’m facing this problem?

Oct 16, 2018 at 10:59

Usually this error pops up when you launch you jupyter notebook from a different conda environment and your command line is in different conda environment. for ex — if you installed opencv in a conda environement called myenv , Ensure that you do (home) C:// conda activate myenv and then use (myenv) C:// jupyter notebook . (notice that environment is myenv ) In your case it seems from the screenshot that you installed cv2 in base, did you also start jupyter notebook from base ?

Как установить библиотеку OpenCV в Python – 2 способа

OpenCV – это библиотека Python с открытым исходным кодом, которая используется для понимания содержимого цифрового изображения. CV – это аббревиатура компьютерного зрения. Она извлекает описание из изображения в реальном времени или цифрового изображения, которое может быть объектом, текстовым описанием и т. д.

Мы можем выполнять множество задач с помощью библиотеки OpenCV, таких как обнаружение лиц, распознавание лиц, обнаружение blob-объектов, выделение границ, фильтр изображений, сопоставление шаблонов и т.д. Разберем как установить библиотеку OpenCV в нашей среде Python.

Установка OpenCV

OpenCV устанавливается следующими способами:

  • с помощью команды pip;
  • используя Anaconda.

Использование команды pip

Откройте командную строку и введите следующую команду.

pip install opencv-contrib-python --upgrade

Или можно установить без дополнительного модуля с помощью следующей команды:

pip install opencv-python

Установка OpenCV в Python

Теперь мы проверим правильность установки OpenCV. Импортируйте модуль cv2 и распечатайте его версию.

Импорт модуля cv2

Если он правильно установлен, то он покажет свою версию.

Использование Anaconda

Anaconda – это программный пакет Python. Anaconda с Jupyter – лучший способ работать с OpenCV. Во-первых, нам нужно установить установщик графики Anaconda с официального сайта.

Установщик Anaconda

Теперь выберите подходящий установщик для вашей версии Python.

Соответствующий версии Python установщик

После завершения загрузки откройте командную строку Anaconda и введите следующую команду.

conda install -c conda-forge opencv

Завершение загрузки

Затем нажмите кнопку ввода, загрузится всю номинальная конфигурация OpenCV.

Загрузка OpenCV

Теперь вы готовы работать с OpenCV.

Установка OpenCV-Python на виртуальной среде для суперчайников

Здесь вы найдете пошаговый пример установки библиотеки OpenCV на Python.

  • Установка Python
  • Установка виртуальной среды
  • Установка OpenCV + jupiterlab, numpy, matplotlib
  • Тестирование

Все тестировала на планшете Microsoft Surface, Windows 10 Pro, c 64-битной операционной системой.

Предположим, что на вашем устройстве ничего не установлено заранее.

  1. Сначала установим Python.
    Скачиваем нужную версию и запускаем .exe файл. Не забываем установить галочку add path. Я установила Python 3.7.3 от 25 марта 2019 г., потому что новая на данный момент версия Python 3.7.4 от 8го июля 2019 г. работала некорректно, а именно в терминале некоторые команды зависали. Открываем командную строку.
  2. Устанавливаем virtualenv.
    Виртуальная среда нам нужна для того, чтобы для каждого отдельного проекта была своя «комната» со своими версиями установленных библиотек, которые не будут зависеть от других проектов и путаться между собой.
    Пакеты будем устанавливать с помощью pip. Он в последнее время сразу идет с Python, но обычно требуется его обновить командой:
    python -m pip install —upgrade pip
    Обновили pip, теперь установим виртуальную среду:
    pip install virtualenv
    Командой cd перейдите в папку, в которой хотите создать среду и введите команду:
    mkdir opencvtutorial_env — так мы создали среду с названием opencvtutorial_env.
    Далее вводим команду virtualenv opencvtutorial_env и для активации перейдите в папку среды и далее с помощью Tab до activate.
    .\opencvtutorial_env\Scripts\activate
  3. Установим библиотеки OpenCV-Python, Numpy и Matplotlib, которые понадобятся для тестирования функций opencv.
    Самый легкий и быстрый вариант установки у меня получился с неофициальной версии. Устанавливаем его командой:
    pip install opencv-python
    Вместе с opencv-python в подарок с этим пакетом идет numpy. Дополнительно установим matplotlib: pip install matplotlib .
  4. Установим pip install jupyterlab и запустим его командой jupyter notebook .
    Теперь осталось проверить все ли у нас работает. В открывшемся окне создаем новый Python 3 файл, и запускаем команду:
    import cv2 as cv
    print( cv.__version__ )
    Если выходит версия opencv, то поздравляю, можно тестировать туториалы c официального сайта. Мои примеры работ по туториалам можно найти здесь.
  • opencv-python
  • computer vision
  • компьютерное зрение
  • python3
  • virtualenv

Tutorial: CUDA, cuDNN, Anaconda, Jupyter, PyTorch Installation in Windows 10

CUDA, cuDNN, Anaconda, Jupyter, PyTorch in Windows 10

4 min read

Sep 4, 2021

In this story, the procedures of CUDA, cuDNN, Anaconda, Jupyter, PyTorch Installation in Windows 10, is described. Indeed, the procedures are straightforward. No tricks involved. Let’s get started! (Sik-Ho Tsang @ Medium)

0. GPU & NVIDIA Driver Installation

  • Before all, the computer should‘ve have got a GPU/Display card.
  • Also, normally, NVIDIA driver is installed by NVIDIA experience console.

1. CUDA Installation

1.1. Download

  • First, go to https://developer.nvidia.com/cuda-downloads
  • Select the following settings to download the CUDA:

1.2. Install

  • After downloading, click the exe file to install CUDA:
  • Mine is CUDA version 11.4.

1.3. Check

  • You may check the CUDA version that just installed.
  • Open Windows PowerShell and type:
nvcc -V
  • which is the same command as in Ubuntu. CUDA version 11.4 is shown.

2. cuDNN Installation

2.1. Download

  • Go to https://developer.nvidia.com/cudnn.
  • You need to have an account in order to download cuDNN. If no, register one, and go to the above link again.
  • Finally, you got something like this:
  • Click to download the zip file. (Mine is v8.2.4.)

2.2. Install

  • Unzip it.
  • My CUDA installed path is:
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vx.x\
  • where vx.x is v11.4.
  • Go to this path. You should see there are 3 directories called “bin”, “include”, and “lib”, which are the same as the unzipped one.
  • Copy the unzipped folders to this path. Then cuDNN is installed.

2.3. Setting Environmental Variables (Optional in my case)

  • In the guideline of NVIDIA, it needs to set the environmental variables, but I do not need to, these are already done. Maybe the guideline is not up-to-date.
  • Below are the steps from the guideline of NVIDIA:
  • Open a command prompt from the Start menu.
    Type Run and hit Enter.
    Issue the control sysdm.cpl command.
    Select the Advanced tab at the top of the window.
    Click Environment Variables at the bottom of the window.
    Ensure the following values are set:
    Variable Name: CUDA_PATH
    Variable Value: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vx.x

2.4. Use

  • Open the Visual Studio project and right-click on the project name.
  • Click Linker > Input > Additional Dependencies. Add cudnn.lib and click OK.

3. Anaconda & Jupyter Installation

3.1. Download & Install

  • Go to https://www.anaconda.com/products/individual
  • Download the Windows version and install should be okay.

3.2. Create & Activate Environment

  • Open “Ananconda Powershell Prompt
  • Update the conda
conda update conda
  • Create a new environment. (I normally like to create a new one for a new task.)
  • conda env list can check the list of environments.
conda create — name pytorch_trial_0

conda env list
  • Activate it.
conda activate pytorch_trial_0

3.3. Jupyter Notebook

  • First, Install it:
conda install jupyter
  • jupyter notebook list can check the list of notebook:
jupyter notebook list
  • Create a notebook for development:
jupyter notebook
  • My Google Chrome automatically open the jupyter notebook page for me.
  • If not, just copy the link at the bottom of the PowerShell console.

4. PyTorch Installation

4.1. Download & Install

  • Go to https://pytorch.org/:
  • Copy the above command to Ananconda Powershell Prompt and run it, to download & install PyTorch GPU version.
  • (If you only got CPU, choose CPU version at the Computer Platform.)
  • (If you have launched the notebook, you may need to open a new PowerShell to activate the same environment again.)
  • I just directly copy the above command to install:
conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c conda-forge

4.2. Use

  • To test, you may try some Python command to test:
import torch
import torchvision
torch.cuda.is_available()
  • The library should be properly imported.
  • CUDA should also be checked as available using torch function.

I write this story so that I can repeat it next time easily if needed. 🙂

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *