1. File "C:UsersuserAppDataLocalTempipykernel_112242016897723.py", line 1
<h1 align='left' >AIR UNIVERSITY</h1>
^
SyntaxError: invalid syntax
NumPy
NumPy is a library that extends the base capabilities of python to add a richer data set including more numeric types, vectors, matrices, and many matrix functions. NumPy and python work
together fairly seamlessly. Python arithmetic operators work on NumPy data types and many NumPy functions will accept python data types.
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: numpy in f:anaconlibsite-packages (1.21.5)
Vectors
Abstract
Vectors, as you will use them in this lab, are ordered arrays of numbers. In notation, vectors are denoted with lower case bold letters such as . The elements of a vector are all the same
type. A vector does not, for example, contain both characters and numbers. The number of elements in the array is often referred to as the dimension though mathematicians may prefer rank.
The elements of a vector can be referenced with an index. In math settings, indexes typically run from 1 to n. In computer science and these labs, indexing will typically run from 0 to n-1. In
notation, elements of a vector, when referenced individually will indicate the index in a subscript, for example, the element, of the vector is . Note, the x is not bold in this case.
NumPy Arrays
NumPy's basic data structure is an indexable, n-dimensional array containing elements of the same type ( dtype ). Right away, you may notice we have overloaded the term 'dimension'.
Above, it was the number of elements in the vector, here, dimension refers to the number of indexes of an array. A one-dimensional or 1-D array has one index.
1-D array, shape (n,): n elements indexed [0] through [n-1]
Vector Creation
Data creation routines in NumPy will generally have a first parameter which is the shape of the object. This can either be a single value for a 1-D result or a tuple (n,m,...) specifying the shape
of the result. Below are examples of creating vectors using these routines.
np.zeros(4) : a = [0. 0. 0. 0.], a shape = (4,), a data type = float64
np.zeros(4,) : a = [0. 0. 0. 0.], a shape = (4,), a data type = float64
np.random.random_sample(4): a = [0.73323249 0.14442404 0.58776524 0.04985309], a shape = (4,), a data type = float64
Some data creation routines do not take a shape tuple:
np.arange(4.): a = [0. 1. 2. 3.], a shape = (4,), a data type = float64
np.random.rand(4): a = [0.87071674 0.8207533 0.3754749 0.47835858], a shape = (4,), a data type = float64
value of x is 2
values can be specified manually as well.
np.array([5,4,3,2]): a = [5 4 3 2], a shape = (4,), a data type = int32
np.array([5.,4,3,2]): a = [5. 4. 3. 2.], a shape = (4,), a data type = float64
These have all created a one-dimensional vector a with four elements. a.shape returns the dimensions. Here we see a.shape = (4,) indicating a 1-d array with 4 elements.
Operations on Vectors
Let's explore some operations using vectors.
Indexing
Elements of vectors can be accessed via indexing and slicing. NumPy provides a very complete set of indexing and slicing capabilities. We will explore only the basics needed for the course
here.
Indexing means referring to an element of an array by its position within the array.
Slicing means getting a subset of elements from an array based on their indices.
NumPy starts indexing at zero so the 3rd element of an vector is a[2] .
[0 1 2 3 4 5 6 7 8 9]
a[2].shape: () a[2] = 2, Accessing an element returns a scalar
a[-1] = 9
The error message you'll see is:
index 10 is out of bounds for axis 0 with size 10
Slicing
Slicing creates an array of indices using a set of three values ( start:stop:step ). A subset of values is also valid. Its use is best explained by example:
a = [0 1 2 3 4 5 6 7 8 9]
a[2:7:1] = [2 3 4 5 6]
a[2:7:2] = [2 4 6]
a[3:] = [3 4 5 6 7 8 9]
a[:3] = [0 1 2]
a[:] = [0 1 2 3 4 5 6 7 8 9]
Single vector operations
There are a number of useful operations that involve operations on a single vector.
a : [1 2 3 4]
b = -a : [-1 -2 -3 -4]
b = np.sum(a) : 10
b = np.mean(a): 2.5
b = a**2 : [ 1 4 9 16]
Vector Vector element-wise operations
Most of the NumPy arithmetic, logical and comparison operations apply to vectors as well. These operators work on an element-by-element basis. For example
Binary operators work element wise: [0 0 6 8]
Of course, for this to work correctly, the vectors must be of the same size:
The error message you'll see is:
operands could not be broadcast together with shapes (4,) (2,)
Scalar Vector operations
Vectors can be 'scaled' by scalar values. A scalar value is just a number. The scalar multiplies all the elements of the vector.
b = 5 * a : [ 5 10 15 20]
Vector Vector dot product
The dot product is a mainstay of Linear Algebra and NumPy. The dot product multiplies the values in two vectors element-wise and then sums the result. Vector dot product requires the
dimensions of the two vectors to be the same. Let's implement our own version of the dot product below:
Using a for loop, implement a function which returns the dot product of two vectors. The function to return given inputs and :
Assume both a and b are the same shape.
my_dot(a, b) = 24
Note, the dot product is expected to return a scalar value.
Let's try the same operations using np.dot .
NumPy 1-D np.dot(a, b) = 24, np.dot(a, b).shape = ()
NumPy 1-D np.dot(b, a) = 24, np.dot(a, b).shape = ()
Above, you will note that the results for 1-D matched our implementation.
The Need for Speed: vector vs for loop
We utilized the NumPy library because it improves speed memory efficiency. Let's demonstrate:
np.dot(a, b) = 2501072.5817
Vectorized version duration: 1377.0380 ms
my_dot(a, b) = 2501072.5817
loop version duration: 32071.1446 ms
So, vectorization provides a large speed up in this example. This is because NumPy makes better use of available data parallelism in the underlying hardware. GPU's and modern CPU's
implement Single Instruction, Multiple Data (SIMD) pipelines allowing multiple operations to be issued in parallel. This is critical in Machine Learning where the data sets are often very large.
Vector Vector operations
That is a somewhat lengthy explanation, but aligning and understanding the shapes of your operands is important when performing vector operations.
(4, 1)
X[1] has shape (1,)
w has shape (1,)
c has shape ()
Matrices
Abstract
Matrices, are two dimensional arrays. The elements of a matrix are all of the same type. In notation, matrices are denoted with capital, bold letter such as . In this and other labs, m is often
the number of rows and n the number of columns. The elements of a matrix can be referenced with a two dimensional index. In math settings, numbers in the index typically run from 1 to n.
In computer science and these labs, indexing will run from 0 to n-1.
NumPy Arrays
NumPy's basic data structure is an indexable, n-dimensional array containing elements of the same type ( dtype ). These were described earlier. Matrices have a two-dimensional (2-D)
index [m,n].
Below you will review:
data creation
slicing and indexing
Matrix Creation
The same functions that created 1-D vectors will create 2-D or n-D arrays. Here are some examples
Below, the shape tuple is provided to achieve a 2-D result. Notice how NumPy uses brackets to denote each dimension. Notice further than NumPy, when printing, will print one row per line.
a shape = (1, 5), a = [[0. 0. 0. 0. 0.]]
<class 'numpy.ndarray'>
a shape = (2, 1), a = [[0.]
[0.]]
a shape = (1, 1), a = [[0.44236513]]
One can also manually specify data. Dimensions are specified with additional brackets matching the format in the printing above.
a shape = (3, 1), np.array: a = [[5]
[4]
[3]]
a shape = (3, 1), np.array: a = [[5]
[4]
[3]]
Operations on Matrices
Let's explore some operations using matrices.
Indexing
Matrices include a second index. The two indexes describe [row, column]. Access can either return an element or a row/column. See below:
a.shape: (3, 2),
a= [[0 1]
[2 3]
[4 5]]
a[2,0].shape: (), a[2,0] = 4, type(a[2,0]) = <class 'numpy.int32'> Accessing an element returns a scalar
a[2].shape: (2,), a[2] = [4 5], type(a[2]) = <class 'numpy.ndarray'>
It is worth drawing attention to the last example. Accessing a matrix by just specifying the row will return a 1-D vector.
Reshape
The previous example used reshape to shape the array.
a = np.arange(6).reshape(-1, 2)
This line of code first created a 1-D Vector of six elements. It then reshaped that vector into a 2-D array using the reshape command. This could have been written:
a = np.arange(6).reshape(3, 2)
To arrive at the same 3 row, 2 column array. The -1 argument tells the routine to compute the number of rows given the size of the array and the number of columns.
Slicing
Slicing creates an array of indices using a set of three values ( start:stop:step ). A subset of values is also valid. Its use is best explained by example:
a =
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]]
a[0, 2:7:1] = [2 3 4 5 6] , a[0, 2:7:1].shape = (5,) a 1-D array
a[:, 2:7:1] =
[[ 2 3 4 5 6]
[12 13 14 15 16]] , a[:, 2:7:1].shape = (2, 5) a 2-D array
a[:,:] =
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]] , a[:,:].shape = (2, 10)
a[1,:] = [10 11 12 13 14 15 16 17 18 19] , a[1,:].shape = (10,) a 1-D array
a[1] = [10 11 12 13 14 15 16 17 18 19] , a[1].shape = (10,) a 1-D array
Numpy Array Functions
Array:
[[2 3 4]
[5 6 7]]
Its shape: (2, 3)
Array after append:
[[2 3]
[4 5]
[6 7]
[2 3]
[4 8]
[5 6]
[7 9]]
[[ 2 99 3 4 5]
[ 6 7 2 3 4]
[ 8 5 6 7 9]]
[[ 2 98 97]
[96 95 3]
[ 4 5 6]
[ 7 2 3]
[ 4 8 5]
[ 6 7 9]]
[[2 5 6]
[7 2 3]
[4 8 5]
[6 7 9]]
5.333333333333333
5.5
2.173067468400883
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ,
5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5, 10. ])
array([[8, 8, 8, 8],
[8, 8, 8, 8],
[8, 8, 8, 8]])
array([[1., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 1.]])
[[ 1 1]
[ 3 -8]]
[[ 1 1]
[ 3 -8]]
[[5 9]
[9 8]]
[[5 9]
[9 8]]
[[ 6 20 35]
[18 0 72]]
[[ 6 20 35]
[18 0 72]]
[[2 4]
[5 3]
[8 8]]
[[87 83]
[84 96]]
[[ 7.3890561 54.59815003]
[ 148.4131591 20.08553692]
[2980.95798704 2980.95798704]]
[[1.41421356 2. ]
[2.23606798 1.73205081]
[2.82842712 2.82842712]]
[[ 0.90929743 -0.7568025 ]
[-0.95892427 0.14112001]
[ 0.98935825 0.98935825]]
[[0.69314718 1.38629436]
[1.60943791 1.09861229]
[2.07944154 2.07944154]]
30
2
[4 4 5]
array([[4, 6, 4]])
[[4 5 9]
[5 8 9]
[3 5 7]]
[[0 5 9]
[3 5 8]
[1 3 7]]
[[0 5 9]
[3 5 8]
[1 3 7]]
array([[3, 5, 7],
[6, 0, 9],
[2, 4, 5],
[3, 8, 8],
[4, 6, 8]])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~AppDataLocalTempipykernel_111682850222346.py in <module>
2 [3,8],
3 [4,6]])
----> 4 Y = np.concatenate((X,c))
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the
array at index 1 has size 2
X:
[[3 5 7]
[6 0 9]
[2 4 5]
[3 8 8]
[4 6 8]]
a:
[[3 5 7]
[6 0 9]]
b:
[[2 4 5]
[3 8 8]
[4 6 8]]
c:
[[2 4]
[3 8]
[4 6]]
array([[2, 4, 5, 2, 4],
[3, 8, 8, 3, 8],
[4, 6, 8, 4, 6]])
array([[3, 5, 7],
[6, 0, 9],
[2, 4, 5],
[3, 8, 8],
[4, 6, 8],
[3, 5, 7],
[6, 0, 9]])
array([[2, 4, 5, 2, 4],
[3, 8, 8, 3, 8],
[4, 6, 8, 4, 6]])
[[3 5 7]
[6 0 9]
[2 4 5]
[3 8 8]
[4 6 8]]
[array([[3],
[6],
[2],
[3],
[4]]), array([[5],
[0],
[4],
[8],
[6]]), array([[7],
[9],
[5],
[8],
[8]])]
[[3]
[6]
[2]
[3]
[4]]
[array([[3, 5, 7]]), array([[6, 0, 9]]), array([[2, 4, 5]]), array([[3, 8, 8]]), array([[4, 6, 8]])]
[[3 8 8]]
MATPLOTLIB
Y value with respect to X
Y value with respect to index
Subplots
OpenCV
OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for
computer vision applications and to accelerate the use of machine perception in commercial products. Let's load an image using OpenCV and display it.
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: numpy in f:anaconlibsite-packages (1.21.5)
Requirement already satisfied: matplotlib in f:anaconlibsite-packages (3.5.2)
Requirement already satisfied: opencv-python in c:usersuserappdataroamingpythonpython39site-packages (4.7.0.68)
Requirement already satisfied: pyparsing>=2.2.1 in f:anaconlibsite-packages (from matplotlib) (3.0.9)
Requirement already satisfied: cycler>=0.10 in f:anaconlibsite-packages (from matplotlib) (0.11.0)
Requirement already satisfied: packaging>=20.0 in f:anaconlibsite-packages (from matplotlib) (21.3)
Requirement already satisfied: python-dateutil>=2.7 in f:anaconlibsite-packages (from matplotlib) (2.8.2)
Requirement already satisfied: fonttools>=4.22.0 in f:anaconlibsite-packages (from matplotlib) (4.25.0)
Requirement already satisfied: kiwisolver>=1.0.1 in f:anaconlibsite-packages (from matplotlib) (1.4.2)
Requirement already satisfied: pillow>=6.2.0 in f:anaconlibsite-packages (from matplotlib) (9.2.0)
Requirement already satisfied: six>=1.5 in f:anaconlibsite-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)
Note: you may need to restart the kernel to use updated packages.
1.21.5
3.5.2
4.7.0
Loading an image
array([[[151, 168, 181],
[151, 168, 181],
[151, 168, 181],
...,
[ 77, 89, 99],
[ 76, 88, 98],
[ 76, 88, 98]],
[[151, 168, 181],
[151, 168, 181],
[151, 168, 181],
...,
[ 76, 88, 98],
[ 76, 88, 98],
[ 76, 88, 98]],
[[151, 168, 181],
[151, 168, 181],
[151, 168, 181],
...,
[ 76, 88, 98],
[ 75, 87, 97],
[ 74, 86, 96]],
...,
[[ 87, 101, 154],
[ 88, 102, 154],
[ 81, 95, 148],
...,
[ 97, 106, 109],
[ 95, 104, 107],
[ 90, 99, 103]],
[[ 82, 94, 152],
[ 88, 102, 155],
[ 86, 100, 152],
...,
[ 95, 107, 109],
[102, 114, 116],
[102, 113, 117]],
[[ 84, 96, 154],
[ 83, 97, 150],
[ 92, 106, 158],
...,
[ 92, 104, 106],
[ 91, 103, 105],
[ 92, 104, 106]]], dtype=uint8)
(616, 925)
array([[151, 151, 151, ..., 77, 76, 76],
[151, 151, 151, ..., 76, 76, 76],
[151, 151, 151, ..., 76, 75, 74],
...,
[ 87, 88, 81, ..., 97, 95, 90],
[ 82, 88, 86, ..., 95, 102, 102],
[ 84, 83, 92, ..., 92, 91, 92]], dtype=uint8)
RGB (Red-Green-Blue): This is the most common color space for displaying and editing color images. Each pixel in an RGB image is represented by three values, indicating the intensities of
red, green, and blue.
Grayscale: A grayscale image is a single-channel image that represents the luminance (brightness) of each pixel. Grayscale images are often used for image analysis and computer vision
tasks.
HSV (Hue-Saturation-Value): This color space separates color information into hue (the color itself), saturation (the intensity of the color), and value (the brightness of the color). HSV is often
used in image processing tasks like color segmentation and object tracking.
LAB (Luminance-a-b): This color space separates color information into luminance (the brightness of the color) and two chrominance channels (a and b). LAB is often used in computer vision
tasks like edge detection and color-based object detection.
YUV/YCbCr (Luma-Chroma): These color spaces separate color information into a luminance channel (Y) and two chrominance channels (UV or YCbCr). YUV/YCbCr are often used in video
processing tasks like compression and transmission.
CMYK (Cyan-Magenta-Yellow-Black): This color space is used in printing to represent the colors that can be created by subtractive color mixing. CMYK is often used in printing applications.
array([[170, 170, 170, ..., 91, 90, 90],
[170, 170, 170, ..., 90, 90, 90],
[170, 170, 170, ..., 90, 89, 88],
...,
[115, 116, 109, ..., 106, 104, 99],
[110, 116, 114, ..., 106, 113, 113],
[112, 111, 120, ..., 103, 102, 103]], dtype=uint8)
(616, 925)
(1000, 1000, 3)
True
(616, 925, 3)
(616, 925)
(1000, 1000, 3)
Conclusion
Python is apt choice for such Image processing tasks. This is due to its growing popularity as a scientific programming language and the free availability of many State of Art Image
Processing tools in its ecosystem.
OpenCV stands for Open Source Computer Vision. It is a popular tool used for image processing tasks in different applications. This open-source library is used to process images and
videos for face detection, object detection, as well as human handwriting.
OpenCV represents an image as a NumPy array comprising integers that represent the pixels and intensity- hence, by indexing and slicing portions of the NumPy array, we are
essentially isolating specific pixels thereby isolating specific portions of the image itself, thus allowing us to effectively crop the image.
In [1]: <h1 align='left' >AIR UNIVERSITY</h1>
<h1 align='left' >Department of Electrical and Computer Engineering</h1>
<h1 align='left' >Digital Image Processing Lab</h1>
<h1 align='left' >Lab #2: Introduction to Color Space Models in Digital Image Processing</h1>
<h2 align='left' >Student Name: Umar Mustafa</h2>
<h2 align='left' >Roll No: 200365</h2>
<h2 align='left' >Instructor: Engr. M. Farooq Khan </h2>
In [7]: !pip install numpy
In [8]: import numpy as np # it is an unofficial standard to use np for numpy
np.set_printoptions(suppress=True)
import time
x
0
th
x x0
In [9]: # NumPy routines which allocate memory and fill arrays with value
a = np.zeros(4); print(f"np.zeros(4) : a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
a = np.zeros((4,)); print(f"np.zeros(4,) : a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
a = np.random.random_sample(4); print(f"np.random.random_sample(4): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
In [10]: # NumPy routines which allocate memory and fill arrays with value but do not accept shape as input argument
a = np.arange(4.); print(f"np.arange(4.): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
a = np.random.rand(4); print(f"np.random.rand(4): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
In [11]: x = 2;
print (f"value of x is {x}")
In [12]: # NumPy routines which allocate memory and fill with user specified values
a = np.array([5,4,3,2]); print(f"np.array([5,4,3,2]): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
a = np.array([5.,4,3,2]); print(f"np.array([5.,4,3,2]): a = {a}, a shape = {a.shape}, a data type = {a.dtype}")
a
In [13]: #vector indexing operations on 1-D vectors
a = np.arange(10)
print(a)
#access an element
print(f"a[2].shape: {a[2].shape} a[2] = {a[2]}, Accessing an element returns a scalar")
# access the last element, negative indexes count from the end
print(f"a[-1] = {a[-1]}")
#indexs must be within the range of the vector or they will produce and error
try:
c = a[10]
except Exception as e:
print("The error message you'll see is:")
print(e)
In [14]: #vector slicing operations
a = np.arange(10)
print(f"a = {a}")
#access 5 consecutive elements (start:stop:step)
c = a[2:7:1]; print("a[2:7:1] = ", c)
# access 3 elements separated by two
c = a[2:7:2]; print("a[2:7:2] = ", c)
# access all elements index 3 and above
c = a[3:]; print("a[3:] = ", c)
# access all elements below index 3
c = a[:3]; print("a[:3] = ", c)
# access all elements
c = a[:]; print("a[:] = ", c)
In [15]: a = np.array([1,2,3,4])
print(f"a : {a}")
# negate elements of a
b = -a
print(f"b = -a : {b}")
# sum all elements of a, returns a scalar
b = np.sum(a)
print(f"b = np.sum(a) : {b}")
b = np.mean(a)
print(f"b = np.mean(a): {b}")
b = a**2
print(f"b = a**2 : {b}")
a + b =
n−1
∑
i=0
ai
+ bi
In [16]: a = np.array([ 1, 2, 3, 4])
b = np.array([-1,-2, 3, 4])
print(f"Binary operators work element wise: {a + b}")
In [17]: #try a mismatched vector operation
c = np.array([1, 2])
try:
d = a + c
except Exception as e:
print("The error message you'll see is:")
print(e)
In [18]: a = np.array([1, 2, 3, 4])
# multiply a by a scalar
b = 5 * a
print(f"b = 5 * a : {b}")
a b
x =
n−1
∑
i=0
aibi
In [19]: from IPython import display
display.Image("F:/Dot_Product.PNG")
Out[19]:
In [20]: def my_dot(a, b):
"""
Compute the dot product of two vectors
Args:
a (ndarray (n,)): input vector
b (ndarray (n,)): input vector with same dimension as a
Returns:
x (scalar):
"""
x=0
for i in range(a.shape[0]):
x = x + a[i] * b[i]
return x
In [21]: # test 1-D
a = np.array([1, 2, 3, 4])
b = np.array([-1, 4, 3, 2])
print(f"my_dot(a, b) = {my_dot(a, b)}")
In [22]: # test 1-D
a = np.array([1, 2, 3, 4])
b = np.array([-1, 4, 3, 2])
c = np.dot(a, b)
print(f"NumPy 1-D np.dot(a, b) = {c}, np.dot(a, b).shape = {c.shape} ")
c = np.dot(b, a)
print(f"NumPy 1-D np.dot(b, a) = {c}, np.dot(a, b).shape = {c.shape} ")
In [23]: np.random.seed(1)
a = np.random.rand(10000000) # very large arrays
b = np.random.rand(10000000)
tic = time.time() # capture start time
c = np.dot(a, b)
toc = time.time() # capture end time
print(f"np.dot(a, b) = {c:.4f}")
print(f"Vectorized version duration: {1000*(toc-tic):.4f} ms ")
tic = time.time() # capture start time
c = my_dot(a,b)
toc = time.time() # capture end time
print(f"my_dot(a, b) = {c:.4f}")
print(f"loop version duration: {1000*(toc-tic):.4f} ms ")
del(a);del(b) #remove these big arrays from memory
In [24]: import numpy as np
X = np.array([[1],
[2],
[3],
[4]])
w = np.array([2])
c = np.dot(X[1], w)
print(X.shape)
print(f"X[1] has shape {X[1].shape}")
print(f"w has shape {w.shape}")
print(f"c has shape {c.shape}")
X
In [25]: a = np.zeros((1, 5))
print(f"a shape = {a.shape}, a = {a}")
print(type(a))
a = np.zeros((2, 1))
print(f"a shape = {a.shape}, a = {a}")
a = np.random.random_sample((1, 1))
print(f"a shape = {a.shape}, a = {a}")
In [26]: # NumPy routines which allocate memory and fill with user specified values
a = np.array([[5], [4], [3]]); print(f" a shape = {a.shape}, np.array: a = {a}")
a = np.array([[5], # One can also
[4], # separate values
[3]]); #into separate rows
print(f" a shape = {a.shape}, np.array: a = {a}")
In [27]: #vector indexing operations on matrices
a = np.arange(6).reshape(-1, 2) #reshape is a convenient way to create matrices
print(f"a.shape: {a.shape}, na= {a}")
#access an element
print(f"na[2,0].shape: {a[2, 0].shape}, a[2,0] = {a[2, 0]}, type(a[2,0]) = {type(a[2, 0])} Accessing an element returns a scalarn")
#access a row
print(f"a[2].shape: {a[2].shape}, a[2] = {a[2]}, type(a[2]) = {type(a[2])}")
In [28]: #vector 2-D slicing operations
a = np.arange(20).reshape(-1, 10)
print(f"a = n{a}")
#access 5 consecutive elements (start:stop:step)
print("a[0, 2:7:1] = ", a[0, 2:7:1], ", a[0, 2:7:1].shape =", a[0, 2:7:1].shape, "a 1-D array")
#access 5 consecutive elements (start:stop:step) in two rows
print("a[:, 2:7:1] = n", a[:, 2:7:1], ", a[:, 2:7:1].shape =", a[:, 2:7:1].shape, "a 2-D array")
# access all elements
print("a[:,:] = n", a[:,:], ", a[:,:].shape =", a[:,:].shape)
# access all elements in one row (very common usage)
print("a[1,:] = ", a[1,:], ", a[1,:].shape =", a[1,:].shape, "a 1-D array")
# same as
print("a[1] = ", a[1], ", a[1].shape =", a[1].shape, "a 1-D array")
In [29]: arr1 = np.array([[2, 3, 4],
[5, 6, 7]])
print("Array:n", arr1)
print("nIts shape:", arr1.shape)
arr2 = np.array([[2, 3, 4, 8],
[5, 6, 7, 9]])
new_array1 = np.append(arr1,arr2).reshape(7,-1) #it append and flattens both the arrays
print("Array after append:n", new_array1)
In [30]: new_array2 = np.insert(new_array1, 1, 99).reshape(3,-1)
print(new_array2)
In [31]: new_array2 = np.insert(new_array1, 1, [98, 97, 96, 95]).reshape(6,-1)
print(new_array2)
In [32]: new_array3 = np.delete(new_array2, [1, 2, 3, 4, 5, 6]).reshape(4,-1)
print(new_array3)
In [33]: np.mean(new_array3)
Out[33]:
In [34]: np.median(new_array3)
Out[34]:
In [35]: np.std(new_array3)
Out[35]:
In [36]: np.linspace(0,10,21, dtype = float) #array of evenly spaced values (samples)
Out[36]:
In [37]: np.full((3,4),8)
Out[37]:
In [38]: np.eye(9)
Out[38]:
In [39]: a = np.array([[3,5],
[6,0]])
b = np.array([[2,4],
[3,8]])
print(a-b)
print("n",np.subtract(a,b))
In [40]: a = np.array([[3,5],
[6,0]])
b = np.array([[2,4],
[3,8]])
print(a+b)
print("n",np.add(a,b))
In [41]: a = np.array([[3,5,7],
[6,0,9]])
b = np.array([[2,4,5],
[3,8,8]])
print(a*b)
print("n",np.multiply(a,b))
In [42]: a = np.array([[3,5,7],
[6,0,9]])
b = np.array([[2,4,5],
[3,8,8]])
# print(np.dot(a,b))
In [43]: b = b.reshape(3,2)
print(b)
print(np.dot(a,b))
In [44]: print(np.exp(b))
print(np.sqrt(b))
print(np.sin(b))
print(np.log(b))
In [45]: print(b.sum())
print(b.min())
b = np.array([[7,4,5],
[10,6,8],
[4,9,5],])
print(b.min(axis=0))
minv = b.min(axis=1)
minv = minv.reshape(1,3)
minv
Out[45]:
In [46]: b = np.array([[9,4,5],
[5,9,8],
[7,3,5],])
b.sort()
print(b)
In [47]: b = np.array([[9,0,5],
[5,3,8],
[7,3,1]])
b.sort(axis=1)
print(b)
In [48]: b = np.array([[9,0,5],
[5,3,8],
[7,3,1]])
b.sort(axis=1)
print(b)
In [49]: a = np.array([[3,5,7],
[6,0,9]])
b = np.array([[2,4,5],
[3,8,8],
[4,6,8]])
X = np.concatenate((a,b))
X
Out[49]:
In [50]: c = np.array([[2,4],
[3,8],
[4,6]])
Y = np.concatenate((X,c))
In [51]: print("X:n",X)
print("na: n",a)
print("nb:n",b)
print("nc:n",c)
In [52]: np.concatenate((b,c),axis=1)
Out[52]:
In [53]: np.vstack((X,a))
Out[53]:
In [54]: np.hstack((b,c))
Out[54]:
In [55]: print(X)
print(np.hsplit(X,3))
print(np.hsplit(X,3)[0])
print(np.vsplit(X,5))
print(np.vsplit(X,5)[3])
In [56]: import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("XY-Plot")
plt.show()
In [57]: x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.plot(x, y)
plt.grid()
plt.show()
In [58]: import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Y")
plt.show()
In [59]: import matplotlib.pyplot as plt
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linestyle = 'dotted')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Y")
plt.show()
In [60]: #plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
In [61]: pip install numpy matplotlib opencv-python
In [1]: import numpy as np
import matplotlib.pyplot as plt
import cv2
In [2]: import matplotlib
print(np.__version__)
print(matplotlib.__version__)
print(cv2.__version__)
import matplotlib.pyplot as plt
In [3]: img = cv2.imread('F:/image.jpg')
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
In [4]: import cv2
from IPython import display
# Load an image using cv2.imread
img = cv2.imread('F:/image.jpg')
# Save the image to a file using cv2.imwrite
cv2.imwrite('F:/hello.jpg', img)
# Display the image using IPython.display.Image
display.Image('F:/hello.jpg')
Out[4]:
In [5]: img
Out[5]:
In [6]: r = img[:,:,0]
r.shape
Out[6]:
In [7]: r
Out[7]:
In [8]: # gray_value = 0.299 * R + 0.587 * G + 0.114 * B
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
In [9]: # HSV (Hue-Saturation-Value) color space:
hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imwrite('F:/hsv.jpg', hsv_image)
display.Image('F:/hsv.jpg')
Out[9]:
In [16]: # LAB (Luminance-a-b) color space:
lab_image = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
# Save the image to a file using cv2.imwrite
cv2.imwrite("F:/lab_image.jpg", lab_image)
display.Image("F:/lab_image.jpg")
Out[16]:
In [17]: # YCrCb (Luma-Chroma-blue-Chroma-red) color space:
ycrcb_image = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
# Save the image to a file using cv2.imwrite
cv2.imwrite("F:/ycrcb_image.jpg", ycrcb_image)
display.Image("F:/ycrcb_image.jpg")
Out[17]:
In [18]: gray
Out[18]:
In [19]: gray.shape
Out[19]:
In [20]: resized = cv2.resize(img, (1000, 1000))
In [21]: resized.shape
Out[21]:
In [22]: cv2.imwrite('F:/gray.jpg', gray)
cv2.imwrite('F:/resized.jpg', resized)
Out[22]:
In [23]: display.Image('F:/gray.jpg')
Out[23]:
In [24]: cv2.imwrite('F:/r.jpg', r)
display.Image('F:/r.jpg')
Out[24]:
In [25]: display.Image('F:/resized.jpg')
Out[25]:
In [26]: img.shape
Out[26]:
In [27]: gray.shape
Out[27]:
In [28]: resized.shape
Out[28]: