Introduction To NumPy and OpenCV
Introduction To NumPy and OpenCV
What is NumPy
In order to create an array, we can use the array function, passing a list of
values and optionally the type of data
NOTE: NumPy arrays must be homogeneous, so each element must have the same type
NOTE: notice that if the type is not set, NumPy will decide the type for you. Default value for NumPy
arrays is Float64
NumPy array: how to create an array
We use the functions zeros and ones to create an array with given shapes in
which each element is, respectively, 0 or 1
NumPy array: how to create an array
Given a NumPy array with a certain shape, zeros_like and ones_like allow to
create a 0 and 1 arrays with the same shape
NumPy array: how to create an array
Notice that the values are generated within the half-open [start, stop[, so stop is
not included
NumPy array: how to create an array
With eye we create an identity matrix, so a matrix full of zeros except for the
diagonal
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
Sometimes we need random values. We can obtain an array filled with random
values calling the rand function
NumPy array: how to create an array
Finally, we can create an array that contains a single scalar value using full
Each array has got attributes, such as dtype or shape. Attributes contain
important information related to that particular array
shape give you back the size of the array along each dimension
Changing the shape of arrays
Notice that this operation is valid for just 1 dimension. In fact, If more
dimensions are unknown, NumPy will throw ValueError
Changing the shape of arrays
Using squeeze, we can remove all the single dimensional entries of the array
However, squeeze allows also to specify the axis to delete (scalar, tuple or
None. Default is None)
Elements of arrays
Slice notation (the same used for python strings) is valid also for arrays
Elements of arrays
Given two array, we can concatenate them together to obtain a single array as
output thanks to the concatenate function
NumPy math
Since NumPy is a scientific package that offers easy and even complex
functions that you can apply to arrays.
Given two arrays, you can sum or subtract them just using + and - operators
In this case, both arrays have the same shape, so the operations are performed
element-wise
NumPy math: broadcasting
Sometimes, our arrays have not the same shape, but NumPy is smart enough
and try to “fit” the arrays. This operation is called broadcasting
Notice that y is a scalar, but both array_sum and array_sub have shapes (4,2,3)
NumPy math: broadcasting
Broadcasting can’t work for all the cases: when operating on two arrays,
NumPy looks at their shapes. The shapes are compatible if, in the element-wise
comparison, they are equals or one dimension is 1. The resulting shape is the
maximum shape along each dimension.
Given two NumPy arrays, we can perform matrix multiplication using matmul
function
Notice that NumPy is quite optimized, so when possible try to used “native”
NumPy way instead of other approaches
NumPy Input/Output
NumPy provides a set of functions to write and read directly from the
filesystem
Plain text (.txt) and csv (.csv) can be loaded using loadtxt function, providing
the path to the file, the data type and the delimiter
NumPy Input/Output
● binary file: using np.save we are able to serialize our arrays in the local file
system. We will obtain a .npy file containing the array
● txt: using savetxt function we will store our 1D or 2D array in a new txt
We can visualize NumPy arrays using some chart libraries, like Matplotlib
Matplotlib
Matplotlib is an open source plotting library able to produce high quality graphs
and charts. Easy to install using pip (just “pip install matplotlib”)
It offers a large set of plot types (e.g., histogram, scatter, line, 3D and more),
and uses NumPy arrays to handle data
Given two collection of values, m1 and m2, we can visualize them using
Matplotlib
OpenCV
OpenCV
Originally developed in C/C++, now OpenCV has handlers also for Java and
Python
Moreover, it is able to handle various image format (png, jpeg etc) and data
types (8bit, 16 bit etc)
OpenCV: Image Handling
Once opened, OpenCV returns a numpy array that stores the image (each value
of the array is a pixel)
OpenCV default format is BGR, so we have to swap the first and the last
channels in order to manage a RGB image. We can do it manually or invoking
the cvtColor function
(A) (B)
In figure (A), the original RGB image, while in figure (B) the same picture saved
using BGR format
OpenCV: Image Handling
(A) (B)
Instead, we can write an image in our file system using the imwrite function
However, remember that OpenCV expects a BGR image, so if img is a RGB you
must convert to BGR using cv2.cvtColor
OpenCV: Image Handling
OpenCV allows to resize images using the resize function. It takes the image
and the new shape
Changing the filter, we would obtain different results. For instance, high-pass
filter can be obtained through a zero-sum kernel
-1 0 1
-2 0 2
-1 0 1
OpenCV: filters
2
* -1 0 1
* 1
Example: Stereo Matching
from Middlebury Dataset
FAR CLOSE
Example: 3D reconstruction
point cloud can be visualized using MeshLab
Given the image canyon.png load it using OpenCV, split the channels and save
each channel in a new image called as the channel.
Using the same image of the previous exercise, load it as gray-scale and
replace all pixels with intensity lower than 80 with 0, 1 otherwise. Save it both
as a new image, called mask.png, and as npy. Finally, apply the mask to the
original image, keeping the original value where the mask is 1, 0 otherwise
Exercise 3