0% found this document useful (0 votes)
5 views30 pages

PRCV

The document outlines nine different programming tasks, each with a specific aim and corresponding code implementation. Tasks include computing Gaussian distributions, implementing gradient descent, linear regression, comparing SVM and CNN classification accuracy, basic image processing, geometric transformations, perspective transformations, camera calibration, and computing the fundamental matrix. Each program is accompanied by Python code that demonstrates the respective functionality.

Uploaded by

girirajchopra1
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)
5 views30 pages

PRCV

The document outlines nine different programming tasks, each with a specific aim and corresponding code implementation. Tasks include computing Gaussian distributions, implementing gradient descent, linear regression, comparing SVM and CNN classification accuracy, basic image processing, geometric transformations, perspective transformations, camera calibration, and computing the fundamental matrix. Each program is accompanied by Python code that demonstrates the respective functionality.

Uploaded by

girirajchopra1
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

PROGRAM NO.

Aim: Write a MATLAB/Python function that computes the value of the Gaussian
distribution N(m,s) at given vector X and plot the effect of varying mean and
variance to the normal distribution.

Code:
import numpy as np

import [Link] as plt

def gaussian_pdf(x, mean, std):

"""

Computes the Gaussian distribution N(mean, std) for vector x.

"""

coeff = 1 / (std * [Link](2 * [Link]))

exponent = [Link](-0.5 * ((x - mean) / std) ** 2)

return coeff * exponent

# Generate vector X

x = [Link](-10, 10, 500)

# Different means and standard deviations

means = [0, 2, -3]

stds = [0.5, 1, 2]

[Link](figsize=(10, 6))

# Plot varying means (fixed std)

for m in means:
[Link](x, gaussian_pdf(x, m, 1), label=f"mean={m}, std=1")

# Plot varying std (fixed mean)

for s in stds:

[Link](x, gaussian_pdf(x, 0, s), linestyle='--', label=f"mean=0, std={s}")

[Link]("Effect of Varying Mean and Variance on Gaussian Distribution")

[Link]("x")

[Link]("Probability Density")

[Link]()

[Link](True)

[Link]()
Output:
PROGRAM NO.2

Aim: Implementation of Gradient descent.


Code:
import numpy as np

import [Link] as plt

def gradient_descent(learning_rate=0.1, iterations=50, start_point=10):

"""

Implements gradient descent to minimize f(x) = x^2.

"""

x = start_point

history = [x]

for i in range(iterations):

grad = 2 * x # derivative of f(x) = x^2

x = x - learning_rate * grad

[Link](x)

return [Link](history)

# Parameters

lr = 0.1

iters = 25

x_vals = [Link](-12, 12, 400)

y_vals = x_vals ** 2
# Run Gradient Descent

trajectory = gradient_descent(learning_rate=lr, iterations=iters, start_point=10)

# Plot the function and descent path

[Link](figsize=(8,6))

[Link](x_vals, y_vals, label="f(x) = x²", color='blue')

[Link](trajectory, trajectory**2, color='red', label="Gradient Descent Steps")

[Link]("Gradient Descent on f(x) = x²")

[Link]("x")

[Link]("f(x)")

[Link]()

[Link](True)

[Link]()

print("Final minimum found near x =", trajectory[-1])


Output:
PROGRAM NO.3

Aim: Implementation of Linear Regression using Gradient descent.


Code:
import numpy as np

import [Link] as plt

# Generate dummy data

[Link](42)

X = [Link](0, 10, 100)

y = 2.5 * X + [Link](100) * 2 + 1 # true slope=2.5, intercept=1

def gradient_descent_linear_regression(X, y, lr=0.01, iterations=1000):

n = len(X)

m, c = 0, 0 # initial parameters

cost_history = []

for i in range(iterations):

y_pred = m * X + c

error = y_pred - y

# Compute gradients

dm = (1/n) * [Link](error, X)

dc = (1/n) * [Link](error)

# Update parameters
m -= lr * dm

c -= lr * dc

# Compute and store cost

cost = (1/(2*n)) * [Link](error ** 2)

cost_history.append(cost)

return m, c, cost_history

# Run gradient descent

m, c, cost_history = gradient_descent_linear_regression(X, y, lr=0.01, iterations=1000)

# Predicted line

y_pred = m * X + c

# Plot

[Link](figsize=(8,6))

[Link](X, y, label='Data Points', alpha=0.7)

[Link](X, y_pred, color='red', label=f'Regression Line (m={m:.2f}, c={c:.2f})')

[Link]("Linear Regression using Gradient Descent")

[Link]("X")

[Link]("y")

[Link]()

[Link](True)

[Link]()
# Plot cost over iterations

[Link](figsize=(8,5))

[Link](cost_history)

[Link]("Cost Function over Iterations")

[Link]("Iterations")

[Link]("Cost (MSE)")

[Link](True)

[Link]()

print(f"Final parameters: m = {m:.4f}, c = {c:.4f}")


Output:
PROGRAM NO.4

Aim: Comparison of classification accuracy of SVM and CNN for the dataset.
Code:
from [Link] import load_digits

from sklearn.model_selection import train_test_split

from sklearn import svm

from [Link] import accuracy_score

from [Link] import Sequential

from [Link] import Dense, Flatten

from [Link] import to_categorical

import numpy as np

# Load digits dataset (8x8 images)

digits = load_digits()

X = [Link] / 16.0

y = [Link]

# Split dataset

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# ----- SVM -----

X_train_flat = X_train.reshape(len(X_train), -1)

X_test_flat = X_test.reshape(len(X_test), -1)

print("Training SVM...")

svm_model = [Link](kernel='linear')
svm_model.fit(X_train_flat, y_train)

y_pred_svm = svm_model.predict(X_test_flat)

svm_acc = accuracy_score(y_test, y_pred_svm)

# ----- CNN -----

X_train_cnn = X_train.reshape(-1, 8, 8, 1)

X_test_cnn = X_test.reshape(-1, 8, 8, 1)

y_train_cat = to_categorical(y_train)

y_test_cat = to_categorical(y_test)

cnn_model = Sequential([

Flatten(input_shape=(8,8,1)),

Dense(64, activation='relu'),

Dense(10, activation='softmax')

])

cnn_model.compile(optimizer='adam',

loss='categorical_crossentropy', metrics=['accuracy'])

cnn_model.fit(X_train_cnn, y_train_cat, epochs=10, batch_size=32, verbose=0)

cnn_acc = cnn_model.evaluate(X_test_cnn, y_test_cat, verbose=0)[1]

print("\n================== Model Comparison ==================")

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

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


Output:
PROGRAM NO.5

Aim: Implementation basic Image Handling and processing operations on the


image.

Code:
# ============================================================

# Basic Image Handling and Processing Operations

# ============================================================

import cv2

import numpy as np

import [Link] as plt

# 1. Load an image

import os

img_path = '/kaggle/input/sample-image/[Link]' # change if needed

if not [Link](img_path):

# create a dummy image (solid color with circle)

img = [Link]((300, 300, 3), dtype=np.uint8)

[Link](img, (150, 150), 80, (0, 255, 0), -1)

else:

img = [Link](img_path)

# Convert BGR (OpenCV default) to RGB for displaying with matplotlib

img_rgb = [Link](img, cv2.COLOR_BGR2RGB)


# -------------------------------

# 2. Convert to grayscale

# -------------------------------

gray = [Link](img, cv2.COLOR_BGR2GRAY)

# -------------------------------

# 3. Resize

# -------------------------------

resized = [Link](img_rgb, (150, 150))

# -------------------------------

# 4. Rotate

# -------------------------------

(h, w) = img_rgb.shape[:2]

center = (w // 2, h // 2)

M = cv2.getRotationMatrix2D(center, 45, 1.0) # rotate by 45 degrees

rotated = [Link](img_rgb, M, (w, h))

# -------------------------------

# 5. Flip (horizontal)

# -------------------------------

flipped = [Link](img_rgb, 1)

# -------------------------------

# 6. Draw shapes & text


# -------------------------------

drawn = img_rgb.copy()

[Link](drawn, (30, 30), (120, 120), (255, 0, 0), 2)

[Link](drawn, 'OpenCV', (50, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2)

# 7. Edge Detection (Canny)

edges = [Link](gray, 100, 200)

titles = [

'Original', 'Grayscale', 'Resized', 'Rotated',

'Flipped', 'Shapes + Text', 'Edges (Canny)'

images = [img_rgb, gray, resized, rotated, flipped, drawn, edges]

[Link](figsize=(12, 8))

for i in range(len(images)):

[Link](2, 4, i + 1)

cmap = 'gray' if len(images[i].shape) == 2 else None

[Link](images[i], cmap=cmap)

[Link](titles[i])

plt.tight_layout()

[Link]()
Output:
PROGRAM NO.6

Aim: Implementation of Geometric Transformation.


Code:
import cv2

import numpy as np

import [Link] as plt

img = [Link]("/kaggle/input/sample/single-fresh-red-strawberry-on-table-green-background-
[Link]")

img_rgb = [Link](img, cv2.COLOR_BGR2RGB)

h, w = img_rgb.shape[:2]

M_translate = np.float32([[1, 0, 50], [0, 1, 30]])

translated = [Link](img_rgb, M_translate, (w, h))

M_rotate = cv2.getRotationMatrix2D((w/2, h/2), 45, 1)

rotated = [Link](img_rgb, M_rotate, (w, h))

scaled = [Link](img_rgb, None, fx=1.5, fy=1.5, interpolation=cv2.INTER_LINEAR)

pts1 = np.float32([[50, 50], [200, 50], [50, 200]])

pts2 = np.float32([[10, 100], [200, 50], [100, 250]])

M_shear = [Link](pts1, pts2)

sheared = [Link](img_rgb, M_shear, (w, h))


reflected = [Link](img_rgb, 1)

titles = ['Original', 'Translated', 'Rotated', 'Scaled', 'Sheared', 'Reflected']

images = [img_rgb, translated, rotated, scaled, sheared, reflected]

[Link](figsize=(12, 8))

for i in range(len(images)):

[Link](2, 3, i+1)

[Link](images[i])

[Link](titles[i])

[Link]('off')

plt.tight_layout()

[Link]()
Output:
PROGRAM NO.7

Aim: Implementation of Perspective Transformation.


Code:
import cv2

import numpy as np

import [Link] as plt

img = [Link]("/kaggle/input/sample/single-fresh-red-strawberry-on-table-green-background-
[Link]")

img_rgb = [Link](img, cv2.COLOR_BGR2RGB)

h, w = img_rgb.shape[:2]

pts1 = np.float32([[50, 50], [w-50, 50], [50, h-50], [w-50, h-50]])

pts2 = np.float32([[10, 100], [w-100, 50], [100, h-100], [w-50, h-50]])

M = [Link](pts1, pts2)

perspective = [Link](img_rgb, M, (w, h))

[Link](figsize=(10, 6))

[Link](1, 2, 1)

[Link](img_rgb)

[Link]('Original Image')

[Link]('off')

[Link](1, 2, 2)

[Link](perspective)

[Link]('Perspective Transformed Image')

[Link]('off')

plt.tight_layout()

[Link](
Output:
PROGRAM NO.8

Aim: Implementation of Camera Calibration


Code:
# Import required modules

import cv2

import numpy as np

import os

import glob

# Define the dimensions of checkerboard

CHECKERBOARD = (6, 9)

# stop the iteration when specified

# accuracy, epsilon, is reached or

# specified number of iterations are completed.

criteria = (cv2.TERM_CRITERIA_EPS +

cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# Vector for 3D points

threedpoints = []

# Vector for 2D points


twodpoints = []

# 3D points real world coordinates

objectp3d = [Link]((1, CHECKERBOARD[0]

* CHECKERBOARD[1],

3), np.float32)

objectp3d[0, :, :2] = [Link][0:CHECKERBOARD[0],

0:CHECKERBOARD[1]].[Link](-1, 2)

prev_img_shape = None

# Extracting path of individual image stored

# in a given directory. Since no path is

# specified, it will take current directory

# jpg files alone

images = [Link]('*.jpg')

for filename in images:

image = [Link](filename)

grayColor = [Link](image, cv2.COLOR_BGR2GRAY)

# Find the chess board corners

# If desired number of corners are

# found in the image then ret = true


ret, corners = [Link](

grayColor, CHECKERBOARD,

cv2.CALIB_CB_ADAPTIVE_THRESH

+ cv2.CALIB_CB_FAST_CHECK +

cv2.CALIB_CB_NORMALIZE_IMAGE)

# If desired number of corners can be detected then,

# refine the pixel coordinates and display

# them on the images of checker board

if ret == True:

[Link](objectp3d)

# Refining pixel coordinates

# for given 2d points.

corners2 = [Link](

grayColor, corners, (11, 11), (-1, -1), criteria)

[Link](corners2)

# Draw and display the corners

image = [Link](image,

CHECKERBOARD,

corners2, ret)

[Link]('img', image)
[Link](0)

[Link]()

h, w = [Link][:2]

# Perform camera calibration by

# passing the value of above found out 3D points (threedpoints)

# and its corresponding pixel coordinates of the

# detected corners (twodpoints)

ret, matrix, distortion, r_vecs, t_vecs = [Link](

threedpoints, twodpoints, [Link][::-1], None, None)

# Displaying required output

print(" Camera matrix:")

print(matrix)

print("\n Distortion coefficient:")

print(distortion)

print("\n Rotation Vectors:")

print(r_vecs)

print("\n Translation Vectors:")

print(t_vecs)
Output:
PROGRAM NO.9

Aim: Compute fundamental matrix


Input:
import cv2

import numpy as np

import [Link] as plt

img1 = [Link]("/kaggle/input/sample/[Link]", cv2.IMREAD_GRAYSCALE)

img2 = [Link]("/kaggle/input/sample/[Link]", cv2.IMREAD_GRAYSCALE)

sift = cv2.SIFT_create()

kp1, des1 = [Link](img1, None)

kp2, des2 = [Link](img2, None)

bf = [Link]()

matches = [Link](des1, des2, k=2)

good = []

pts1 = []

pts2 = []

for m, n in matches:

if [Link] < 0.75 * [Link]:

[Link](m)

[Link](kp1[[Link]].pt)
[Link](kp2[[Link]].pt)

pts1 = np.int32(pts1)

pts2 = np.int32(pts2)

F, mask = [Link](pts1, pts2, cv2.FM_RANSAC)

pts1_inliers = pts1[[Link]() == 1]

pts2_inliers = pts2[[Link]() == 1]

print("Fundamental Matrix:\n", F)
Output:

You might also like