Professional Documents
Culture Documents
Lab Manual No 01
Learning Outcomes:-
What is Python?
Python is a popular high-level programming language. It can handle various programming tasks
such as numerical computation, web development, database programming, network programming,
parallel processing, etc. Python is popular for various reasons which include:
1. It is free.
2. It is available on all the popular operating systems such as Windows, Mac or Linux.
3. It is an interpreted language. Hence, programmers can test portions of code on the
command line before incorporating it into their program. There is no need for compiling
or linking.
4. It comes with various modules that are standard or can be installed to an existing Python
installation. These modules can perform various tasks like reading and writing various
files, scientific computation, visualization of data etc.
5. It is a dynamically typed language. Hence the data type of variables does not have to be
declared prior to their use.
Indentation:
The general practice is to add a tab or 4 spaces at the start of every line. Since indentation is part
of the language to separate logical code sections, users do not need to use any curly braces. The
start and end of a block can be easily identified by following the indentation.
Comments:
In Python, a comment is denoted by a hash mark # at the beginning of a line. Multiple lines can be
commented by using triple quoted strings (' ' ') at the beginning and at the end of the block.
Variables:
Python is a dynamic language and hence you do not need to specify the variable type as in C/C++.
Variables can be imagined as containers of values. The values can be an integer, float, string, etc.
Digital Image Processing Lab Instructor:- Sheharyar Khan
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
Operators:
Python supports all the common arithmetic operators such as +; −; ∗; =. It also supports the
common comparison operators such as >; <; ==; ! =; >=; <= etc. In addition, through various
modules Python provides many operators for performing trigonometric, mathematical, geometric
operations etc.
Loops:
The most common looping construct in Python is the for-loop statement, which allows iterating
through the collection of objects. Here is an example:
The real power of for-loop lies in its ability to iterate through other Python objects such as lists,
dictionaries, sets, strings etc.
In the program above, the for-loop iterates through each element of the list and prints it.
In the next program, the content of a dictionary is printed using the for-loop. A dictionary with
two keys lang and ver is defined. Then, using the for-loop the various keys are iterated and the
corresponding values are printed.
If-else statement:
The if-else is a popular conditional statement in all programming languages including Python.
An example of if-elif-else statement is shown below.
The if-else statement conditionals do not necessarily have to use the conditional operators such as
<; >; == etc. For example, the following if statement is legal in Python. This if statement checks
for the condition that the list d is not empty.
Data Structures:
The real power of Python lies in the usage of its data structure. The common criticism of Python
is that it is slow compared to C/C++. This is especially true if multiple for-loops are used in
programming Python. Since Python is a dynamically typed language and since you do not declare
the type and size of the variable, Python has to dynamically allocate space for variables that
increase in size at runtime. Hence for-loops are not the most efficient way for programming
Python. The alternate is to use data structures such as lists, tuples, dictionary and sets. We describe
each of these data structures below.
List:
Lists are similar to arrays in C/C++. But, unlike arrays in C/C++, lists in Python can hold objects
of any type such as int, float, string and including another list. Lists can also have objects of
different type. Lists are mutable, as their size can be changed by adding or removing elements.
The following examples will help show the power and flexibility of lists.
A list may contain another list. Here is an example. We will consider the case of a list containing
four numbers and arranged to look like and operate like a matrix.
Although the list elements can be individually operated, the power of Python is in its ability to
operate on the entire list at once using list functions and list comprehensions.
List Functions:
Let us consider the list that we created in the previous section. We can sort the list using the sort
function as shown in line 2. The sort function does not return a list; instead, it modifies the current
list. Hence the existing list will contain the elements in a sorted order. If a list contains both
numbers and strings, Python sorts the numerical values first and then sorts the strings in
alphabetical order.
List Comprehension:
A list comprehension allows building a list from another list. Let us consider the case where we
need to generate a list of squares of numbers from 0 to 9. We will begin by generating a list of
numbers from 0 to 9. Then we will determine the square of each element.
Tuples:
Tuples are similar to lists except that they are not mutable, i.e. the length and the content of the
tuple cannot be changed at runtime. Syntactically, the list uses [ ] while tuples use ( ). Similar to
lists, tuples may contain any data type including other tuples. Here are a few examples:
Sets:
A set is an unordered collection of objects. A set can contain objects of any data type supported
by Python. To create a set, we need to use the function set. Here are some examples:
Sets in Python can be operated using many of the common mathematical operations on sets such
as union, intersection, set difference, symmetric difference etc. Since sets do not store repeating
values and since we can convert lists and tuples to sets easily, they can be used to perform useful
operations faster which otherwise would involve multiple loops and conditional statements. For
example, a list containing only unique values can be obtained by converting the list to a set and
back to a list. Here is an example:
Dictionaries:
Dictionaries store a key-value pair. A dictionary is created by enclosing a key-value pair inside {
}.
In the example above, we added a new key called creator and stored the the string, Guido Von
Rossum." In certain instances, the dictionary membership needs to be tested using the has key()
method. To obtain a list of all the dictionary keys, use the keys() method.
File Handling:
Python provides the ability to read and write files. It also has functions and methods for reading
specialized formats such as csv, Microsoft Excel (xls) format etc. We will look into each method
in this section.
The first line opens a file and returns a new file object which is stored in the variable fo." The
method readlines in line 2, reads all the lines of input. The for-loop then iterates over each of those
lines, and prints. The file is finally closed using the close method.
The program to read CSV files is similar to the previous program. A combination of strip method
in the for-loop will be sufficient to produce the same result. But, as true Python programmers, we
should use a function that is built specifically for this purpose.
Microsoft Excel files can be read using the xlrd module and written using the xlwt module. Here
is a simple example of reading an Excel file using the xlrd module.
In line 2, the open workbook() function is used to read the file. In line 3, the first sheet in the Excel
file is obtained. In lines 4 and 5, the various lines in that sheet are iterated and its content printed.
A function allows reuse of code fragments. A Python function can be created using the def
statement. Here is an example:
The function circleproperties takes in one input argument, the radius (r). The return statement at
the end of the function definition passes the computed values (in this case area and circumference)
to the calling function, circleproperties. To invoke the function, use the name of the function and
provide the radius value as argument enclosed in parenthesis. Finally, the area and circumference
of the circle are displayed using the print command.
Python comes with various built in batteries or modules. These batteries or modules perform
various specialized operations. The modules can be used to perform computation, database
management, web server etc. we limit our focus to Python modules that allow computation such
as scipy, numpy, matplotlib, Python Imaging Library (PIL) and scikits.
Python Modules:
A number of scientific Python modules have been created and are available in the Python
distributions. Some of the most popular modules relevant are:
Numpy:
NumPy, which stands for Numerical Python, is a library consisting of multidimensional array
objects and a collection of routines for processing those arrays. Using NumPy, mathematical and
logical operations on arrays can be performed. This section explains the basics of NumPy such as
its architecture and environment. It also discusses the various array functions, types of indexing,
etc. NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of
multidimensional array objects and a collection of routines for processing of array.
NumPy is often used along with packages like SciPy (Scientific Python) and Mat−plotlib (plotting
library). This combination is widely used as a replacement for MatLab, a popular platform for
technical computing. However, Python alternative to MatLab is now seen as a more modern and
complete programming language. It is open source, which is an added advantage of NumPy.
NumPy Environment:
To test whether NumPy module is properly installed, try to import it from Python prompt.
import numpy
If it is not installed, the following error message will be displayed.
import numpy as np
NumPy - Ndarray Object:
The most important object defined in NumPy is an N-dimensional array type called ndarray. It
describes the collection of items of the same type. Items in the collection can be accessed using a
zero-based index. Every item in an ndarray takes the same size of block in the memory. Each
element in ndarray is an object of data-type object (called dtype).
numpy.array
Example 1:
import numpy as np
a = np.array([1,2,3])
print(a)
[1, 2, 3]
Example 2:
# more than one dimensions
import numpy as np
print(a)
[[1, 2]
[3, 4]]
NumPy supports a much greater variety of numerical types than Python does.
ndarray.shape
This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the
array.
Example 1:
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print a.shape
(2, 3)
Example 2:
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a.shape = (3,2)
print a
[[1, 2]
[3, 4]
[5, 6]]
Example 3:
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print b
[[1, 2]
[3, 4]
[5, 6]]
Digital Image Processing Lab Instructor:- Sheharyar Khan
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
ndarray.ndim
Example 1
# an array of evenly spaced numbers
import numpy as np
a = np.arange(24)
print a
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20 21 22 23]
Example 2:
# this is one dimensional array
import numpy as np
a = np.arange(24)
a.ndim
# now reshape it
b = a.reshape(2,4,3)
print b
[[[ 0, 1, 2]
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
A new ndarray object can be constructed by any of the following array creation routines or using
a low-level ndarray constructor.
numpy.empty
Example
import numpy as np
print x
[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
The elements in an array show random values as they are not initialized.
numpy.zeros
Example 1
# array of five zeros. Default dtype is float
import numpy as np
x = np.zeros(5)
print x
[ 0. 0. 0. 0. 0.]
Example 2
import numpy as np
print x
[0 0 0 0 0]
numpy.ones
Returns a new array of specified size and type, filled with ones.
Example 1
# array of five ones. Default dtype is float
import numpy as np
x = np.ones(5)
print x
[ 1. 1. 1. 1. 1.]
Example 2
import numpy as np
print x
[[1 1]
[1 1]]
numpy.arange
This function returns an ndarray object containing evenly spaced values within a given range. The
format of the function is as follows.
Example 1
import numpy as np
x = np.arange(5)
print x
[0 1 2 3 4]
Example 2
import numpy as np
# dtype set
print x
[0. 1. 2. 3. 4.]
Example 3
# start and stop parameters set
import numpy as np
x = np.arange(10,20,2)
print x
[10 12 14 16 18]
Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python's
in-built container objects.
Example 1
import numpy as np
a = np.arange(10)
s = slice(2,7,2)
print a[s]
[2 4 6]
The same result can also be obtained by giving the slicing parameters separated by a colon :
(start:stop:step) directly to the ndarray object.
Example 2
import numpy as np
a = np.arange(10)
b = a[2:7:2]
print b
[2 4 6]
Example 3
import numpy as np
a = np.arange(10)
b = a[5]
print b
Example 4
# slice items starting from index
import numpy as np
a = np.arange(10)
print a[2:]
[2 3 4 5 6 7 8 9]
Example 5
# slice items between indexes
import numpy as np
a = np.arange(10)
print a[2:5]
[2 3 4]
Lab Tasks: