0% found this document useful (0 votes)
6 views2 pages

Image Processing and ML Techniques

The document contains Python code for two main tasks: image recoloring using KMeans clustering and a machine learning model for classifying animal images using a neural network. It includes data preprocessing, model training, evaluation, and visualization of results. Additionally, it demonstrates the use of libraries such as OpenCV, TensorFlow, and scikit-learn for image processing and machine learning tasks.

Uploaded by

SHRIGAYATHRI S
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)
6 views2 pages

Image Processing and ML Techniques

The document contains Python code for two main tasks: image recoloring using KMeans clustering and a machine learning model for classifying animal images using a neural network. It includes data preprocessing, model training, evaluation, and visualization of results. Additionally, it demonstrates the use of libraries such as OpenCV, TensorFlow, and scikit-learn for image processing and machine learning tasks.

Uploaded by

SHRIGAYATHRI S
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

1. import numpy as np 2.

import numpy as np
import cv2 import pandas as pd
from [Link] import KMeans import [Link] as plt
import [Link] as plt from [Link] import fetch_california_housing
def vectorize_image(image_path, k=5): from sklearn.model_selection import train_test_split
image = [Link](image_path) from [Link] import StandardScaler
image = [Link](image, cv2.COLOR_BGR2RGB) from sklearn.linear_model import LinearRegression
pixels = [Link]((-1, 3)) from [Link] import mean_squared_error, r2_score
kmeans = KMeans(n_clusters=k, random_state=42, housing = fetch_california_housing()
n_init=10) df = [Link]([Link],
[Link](pixels) columns=housing.feature_names)
recolored_pixels = df['PRICE'] = [Link]
kmeans.cluster_centers_[kmeans.labels_] X = [Link](columns=['PRICE']) y = df['PRICE']
recolored_image = X_train, X_test, y_train, y_test = train_test_split(X, y,
recolored_pixels.reshape([Link]).astype(np.uint8) test_size=0.2, random_state=42)
return image, recolored_image scaler = StandardScaler()
def display_images(original, recolored): X_train = scaler.fit_transform(X_train)
fig, ax = [Link](1, 2, figsize=(10, 5)) X_test = [Link](X_test)
ax[0].imshow(original) model = LinearRegression()
ax[0].set_title("Original Image") [Link](X_train, y_train)
ax[0].axis("off") y_pred = [Link](X_test)
ax[1].imshow(recolored) mse = mean_squared_error(y_test, y_pred)
ax[1].set_title("Recolored Image") r2 = r2_score(y_test, y_pred)
ax[1].axis("off") print(f"Mean Squared Error: {mse}")
[Link]() print(f"R^2 Score: {r2}")
image_path = "[Link]" [Link](y_test, y_pred, alpha=0.7)
original, recolored = vectorize_image(image_path, k=5) [Link]("Actual Prices")
display_images(original, recolored) [Link]("Predicted Prices")
[Link]("Actual vs Predicted House Prices") [Link]()

3. import tensorflow as tf 4 . import tensorflow as tf


from [Link] import Sequential from tensorflow import keras
from [Link] import Dense, Flatten from [Link] import layers, models
from [Link] import mnist from [Link] import ResNet50
import [Link] as plt import numpy as np
import numpy as np import [Link] as plt
(x_train, y_train), (x_test, y_test) = mnist.load_data() (x_train, y_train), (x_test, y_test) =
x_train, x_test = x_train / 255.0, x_test / 255.0 [Link].cifar10.load_data()
model = Sequential([Flatten(input_shape=(28, 28)), labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog',
Dense(128, activation='relu'),Dense(64, activation='relu'), 'frog', 'horse', 'ship', 'truck']
Dense(10, activation='softmax')]) animals = [2, 3, 4, 5, 6, 7]
[Link](optimizer='adam', mask = lambda data, classes: [Link](data, classes).flatten()
loss='sparse_categorical_crossentropy', x_train, y_train = x_train[mask(y_train, animals)],
metrics=['accuracy']) y_train[mask(y_train, animals)]
[Link](x_train, y_train, epochs=10, x_test, y_test = x_test[mask(y_test, animals)],
validation_data=(x_test, y_test)) y_test[mask(y_test, animals)]
test_loss, test_acc = [Link](x_test, y_test) x_train, x_test = x_train / 255.0, x_test / 255.0
print(f"Test accuracy: {test_acc:.4f}") num_classes = len(animals)
predictions = [Link](x_test) y_train = [Link].to_categorical([[Link](y) for y
def display_predictions(images, labels, predictions, in y_train], num_classes)
num=5):[Link](figsize=(10, 5)) y_test = [Link].to_categorical([[Link](y) for y
for i in range(num): [Link](1, num, i+1) in y_test], num_classes)
[Link](images[i], cmap='gray') datagen = [Link](
[Link]('off') rotation_range=20, width_shift_range=0.2,
predicted_label = [Link](predictions[i]) height_shift_range=0.2,
actual_label = labels[i] horizontal_flip=True, zoom_range=0.2)
[Link](f"Pred: {predicted_label}\nActual: [Link](x_train)
{actual_label}")[Link]() model = [Link]([
display_predictions(x_test, y_test, predictions) ResNet50(weights='imagenet', include_top=False,
input_shape=(32, 32, 3), trainable=False),
layers.GlobalAveragePooling2D(),
[Link](256, activation='relu'),
[Link](),
[Link](0.4),
[Link](num_classes, activation='softmax')
])
[Link](optimizer=[Link](learning
_rate=1e-4),
loss='categorical_crossentropy',
metrics=['accuracy'])
lr_scheduler =
[Link](monitor='val_loss',
factor=0.5, patience=3, verbose=1)
[Link]([Link](x_train, y_train, batch_size=64),
validation_data=(x_test, y_test), epochs=40,
callbacks=[lr_scheduler])
loss, acc = [Link](x_test, y_test, verbose=2)
print(f"Test Accuracy: {acc * 100:.2f}%")
[Link]("optimized_animal_classifier.keras")
pred = [Link]([Link](x_test), axis=1)
actual = [Link](y_test, axis=1)
correct_indices = [Link](pred == actual)[0][:4]
def display_correct_preds(images, actual, pred, labels,
indices):
[Link](figsize=(10, 5))
for i, idx in enumerate(indices):
[Link](1, 4, i + 1)
[Link](images[idx])
[Link]('off')
[Link](f"Predicted: {labels[animals[actual[idx]]]}",
color='green')
[Link]()
display_correct_preds(x_test, actual, pred, labels,
correct_indices)

You might also like