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

Pattern recognition

The document contains a series of Python programs demonstrating various data processing and machine learning techniques. Programs include Gaussian distribution plotting, gradient descent optimization, SVM and CNN model training on the Iris dataset, image manipulation using OpenCV, and camera calibration methods. Each program is self-contained and showcases different functionalities such as image transformations, corner detection, and pose estimation.

Uploaded by

piyushdemo48
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)
4 views

Pattern recognition

The document contains a series of Python programs demonstrating various data processing and machine learning techniques. Programs include Gaussian distribution plotting, gradient descent optimization, SVM and CNN model training on the Iris dataset, image manipulation using OpenCV, and camera calibration methods. Each program is self-contained and showcases different functionalities such as image transformations, corner detection, and pose estimation.

Uploaded by

piyushdemo48
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/ 10

Program 1

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

matplotlib.use("TkAgg")
def gaussian(x, mu, sigma):
return (1 / (np.sqrt(2 * np.pi * sigma ** 2))) * np.exp(-((x - mu) ** 2) / (2 * sigma ** 2))

x = np.linspace(-10, 10, 100)


plt.plot(x, gaussian(x, 0, 1), label="mu=0, sigma=1")
plt.plot(x, gaussian(x, 0, 2), label="mu=0, sigma=2")
plt.plot(x, gaussian(x, 2, 1), label="mu=2, sigma=1")
plt.legend()
plt.title("Gaussian Distribution with Different Mean and Variance")
plt.show()

OUTPUT:
Program 2

import numpy as np

def gradient(x):
return 2 * x
def gradient_descent(gradient, start, learn_rate, n_iter=50, tolerance=1e-06):
vector = start
for _ in range(n_iter):
diff = -learn_rate * gradient(vector)
if np.all(np.abs(diff) <= tolerance):
break
vector += diff # Update the parameter
return vector

start_point = 10 # Starting point for x


learning_rate = 0.1 # Learning rate
result = gradient_descent(gradient, start_point, learning_rate)

print(f"Optimized parameter: {result}")

OUTPUT:
Program 3

from sklearn import datasets


from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow.keras import layers, models

# Load dataset (e.g., Iris dataset)


iris = datasets.load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# SVM Model
svm = SVC(kernel='linear')
svm.fit(X_train, y_train)
svm_pred = svm.predict(X_test)
svm_acc = accuracy_score(y_test, svm_pred)

# CNN Model
X_train_reshaped = X_train.reshape((X_train.shape[0], 4, 1, 1))
X_test_reshaped = X_test.reshape((X_test.shape[0], 4, 1, 1))
cnn = models.Sequential([
layers.Conv2D(32, (2, 2), activation='relu', input_shape=(4, 1, 1)),
layers.Flatten(),
layers.Dense(3, activation='softmax')
])
cnn.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
cnn.fit(X_train_reshaped, y_train, epochs=5, verbose=1)
cnn_acc = cnn.evaluate(X_test_reshaped, y_test, verbose=0)[1]

# Output

print(f"SVM Accuracy: {svm_acc * 100:.2f}%")


print(f"CNN Accuracy: {cnn_acc * 100:.2f}%")
Program 4

from sklearn import datasets


from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow.keras import layers, models

# Load dataset (e.g., Iris dataset)


iris = datasets.load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# SVM Model
svm = SVC(kernel='linear')
svm.fit(X_train, y_train)
svm_pred = svm.predict(X_test)
svm_acc = accuracy_score(y_test, svm_pred)

# CNN Model
X_train_reshaped = X_train.reshape((X_train.shape[0], 4, 1, 1))
X_test_reshaped = X_test.reshape((X_test.shape[0], 4, 1, 1))
cnn = models.Sequential([
layers.Conv2D(32, (2, 2), activation='relu', input_shape=(4, 1, 1)),
layers.Flatten(),
layers.Dense(3, activation='softmax')
])
cnn.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
cnn.fit(X_train_reshaped, y_train, epochs=5, verbose=1)
cnn_acc = cnn.evaluate(X_test_reshaped, y_test, verbose=0)[1]

# Output
print(f"SVM Accuracy: {svm_acc * 100:.2f}%")
print(f"CNN Accuracy: {cnn_acc * 100:.2f}%")

Output:
SVM Accuracy: 96.67% CNN Accuracy: 100.00%
Program 5

from PIL import Image


import matplotlib.pyplot as plt
import matplotlib

# Set the interactive backend (if not set already)


matplotlib.use("TkAgg") # Or use "Qt5Agg" if available

# Load an image using Pillow


img = Image.open("example.jpg") # Replace with your image path

# Display the image using Matplotlib


plt.imshow(img)
plt.axis('off') # Hide axes
plt.show()

# Convert the image to grayscale using Pillow


gray_img = img.convert("L")

# Save the grayscale image


gray_img.save("gray_image.jpg")
print("Grayscale image saved as 'gray_image.jpg'")

Output:
Program 6

import cv2
import numpy as np

# Load image
img = cv2.imread("example.jpg")

# Scaling: Resize image


scaled_img = cv2.resize(img, None, fx=0.5, fy=0.5)

# Rotation: Rotate by 45 degrees


height, width = img.shape[:2]
M = cv2.getRotationMatrix2D((width / 2, height / 2), 45, 1)
rotated_img = cv2.warpAffine(img, M, (width, height))

# Translation: Move image by 50 pixels in both directions


M = np.float32([[1, 0, 50], [0, 1, 50]])
translated_img = cv2.warpAffine(img, M, (width, height))

# Display results
cv2.imshow("Scaled Image", scaled_img)
cv2.imshow("Rotated Image", rotated_img)
cv2.imshow("Translated Image", translated_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:
Program 7

import matplotlib
matplotlib.use("TkAgg")
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread("example.jpg")
if img is None:
print("Error: Image not loaded. Check the image path.")
exit()
pts1 = np.float32([[100, 100], [400, 100], [100, 400], [400, 400]])
pts2 = np.float32([[50, 50], [450, 50], [50, 450], [450, 450]])

M = cv2.getPerspectiveTransform(pts1, pts2)
perspective_img = cv2.warpPerspective(img, M, (500, 500))
perspective_img_rgb = cv2.cvtColor(perspective_img, cv2.COLOR_BGR2RGB)
plt.imshow(perspective_img_rgb)
plt.axis('off')
plt.show()

Output:
Program 8

import cv2
import numpy as np

img = cv2.imread('checkerboard1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
checkerboard_size = (9, 6) # Example: 9x6 inner corners
ret, corners = cv2.findChessboardCorners(gray, checkerboard_size, None)
if ret:
cv2.drawChessboardCorners(img, checkerboard_size, corners, ret)
cv2.imshow('Corners Detected', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Corners not detected")
img = cv2.imread('checkerboard1.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
corners = np.int0(corners)
for corner in corners:
x, y = corner.ravel()
cv2.circle(img, (x, y), 3, 255, -1)

cv2.imshow('Corners Detected', img)


cv2.waitKey(0)
cv2.destroyAllWindows()

Output:
Program 9

import cv2
import numpy as np

img1 = cv2.imread("checkerboard1.jpg", 0)
img2 = cv2.imread("example.jpg", 0)

orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)

bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)

pts1 = np.float32([kp1[m.queryIdx].pt for m in matches])


pts2 = np.float32([kp2[m.trainIdx].pt for m in matches])

F, mask = cv2.findFundamentalMat(pts1, pts2, cv2.FM_LMEDS)

print("Fundamental Matrix:", F)

Output:

Fundamental Matrix: [[-4.74963049e-07 1.54314551e-07 4.01422476e-05]


[-5.16450886e-06 7.58869561e-06 -4.19000405e-04]
[ 1.59047925e-02 -2.13641821e-02 1.00000000e+00]]

Process finished with exit code 0


Program 10

import cv2
import numpy as np
checkerboard_size = (9, 6)
obj_points = np.zeros((np.prod(checkerboard_size), 3), dtype=np.float32)
obj_points[:, :2] = np.indices(checkerboard_size).T.reshape(-1, 2)
cmera_matrix = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1]]) # Placeholder matrix
dist_coeffs = np.zeros((4, 1))
img = cv2.imread('checkerboard0.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, checkerboard_size, None)
if ret:
cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1),
criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30,
0.001))
cv2.drawChessboardCorners(img, checkerboard_size, corners, ret)
img_points = corners.reshape(-1, 2)
ret, rvec, tvec = cv2.solvePnP(obj_points, img_points, camera_matrix, dist_coeffs)
if ret:
axis = np.float32([[0, 0, 0], [3, 0, 0], [0, 3, 0], [0, 0, 3]]).reshape(-1, 3)
img_points, _ = cv2.projectPoints(axis, rvec, tvec, camera_matrix, dist_coeffs)
img = cv2.line(img, tuple(img_points[0].ravel()), tuple(img_points[1].ravel()), (0, 0, 255), 5)
img = cv2.line(img, tuple(img_points[0].ravel()), tuple(img_points[2].ravel()), (0, 255, 0), 5)
img = cv2.line(img, tuple(img_points[0].ravel()), tuple(img_points[3].ravel()), (255, 0, 0), 5)

cv2.imshow('Pose Estimation', img)


cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Checkerboard corners not found!")

Output:

You might also like