Solarian Programmer

My programming ramblings

Install NumPy, SciPy, Matplotlib and OpenCV for Python 3 on Ubuntu 18.04

Posted on April 25, 2018 by Paul

This is a short article about installing NumPy, SciPy, Matplotlib and OpenCV on the latest Ubuntu LTS, which at the time of this writing is 18.04. Ubuntu 18.04 comes with Python 3.6.5.

Let’s start by making sure we have an updated system:

1 sudo apt update
2 sudo apt upgrade

Now, let’s install NumPy, SciPy and Matplotlib:

1 sudo apt install python3-numpy python3-scipy python3-matplotlib

If you need OpenCV, you can install it with:

1 sudo apt install python3-opencv

Many useful Python libraries can be installed from, let’s make sure we have pip on our system:

1 sudo apt install python3-pip

If you need to install a library from, for example the Python Imaging Library Pillow, you can do it with:

1 pip3 install Pillow

We can test ScipPy and Matplotlib, by writing a short test program:

1 import scipy as sp
2 import matplotlib.pylab as plt
4 t = sp.arange(0, 10, 1/100)
5 plt.plot(t, sp.sin(1.7 * 2 * sp.pi * t) + sp.sin(1.9 * 2 * sp.pi * t))

Save the above code as and run it with:

1 python3

You should see something like in the next figure:

Testing SciPy and Matplotlib on Ubuntu Linux

We can write a small test program that will print the OpenCV version, load an image from the disk, convert the image to gray and show the result. Start by downloading the next image:

Over the Clouds test image

Save it as clouds.jpg. In the same folder where you’ve saved the above image, create a new file and write the next code:

 1 import cv2
 3 print("OpenCV version:")
 4 print(cv2.__version__)
 6 img = cv2.imread("clouds.jpg")
 7 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 9 cv2.imshow("Over the Clouds", img)
10 cv2.imshow("Over the Clouds - gray", gray)
12 cv2.waitKey(0)
13 cv2.destroyAllWindows()

Run the code with:

1 python3

(You can close the two windows by pressing ESC!)

You should see something like in the next figure:

Python 3 OpenCV 3 test on Ubuntu Linux - convert image to gray

If you want to learn more about Python and Matplotlib, I recommend reading Python Crash Course by Eric Matthes. The book is intended for beginners, but has a nice Data Visualization intro to Matplotlib chapter:

If you want to learn about OpenCV and Python, I would recommend reading OpenCV with Python Blueprints by M. Beyeler:

Show Comments