510 A Computational Introduction to Digital Image Processing, Second Edition
Python
In : B = A-1
In : print A.dot(B)
[[ 24 30 36]
[ 51 66 81]
[ 78 102 126]]
Note that we invoked the sqrt function from numpy, which operates on arrays. The sqrt
function f rom
math
is designed only to operate on single numbers:
Python
In : math.sqrt(A)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-69-8214aa97e221> in <module>()
----> 1 math.sqrt(A)
TypeError: only length-1 arrays can be converted to Python scalars
Here is an example of two functions sqrt with the same name, but with completely different
operations. For this reason, the importing of all functions from a library:
Python
In : from math import
*
may be dangerous, as it may place the wrong version of a function into the user namespace.
It is better to call functions from their libraries, as above.
Python provides an object oriented model, where an object of a particular type (such
as an array) has many methods associated with it. To see them, enter
A. (with period)
followed by the Tab
key:
Python
In : A. Tab
A.T A.conjugate A.flatten A.prod A.sort
A.all A.copy A.getfield A.ptp A.squeeze
A.any A.ctypes A.imag A.put A.std
A.argmax A.cumprod A.item A.ravel A.strides
A.argmin A.cumsum A.itemset A.real A.sum
A.argpartition A.data A.itemsize A.repeat A.swapaxes
A.argsort A.diagonal A.max A.reshape A.take
A.astype A.dot A.mean A.resize A.tofile
A.base A.dtype A.min A.round A.tolist
A.byteswap A.dump A.nbytes A.searchsorted A.tostring
A.choose A.dumps A.ndim A.setfield A.trace
A.clip A.fill A.newbyteorder A.setflags A.transpose
A.compress A.flags A.nonzero A.shape A.var
A.conj A.flat A.partition A.size A.view
In order to see what each one does, enter it followed by a question mark:
Introduction to Python 511
Python
In : A.max?
Type: builtin
_
function
_
or
_
method
String Form:<built-
in
method max of numpy.ndarray object at 0x1d9c4f0>
Docstring:
a.max(axis=None, out=None)
Return the maximum along a given axis.
Refer to ‘numpy.amax‘ for full documentation.
See Also
--------
numpy.amax : equivalent function
Then
Python
In : np.amax?
will produce copious documentation about finding the maxima of arrays.
Elements can be accessed with square bracket notation, and noting the vital fact that
in Python, arrays and lists are indexed starting at zero.
Python
In : A[0,1]
Out: 2
In : A[1]
Out: array([4, 5, 6])
In : B = np.reshape(range(25),(5,5))
In : print B
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
The range function in its simplest form range(n) provides a list of n integers from 0 to
n 1; more generally, we can have
range(<start>, <stop>, <step>):
Python
In : range(3,10)
Out: [3, 4, 5, 6, 7, 8, 9]
In : range(2,30,3)
Out: [2, 5, 8, 11, 14, 17]
Note that range does not include the final value.
Elements and rows or columns of an array can be produced by array
slicing, in a
manner similar to that of MATLAB, using a colon operator:
512 A Computational Introduction to Digital Image Processing, Second Edition
Python
In : print B[::2]
[[ 0 1 2 3 4]
[10 11 12 13 14]
[20 21 22 23 24]]
In : print B[::-1]
[[20 21 22 23 24]
[15 16 17 18 19]
[10 11 12 13 14]
[ 5 6 7 8 9]
[ 0 1 2 3 4]]
In : print B[:,::2]
[[ 0 2 4]
[ 5 7 9]
[10 12 14]
[15 17 19]
[20 22 24]]
In : print B[:,::-1]
[[ 4 3 2 1 0]
[ 9 8 7 6 5]
[14 13 12 11 10]
[19 18 17 16 15]
[24 23 22 21 20]]
In : print B[[0,3]]
[[ 0 1 2 3 4]
[15 16 17 18 19]]
In : print B[:,[3,4]]
[[ 3 4]
[ 8 9]
[13 14]
[18 19]
[23 24]]
As you see, two colons will list from the entire array in steps of the value given. Note also
that in Python elements are entered into arrays by rows, as opposed to MATLAB, where
elements are entered column-wise.
B.3 Graphics and Plots
The standard library for plotting in Python is matplotlib in which the module pyplot
provides plotting functionality in the style of MATLAB:
Introduction to Python 513
Python
In : import matplotlib as mpl
In : import matplotlib.pyplot as plt
In : x = np.arange(0,2
*
np.pi,0.1)
In : plt.plot(x,np.sin(x),x,np.cos(x),’or’)
Depending on your setup, you may now need to enter
Python
In : plt.show()
to display the plot, which is given in Figure B.2. Note that to create the list of
x
values,
we used the
arange f unction, which returns an array instead of a list.
FIGURE B.2: A plot with pyplot in Python
B.4 Programming
Programming in Python is broadly similar to any other high level language, but with
some extra flexibility and power. All the programming constructs–repetition, flow control,
input and output–are very easy.
One very elegant aspect is that the looping
for function allows you to iterate over pretty
much any list; the list may contain numbers, arrays, graphics, or other lists.
Suppose we aim to write a program that will set to zero all elements in an array that
are equal to the largest or second largest absolute value. For example:
Python
In : A = np.random.randint(-100,100,size=(10,10))
514 A Computational Introduction to Digital Image Processing, Second Edition
The
randint function produces values between the first (low) and second (high) values, in
an array of size given by the
size
parameter.
The largest absolute value can be found by
Python
In : maxA = abs(A).max()
In : maxA
Out:
98
Now we need to set to zero all values equal to ± 98:
Python
In : B = np.copy(A)
In : B[np.where(abs(A)==maxA)] = 0
The where function acts like MATLAB’s find: it produces lists of indices of all elements
satisfying a condition.
In order to work on a new array, the
copy function creates a new version of the original
array. Without
copy, B and A would simply be two names for the same array.
Now we simply do the same thing again, to eliminate elements with the next highest
absolute value:
Python
In : C = np.copy(B)
In : maxB = abs(B).max()
In : maxB
Out: 97
In : C[np.where(abs(B)==maxB)] = 0
We can see the difference with
Python
In : print abs(C-A)
[[ 0 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 97 0 0 0 0 0]
[ 0 0 0 0 0 98 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0 0]
[ 0 0 0 97 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 0 0 0]
[ 0 0 0 0 0 0 0 97 0 0]
[ 0 0 0 0 0 0 0 0 0 0]]
Now for the program:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.110.137