Load an image using matplotlib / PIL and convert it into a NumPy array.
Show that an image is
just a 2D (grayscale) or 3D (RGB) array.
from PIL import Image
import numpy as np
import [Link] as plt
image_path = "/content/[Link]"
img = [Link](image_path)
[Link](img)
[Link]('off')
[Link]("Original Image")
[Link]()
img_array = [Link](img)
print("Image array shape:", img_array.shape)
if len(img_array.shape) == 2:
print("This is a grayscale image (2D array).")
elif len(img_array.shape) == 3:
print("This is an RGB image (3D array).")
else:
print("Unknown image format.")
[Link](img_array)
[Link]('off')
[Link]("Image from NumPy array")
[Link]()
Image array shape: (675, 1200, 3)
This is an RGB image (3D array).
Take a 5×5 grayscale image and apply a 3×3 filter using nested loops. Try simple filters like edge
detection or blur. (without using Deep learning libraries)
import numpy as np
image = [Link]([
[10, 50, 80, 50, 10],
[60, 100, 150, 100, 60],
[90, 200, 255, 200, 90],
[60, 100, 150, 100, 60],
[10, 50, 80, 50, 10]
], dtype=np.float32)
print("Original Image:\n", image)
blur_filter = [Link]([
[1/9, 1/9, 1/9],
[1/9, 1/9, 1/9],
[1/9, 1/9, 1/9]
])
edge_filter = [Link]([
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
])
def apply_filter(image, filt):
img_height, img_width = [Link]
filt_height, filt_width = [Link]
pad = filt_height // 2
padded_image = [Link](image, pad, mode='constant',
constant_values=0)
output = np.zeros_like(image)
for i in range(img_height):
for j in range(img_width):
region = padded_image[i:i+filt_height, j:j+filt_width]
output[i, j] = [Link](region * filt)
return output
blurred_image = apply_filter(image, blur_filter)
edge_image = apply_filter(image, edge_filter)
print("\nBlurred Image:\n", blurred_image)
print("\nEdge Detection Image:\n", edge_image)
Original Image:
[[ 10. 50. 80. 50. 10.]
[ 60. 100. 150. 100. 60.]
[ 90. 200. 255. 200. 90.]
[ 60. 100. 150. 100. 60.]
[ 10. 50. 80. 50. 10.]]
Blurred Image:
[[ 24.444445 50. 58.88889 50. 24.444445]
[ 56.666668 110.55556 131.66667 110.55556 56.666668]
[ 67.77778 129.44444 150.55556 129.44444 67.77778 ]
[ 56.666668 110.55556 131.66667 110.55556 56.666668]
[ 24.444445 50. 58.88889 50. 24.444445]]
Edge Detection Image:
[[-130. 0. 190. 0. -130.]
[ 30. -95. 165. -95. 30.]
[ 200. 635. 940. 635. 200.]
[ 30. -95. 165. -95. 30.]
[-130. 0. 190. 0. -130.]]
-Build a CNN for MNIST / CIFAR-10 digit classification. (Conv -> ReLU -> MaxPool -> Dense ->
Softmax.)
-Compare CNN vs simple Dense NN on the same dataset.
-Visualize feature maps after the first conv layer.
import tensorflow as tf
from [Link] import layers, models
from [Link] import mnist
import [Link] as plt
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype('float32')/255.0
x_test = x_test.astype('float32')/255.0
x_train = x_train[..., [Link]]
x_test = x_test[..., [Link]]
y_train_cat = [Link].to_categorical(y_train, 10)
y_test_cat = [Link].to_categorical(y_test, 10)
dense_model = [Link]([
[Link](shape=(28,28,1)),
[Link](),
[Link](128, activation='relu'),
[Link](10, activation='softmax')
])
dense_model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
dense_history = dense_model.fit(x_train, y_train_cat, epochs=5,
batch_size=64,
validation_split=0.1)
dense_acc = dense_model.evaluate(x_test, y_test_cat, verbose=0)
print(f"\nDense NN Test Accuracy: {dense_acc[1]*100:.2f}%")
inputs = [Link](shape=(28,28,1))
x = layers.Conv2D(32, (3,3), activation='relu')(inputs)
x = layers.MaxPooling2D((2,2))(x)
x = layers.Conv2D(64, (3,3), activation='relu')(x)
x = layers.MaxPooling2D((2,2))(x)
x = [Link]()(x)
x = [Link](128, activation='relu')(x)
outputs = [Link](10, activation='softmax')(x)
cnn_model = [Link](inputs=inputs, outputs=outputs)
cnn_model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
cnn_history = cnn_model.fit(x_train, y_train_cat, epochs=5,
batch_size=64,
validation_split=0.1)
cnn_acc = cnn_model.evaluate(x_test, y_test_cat, verbose=0)
print(f"\nCNN Test Accuracy: {cnn_acc[1]*100:.2f}%")
first_conv_layer_model = [Link](inputs=cnn_model.input,
outputs=cnn_model.layers[1].output)
test_img = x_test[0:1]
feature_maps = first_conv_layer_model.predict(test_img)
num_filters = feature_maps.shape[-1]
[Link](figsize=(12,6))
for i in range(num_filters):
[Link](4, 8, i+1)
[Link](feature_maps[0,:,:,i], cmap='gray')
[Link]('off')
[Link]("Feature Maps after First Conv Layer")
[Link]()
Downloading data from [Link]
keras-datasets/[Link]
11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step
Epoch 1/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 5s 5ms/step - accuracy: 0.8498 - loss:
0.5422 - val_accuracy: 0.9588 - val_loss: 0.1486
Epoch 2/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 3s 4ms/step - accuracy: 0.9526 - loss:
0.1623 - val_accuracy: 0.9718 - val_loss: 0.1035
Epoch 3/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 3s 4ms/step - accuracy: 0.9689 - loss:
0.1062 - val_accuracy: 0.9723 - val_loss: 0.0931
Epoch 4/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 4s 5ms/step - accuracy: 0.9785 - loss:
0.0749 - val_accuracy: 0.9735 - val_loss: 0.0893
Epoch 5/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 3s 4ms/step - accuracy: 0.9833 - loss:
0.0598 - val_accuracy: 0.9755 - val_loss: 0.0834
Dense NN Test Accuracy: 97.56%
Epoch 1/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 47s 53ms/step - accuracy: 0.8815 - loss:
0.3965 - val_accuracy: 0.9863 - val_loss: 0.0531
Epoch 2/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 43s 51ms/step - accuracy: 0.9844 - loss:
0.0522 - val_accuracy: 0.9787 - val_loss: 0.0644
Epoch 3/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 83s 52ms/step - accuracy: 0.9885 - loss:
0.0355 - val_accuracy: 0.9883 - val_loss: 0.0376
Epoch 4/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 43s 51ms/step - accuracy: 0.9919 - loss:
0.0257 - val_accuracy: 0.9878 - val_loss: 0.0465
Epoch 5/5
844/844 ━━━━━━━━━━━━━━━━━━━━ 43s 51ms/step - accuracy: 0.9936 - loss:
0.0196 - val_accuracy: 0.9902 - val_loss: 0.0345
CNN Test Accuracy: 98.90%
1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 94ms/step