Exp 1
Exp 1
img = cv.imread('fruits.jpeg')
cv2_imshow(img)
print("Image Properties")
print("- Number of Pixels: " + str(img.size))
print("- Shape/Dimensions: " + str(img.shape))
Image Properties
- Number of Pixels: 2469600
- Shape/Dimensions: (686, 1200, 3)
, (width, height))
cv2_imshow(img_translation)
EXPERIMENT-2
import numpy as np
import matplotlib.pyplot as plt
import cv2
<matplotlib.image.AxesImage at 0x7e05c80f7400>
<matplotlib.image.AxesImage at 0x7e05ae956f20>
image=cv2.imread('dog.jpg')
img_grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh=100
ret, thresh_img=cv2.threshold(img_grey, thresh,255,cv2.THRESH_BINARY)
contours, hierarchy=cv2.findContours(thresh_img,cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
img_contours = np.zeros(image.shape)
cv2.drawContours(img_contours, contours, -1, (0, 255, 0), 3)
cv2.imwrite('contours.jpg', img_contours)
plt.imshow(img_contours)
<matplotlib.image.AxesImage at 0x7e05ae54cf70>
image=cv2.imread("dog.jpg",cv2.IMREAD_UNCHANGED)
position= (10,50)
cv2.putText(image, "This is a Dog in
Nature",position,cv2.FONT_HERSHEY_SIMPLEX, 1,(0, 150, 255),2,cv2.LINE_AA)
cv2.imwrite('output.jpg', image)
plt.imshow(image)
<matplotlib.image.AxesImage at 0x7e05ae5ed870>
EXPERIMENT-3
Program to perform bit plane slicing of a grayscale image.
#BIT SLICING
import numpy as np
import cv2
import random
import matplotlib.pyplot as plt
img1=cv2.imread("/content/gray.jpeg", cv2.IMREAD_GRAYSCALE)
c=np.array(img1.data)
plt.subplot(2,5,1)
plt.title('ORIGINAL')
plt.imshow(c, cmap='gray')
finalImage=[[0 for i in range(c.shape[1])]for j in range(c.shape[0])]
for k in range(8):
bitPlane=[]
for i in range(c.shape[0]):
a=[]
for j in range(c.shape[1]):
if c[i][j]%2 == 1:
a.append(255)
else:
a.append (0)
c[i][j]=c[i][j]/2
bitPlane. append (a)
img=np.array(bitPlane)
for i in range(c.shape[0]):
for j in range(c.shape[1]):
if img[i][j] == 255:
finalImage[i][j] = finalImage[i][j] + np.power(2, k)
plt. subplot (2,5,k+2)
plt.title('BP-'+str(k))
plt.imshow(img, cmap='gray')
fimg=np.array (finalImage)
plt.subplot (2,5,10)
plt.imshow (fimg, cmap='gray')
plt.title('RECONSTRUCTED')
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.50,
wspace=0.92)
plt. show()
2. Write a program to display the use of:
Write a program for showing the edge detection using derivative filter mask.
import numpy as np
import matplotlib.pyplot as plt
# Load the image in grayscale
img = cv2.imread('/content/lion.jpg', cv2.IMREAD_GRAYSCALE)
ing = np.array(img)
# plt.subplot(1, 3, 1)
# plt.title("ORIGINAL")
# plt.imshow(ing, cmap='gray')
# plt.show()
# Define kernels
sobelGx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
sobelGy = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
prewittGx = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
prewittGy = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])
laplacianG = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
# Pad the image
ing = np.pad(ing, pad_width=1, mode='constant', constant_values=0)
# Convolution with kernels
sobelx = np.zeros_like(ing)
sobely = np.zeros_like(ing)
prewittx = np.zeros_like(ing)
prewitty = np.zeros_like(ing)
laplacian = np.zeros_like(ing)
for i in range(ing.shape[0] - 2):
for j in range(ing.shape[1] - 2):
sobelx[i + 1][j + 1] = np.sum(np.multiply(sobelGx, ing[i:i + 3, j:j + 3]))
sobely[i + 1][j + 1] = np.sum(np.multiply(sobelGy, ing[i:i + 3, j:j + 3]))
prewittx[i + 1][j + 1] = np.sum(np.multiply(prewittGx, ing[i:i + 3, j:j + 3]))
prewitty[i + 1][j + 1] = np.sum(np.multiply(prewittGy, ing[i:i + 3, j:j + 3]))
laplacian[i + 1][j + 1] = np.sum(np.multiply(laplacianG, ing[i:i + 3, j:j + 3]))
coins = data.coins()
hist, _ = np.histogram(coins, bins=np.arange(0, 256))
fig, ax1 = plt.subplots()
ax1.imshow(coins, cmap=plt.cm.gray, interpolation='nearest')
edges = canny(coins/255.)
fig, ax2 = plt.subplots(figsize=(4, 3))
ax2.imshow(edges, cmap=plt.cm.gray, interpolation='nearest')
ax2.axis('off')
ax2.set_title('Canny detector')
plt.show()
from scipy import ndimage as ndi
import matplotlib.pyplot as plt
from skimage import data
from skimage.feature import canny
coins = data.coins()
edges = canny(coins/255.)
fill_coins = ndi.binary_fill_holes(edges)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(fill_coins, cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
ax.set_title('Filling the holes')
plt.show()
4. Write a program for object detection using Histogram of Oriented Gradients (HOG).
#importing required libraries
from skimage.io import imread, imshow
from skimage.transform import resize
from skimage.feature import hog
from skimage import exposure
import matplotlib.pyplot as plt
%matplotlib inline
img = cv2.imread('pikachu.jpg')
imshow(img)
print(img.shape)
#resizing image
resized_img = resize(img, (128, 64))
imshow(resized_img)
print(resized_img.shape) (182, 182, 3)(128, 64, 3)
Experiment-8
1. Write a program for face detection using Haar Cascade Library.
import cv2
import numpy as np
%matplotlib inline
from matplotlib import pyplot as plt
import pylab
pylab.rcParams['figure.figsize']=(10.0,8.0)
base_image=cv2.imread("/content/NASA_Astronaut_Group_15.jpg")
grey=cv2.cvtColor(base_image,cv2.COLOR_BGR2GRAY)
plt.imshow(cv2.cvtColor(base_image, cv2.COLOR_BGR2RGB))
<matplotlib.image.AxesImage at 0x7f59fe3162f0>
<matplotlib.image.AxesImage at 0x7f5a10c983a0>
import cv2
import numpy as np
import pandas as pd
from google.colab.patches import cv2_imshow # for image display
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
img = cv2.imread("/content/NASA_Astronaut_Group_15.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.05, minNeighbors=5)
for x, y, w, h in faces:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
resized = cv2.resize(img, (int(img.shape[1] / 1), int(img.shape[0] / 1)))
cv2_imshow(resized)
import cv2
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
# Load the image
image1 = cv2.imread('/content/AI_man.jpg')
# Convert the training image to RGB
training_image = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
# Convert the training image to grayscale
training_gray = cv2.cvtColor(training_image, cv2.COLOR_RGB2GRAY)
# Create test image by adding Scale Invariance and Rotational Invariance
test_image = cv2.pyrDown(training_image)
test_image = cv2.pyrDown(test_image)
num_rows, num_cols = test_image.shape[:2]
rotation_matrix = cv2.getRotationMatrix2D((num_cols/2, num_rows/2), 30, 1)
test_image = cv2.warpAffine(test_image, rotation_matrix, (num_cols, num_rows))
test_gray = cv2.cvtColor(test_image, cv2.COLOR_RGB2GRAY)
# Display training image and testing image
fig, plots = plt.subplots(1, 2, figsize=(20,10))
plots[0].set_title("Training Image")
plots[0].imshow(training_image)
plots[1].set_title("Testing Image")
plots[1].imshow(test_image)
<matplotlib.image.AxesImage at 0x7f5a10ac9f60>
# Detect Key Points and Descriptor
sift = cv2.xfeatures2d.SIFT_create()
train_keypoints, train_descriptor = sift.detectAndCompute(training_gray, None)
test_keypoints, test_descriptor = sift.detectAndCompute(test_gray, None)
keypoints_without_size = np.copy(training_image)
keypoints_with_size = np.copy(training_image)
cv2.drawKeypoints(training_image, train_keypoints, keypoints_without_size, color=(255, 0))
cv2.drawKeypoints(training_image, train_keypoints, keypoints_with_size,
flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# Display image
plt.figure(figsize=(20,10))
plt.subplot(1,2,1)
plt.title("Train keypoints With Size")
plt.imshow(keypoints_with_size, cmap='Reds')
plt.subplot(1,2,2)
plt.title("Train keypoints Without Size")
plt.imshow(keypoints_without_size, cmap='Reds')
# Print the number of keypoints detected in the training image
print("Number of Keypoints Detected In The Training Image: ", len(train_keypoints))
# Print the number of keypoints detected in the query image
print("Number of Keypoints Detected In The Query Image: ", len(test_keypoints))
Number of Matching Keypoints Between The Training and Query Images: 6579
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
# matplotlib inline
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
df.head()
features
y = df.loc[:, ["target"]].values
x = StandardScaler().fit_transform(x)
pd.DataFrame(data=x, columns=features).head()
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(x)
principaldf = pd.DataFrame(data=principalComponents, columns=['principal component 1', 'principal component
2'])
principaldf.head()
df['target'].head()
0 Iris-setosa
1 Iris-setosa
2 Iris-setosa
3 Iris-setosa
4 Iris-setosa
Name: target, dtype: object
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_title('Principal Component Analysis', fontsize=15)
ax.set_xlabel("Principal Component 1", fontsize=15)
ax.set_ylabel("Principal Component 2", fontsize=15)
dataset.head()
X = dataset.loc[:, 'Class']
y = dataset['Class']
# Now, X_train contains the principal components, and y_train contains the class labels
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(max_depth=2, random_state=0)
classifier.fit(X_train, y_train)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
[[5 0 0]
[0 3 3]
[0 0 4]]
explained_variance_ratio = pca.explained_variance_ratio_
[[1 0 4]
[2 0 4]
[0 0 4]]
4. Write a program to implement Image reconstruction with the help of auto encoders.
import keras
from tensorflow.keras import callbacks
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Dense, Input
#from keras.initializers import VarianceScaling
#from keras.engine.topology import Layer, InputSpec
#from sklearn.metrics import accuracy_score, normalized_mutual_info_score
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
# Defining input placeholder for autoencoder model
input_img = Input(shape=(784,))
# Encoded representation of the input
enc_rep = Dense(2000, activation='relu')(input_img)
enc_rep = Dense(500, activation='relu')(enc_rep)
enc_rep = Dense(500, activation='relu')(enc_rep)
enc_rep = Dense(10, activation='sigmoid')(enc_rep)
# Lossy reconstruction of the input from encoded representation
decoded = Dense(500, activation='relu')(enc_rep)
decoded = Dense(500, activation='relu')(decoded)
decoded = Dense(2000, activation='relu')(decoded)
decoded = Dense(784)(decoded)
# This model maps an input to its reconstruction
autoencoder = Model(input_img, decoded)
autoencoder.summary()
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 784)] 0
=================================================================
Total params: 5652794 (21.56 MB)
Trainable params: 5652794 (21.56 MB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
Epoch 108/108
30/30 [==============================] - 37s 1s/step - loss: 0.0111 - val_loss: 0.0117
To predict images
[1 0 2 1 1 0 1 2 2 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0]
0.9666666666666667
<matplotlib.collections.PathCollection at 0x7898df325840>
X = bankdata.drop('Class', axis=1)
y = bankdata['Class']
SVC(kernel='linear')
y_pred = svclassifier.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
[[147 2]
[ 2 124]]
precision recall f1-score support
Gaussian Kernel
from sklearn.svm import SVC
svclassifier = SVC(kernel='rbf')
svclassifier.fit(X_train,y_train)
SVC()
y_pred=svclassifier.predict(X_test)
svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)
[[ 8 0 0]
[ 0 15 0]
[ 0 0 7]]
precision recall f1-score support
accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
Sigmoidal Kernel
from sklearn.svm import SVC
svclassifier = SVC(kernel='sigmoid')
svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)
[[ 0 0 8]
[ 0 0 15]
[ 0 0 7]]
precision recall f1-score support
accuracy 0.23 30
macro avg 0.08 0.33 0.13 30
weighted avg 0.05 0.23 0.09 30