import torch
import torch.nn.functional as F
from torch import nn
import pandas as pd
import matplotlib.pyplot as plt # for making figures
import seaborn as sns
%matplotlib inline
CNN Edge 2d
CNNs
# Create a tensor of size 6x6 with first three columns as 1 and rest as 0
= torch.zeros(6, 6)
x 3] = 1
x[:, :print(x)
tensor([[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 0., 0., 0.],
[1., 1., 1., 0., 0., 0.]])
x.shape
torch.Size([6, 6])
# Plot the tensor with equal aspect ratio
=(6, 6))
plt.figure(figsize=False, xticklabels=False, yticklabels=False, cmap='gray', annot=True) sns.heatmap(x, cbar
<AxesSubplot: >
# Create a 3x3 kernel with first column as 1, second as 0 and third as -1
= torch.tensor([[1, 0, -1], [1, 0, -1], [1, 0, -1]]).float()
k print(k)
tensor([[ 1., 0., -1.],
[ 1., 0., -1.],
[ 1., 0., -1.]])
# Apply the kernel to the image
= F.conv2d(x.view(1, 1, 6, 6), k.view(1, 1, 3, 3))
y print(y)
# Create figure of size of y
=(y.shape[2], y.shape[3]))
plt.figure(figsize0, 0], cbar=False, xticklabels=False, yticklabels=False, cmap='gray', annot=True) sns.heatmap(y[
tensor([[[[0., 3., 3., 0.],
[0., 3., 3., 0.],
[0., 3., 3., 0.],
[0., 3., 3., 0.]]]])
<AxesSubplot: >
= plt.imread('lm.jpeg')
im plt.imshow(im)
<matplotlib.image.AxesImage at 0x151220670>
# Crop to left 180 X 180 pixels
= im[:180, :180]
im ='gray') plt.imshow(im, cmap
<matplotlib.image.AxesImage at 0x1512b3cd0>
# Convert to grayscale
= im.mean(axis=2)
im ='gray') plt.imshow(im, cmap
<matplotlib.image.AxesImage at 0x15133dac0>
im.shape
(180, 180)
# Detect edges using our filter
= torch.tensor([[1, 0, -1], [1, 0, -1], [1, 0, -1]]).float()
k
# Apply the kernel to the image
= F.conv2d(torch.tensor(im).float().view(1, 1, 180, 180), k.view(1, 1, 3, 3))
y
# plot the result
#plt.figure(figsize=(y.shape[2], y.shape[3]))
0, 0], cmap='gray') plt.imshow(y[
<matplotlib.image.AxesImage at 0x197097430>
# Detect horizontal edges using our filter
= torch.tensor([[1, 0, -1], [1, 0, -1], [1, 0, -1]]).float().T
k
# Apply the kernel to the image
= F.conv2d(torch.tensor(im).float().view(1, 1, 180, 180), k.view(1, 1, 3, 3))
y 0, 0], cmap='gray') plt.imshow(y[
<matplotlib.image.AxesImage at 0x197105730>