0% found this document useful (0 votes)
2 views

Numpy

The document provides an overview of using NumPy for numeric and scientific computing in Python, covering topics such as array creation, indexing, and operations. It also discusses integration with OpenCV for image processing, including reading, stacking, and smoothing images. Key functions and methods are illustrated with examples to facilitate understanding of NumPy's capabilities.

Uploaded by

160421737033
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Numpy

The document provides an overview of using NumPy for numeric and scientific computing in Python, covering topics such as array creation, indexing, and operations. It also discusses integration with OpenCV for image processing, including reading, stacking, and smoothing images. Key functions and methods are illustrated with examples to facilitate understanding of NumPy's capabilities.

Uploaded by

160421737033
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Machine Learning Lab

(PC 652 IT)


Numeric and Scientific
Computing using Numpy
Topics
1. Introduction to NumPy
2. NumPy Datatypes
3. Array Creation methods
4. Indexing and Slicing
5. Array Operations
6. Working with OpenCV
7. Stacking NumPy Arrays
8. Splitting NumPy Arrays
9. Smoothing an Image
1. Introduction to NumPy
• NumPy is a library for numerical computation in Python. It
stands for Numerical Python
• It consists of muti-dimensional array objects and a collection of
methods to process these arrays.
• Using NumPy, mathematical and logical operations on arrays
can be performed.
• Use the following command to install NumPy:
pip install numpy
• To use NumPy package, we have to import it:
import numpy as np
N-Dimensional Array - ndarray object
• ndarray is the most important object defined in NumPy.
• It is an N-dimensional array type
• It describes the collection of items of the same type.
• Items in the collection are accessed using an index (zero-
based).
• Ndarrays can be created in many ways in NumPy. The most
basic method is to use the array method.
ndarray example
• The basic ndarray is created using an array function in NumPy
as numpy.array(list_of_elements). For example:
a1 = np.array([1,2,3])
print (a1)
a2 = np.array([[1, 2], [3, 4]]) # 2-D array
print(a2)
2. NumPy Datatypes
• We can specify the datatype of the elements:
a3 = np.array([[1, 2], [3, 4]],dtype=str) # 2-D array
• NumPy supports a rich variety of numerical types, many more
than Python does.
• The following is the list of DataTypes supported in NumPy:
integer, boolean, unsigned integer, float, complex float,
timedelta, datetime, object, string, unicode string, fixed chunk
of memory for other type ( void )
• The dtype property of NumPy array object returns the data
type of the array: print(a2.dtype)
Array Attributes
• ndarray.shape: This array attribute returns a tuple. This tuple
consists of array dimensions.
• The reshape function is used to resize an array. For example:
a4 = np.array([[1,2],[4,5],[7,8]])
print(a4)
print(a4.shape)
a4=a4.reshape(2,3)
print(a4.shape)
print(a4)
3. Array Creation methods
• A new ndarray object can be created by the following array
creation methods:
i. numpy.empty(): It creates an uninitialized array of specified
shape and dtype. It uses the following syntax:
numpy.empty(shape, dtype = float, order = 'C')
For Example:
x = np.empty([3,2], dtype = int)
print(x)
ii. numpy.zeros(): Returns a new array filled with zeroes, of
specified size. Syntax: numpy.zeros(shape, dtype = float, order = 'C')
Array Creation methods (cont..)
x = np.zeros([5,3], dtype = int)
print(x)
iii. numpy.ones(): Returns a new array of specified size and type,
filled with ones.
numpy.ones(shape, dtype = float, order = 'C')
x = np.ones(5) # Default dtype is float
print(x)
Creating arrays from data
• numpy.asarray(): This function is useful for converting Python
sequence into ndarray. Its syntax is:
numpy.asarray(a, dtype = None, order = None)
x = [1,2,3]
a = np.asarray(x) # a is integer ndarray
a = np.asarray(x, dtype = float) # a is float ndarray
• numpy.fromiter(): This function builds an ndarray object from
any iterable object. A new one-dimensional array is returned
by this function.
Creating arrays from data (cont..)
• Its syntax is :
numpy.fromiter(iterable, dtype, count = -1)
Where count indicate number of items to be read from the
iterable. -1 means all items.
list1 = range(5)
x1 = np.fromiter(list1, dtype = float)
print(x1)
Creating arrays from numerical ranges
• numpy.arange(): This function returns an ndarray object which
contains evenly spaced values within a given range. Syntax of
the function is:
numpy.arange(start, stop, step, dtype)
• For example:
x = np.arange(0,10,2,float)
print(x)
• numpy.linspace(): In this function, instead of step size, the
number of values between the interval is specified. These
values are evenly spaced.
Creating arrays from numerical ranges (cont..)
• The syntax of this function is as follows:
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
• For example:
x = np.linspace(10,20,15)
print(x)
4. Indexing and Slicing
• The contents of ndarray objects can be accessed and modified
by slicing and indexing, like Python's other built-in container
objects.
• Items in ndarray object follows zero-based index.
• ndarray slicing is an extension of Python's basic concept of
slicing, extended to n dimensions.
• A Python slice object is constructed by giving start, stop,
and step parameters to the built-in slice function.
• This sliced object is passed to the array in order to extract a
part of the array.
Indexing and Slicing (cont..)
• Single dimension array
a = np.arange(10)
b = a[2:7:2]
print(b)
• Multi dimensional array
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print(a)
print(a[1:])
print(a[1][2])
print(a[2])
Advanced Indexing
• There are two types of advanced indexing:
i. Integer Indexing: This mechanism helps in selecting any
arbitrary item in an array based on its ndarray index. Each
integer array is used to represent the number of indices into
that dimension.
ii. Boolean Indexing: This type of advanced indexing is used when
the resultant object is meant to be the result of Boolean
operations, such as comparison operators.
Integer Indexing
• The following operation returns the elements: (0,0),(1,1),(2,0)
x = np.array([[1, 2], [3, 4], [5, 6]])
y = x[[0,1,2], [0,1,0]]
print(y)
• Advanced and basic indexing can be combined by using slice (:)
with an index array.
x = np.array([[ 10, 11, 12],[13, 14, 15],[16,17,18],[ 19, 20, 21]])
print(x)
# using advanced index for column
y = x[1:3,[0,1]]
print(y)
Boolean Indexing
• Find all elements greater than 15:
x = np.array([[ 10, 11, 12],[13, 14, 15],[16,17,18],[ 19, 20, 21]])
print ('The items greater than 15 are:' )
print(x[x > 15])
• Find all non-NaN elements:
print(x[~np.isnan(x)])
• Find all non-integer elements:
print (x[x.dtype!=‘int'])
Broadcasting
• Broadcasting is the ability of NumPy to work with arrays of
different shapes during arithmetic operations.
• Arithmetic operations on arrays are usually done on
corresponding elements.
• If the dimensions of two arrays are dissimilar, the smaller array
is said to be broadcast to the size of the larger array.
• This is done so that they may have compatible shapes.
• Consider the following example:
Broadcasting Example
a = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]])
b = np.array([1.0,2.0,3.0])
print('First Array + Second Array' )
print(a + b)
5. Array Operations
• Transpose: x.T
• Joining Arrays:
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
print('a:',a)
print('b:',b)
print('Joining the two arrays along axis 0:')
print(np.concatenate((a,b)))
print('Joining the two arrays along axis 1:')
print(np.concatenate((a,b),axis = 1))
Iterating over Arrays
• NumPy package contains an iterator object numpy.nditer.
• nditer is an efficient multidimensional iterator object using
which we can iterate over a complete array.
• For Example:
x = np.array ([[ 10, 11, 12],[13, 14, 15],[16,17,18],[ 19, 20, 21]])
for i in np.nditer(x):
print(i)
6. Working with OpenCV
• OpenCV-Python is a library in Python which is designed to solve
computer vision problems.
• OpenCV-Python makes use of Numpy, which is a highly
optimized library for numerical operations.
• All the OpenCV array structures are converted into Numpy
arrays, and vice versa.
• Install OpenCV: Open the command line and type:
pip install opencv-python
• OpenCV must be imported into Python programs: import cv2
Representing an image in OpenCV
• Consider a grayscale image, called smallgray.png of 15 pixels.
Reading image from a file
• cv2.imread() method is used to load an image from a file.
• If the image cannot be read for any reason (for example,
because of missing file, improper permissions, etc) then this
method returns an empty matrix.
• The first argument to the imread method specifies the path of
the image
• The second argument is a flag. It specifies the mode in which
the image should be read. For example:
im_g = cv2.imread("smallgray.png",0) # 0 means grayscale
Reading image from a file (cont..)
• cv2.imread() returns a numpy array which represents the pixel
by pixel representation of the image. For example, the numpy
array returned by the previous command is:
• print(im_g)
[[187 158 104 121 143]
[198 125 255 255 147]
[209 134 255 97 182]]
• Where each value in the array represents the grayscale value
of each of the 15 pixels in the image.
7. Stacking Numpy Arrays
• We can stack numpy arrays either horizontally or vertically
using the hstack() and vstack() methods. For example:
• im_h = np.hstack((im_g,im_g))
print(im_h)
• As we can observe from the output, the above operation has
effectively created two copies of the same image in one
variable, called im_h
Stacking Numpy arrays
• Similarly, we can stack arrays vertically using vstack method:
• im_v = np.vstack((im_g,im_g,im_g))
• print(im_v)
[[187 158 104 121 143]
[198 125 255 255 147]
[209 134 255 97 182]
[187 158 104 121 143]
[198 125 255 255 147]
[209 134 255 97 182]
[187 158 104 121 143]
[198 125 255 255 147]
[209 134 255 97 182]]
8. Splitting Numpy arrays
• The following methods can be used to split numpy arrays
horizontally as well as vertically:
• hsplit(): Splits an array into multiple sub-arrays horizontally
(column-wise)
• vsplit(): Splits an array into multiple sub-arrays vertically (row-
wise)
• For example:
• im_sp_h=np.hsplit(im_h,2)
print(im_sp_h)
• im_sp_v=np.vsplit(im_v,3)
print(im_sp_v)
9. Smoothing an Image
import cv2
im_g = cv2.imread("smallgray.png",0)
print(im_g)
img_blur = cv2.blur(im_g,(3,5))
# Blur the image based on average of surrounding pixels
print(img_blur)
cv2.imwrite("newsmallgray.png",img_blur)
Blurred Image
THANK YOU

You might also like