Fenghe's Blog

Install opencv-python inside Python Virtual Environment

As I mentioned in this article, matplotlib is not supported with miniconda. To resolve the issue, I read through Python 3.7 documentation and realized using Virtual Environment would be a good way to handle the conflicts.

The following tutorial is tested on macOS 10.14 Mojave.

To create a python Virtual Environment, use the following command, where env_name is the name of the environment that you want to create. The env_name folder is created if there’s no such env_name called that before.

$ python3 -m venv env_name

Activate the virtual environment by running

$ source activate

Now you can check your python version by running

$ python --version

Now your can install packages only applied for the new environment, i.e., the directory just created. Following are a few examples:

$ pip install opencv-python
$ pip install matplotlib
$ pip install numpy

After the installation, it should be safe for you to import cv2 and process your images with opencv.

$ python
>>> import cv2
# To check your cv2 version
>>> cv2.__version__
'4.0.0'

Basic Operations

To create a .py file

$ touch example.py

To edit a file with idle or sublime(To open a file with sublime in terminal requires extra configuration)

$ idle3 example.py
$ sublime example.py

To execute you code:

$ pythonw example.py

Pycharm is more friendly

If you are a Jetbrains fan like me, you may want to use Pycharm. Actually, it is more friendly, the only thing you need to do is to open the working directory in the IDE, and then run

$ source activate

inside the terminal below the editor directly.

References:

  1. https://docs.python.org/3/tutorial/venv.html?highlight=environment
  2. Install Tensorflow and OpenCV on Your Raspberry Pi with Python 3 by me
  3. https://www.pyimagesearch.com/2015/08/10/checking-your-opencv-version-using-python/

Leave a Reply

Your email address will not be published. Required fields are marked *