Skip to content

Instantly share code, notes, and snippets.

@NikaTsanka
Created July 2, 2017 18:17
Show Gist options
  • Save NikaTsanka/868a33330c26e775e70b18bb96615d39 to your computer and use it in GitHub Desktop.
Save NikaTsanka/868a33330c26e775e70b18bb96615d39 to your computer and use it in GitHub Desktop.
Sobel Operator
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# Open the image
img = np.array(Image.open('dancing-spider.jpg')).astype(np.uint8)
# Apply gray scale
gray_img = np.round(0.299 * img[:, :, 0] +
0.587 * img[:, :, 1] +
0.114 * img[:, :, 2]).astype(np.uint8)
# Sobel Operator
h, w = gray_img.shape
# define filters
horizontal = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) # s2
vertical = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]) # s1
# define images with 0s
newhorizontalImage = np.zeros((h, w))
newverticalImage = np.zeros((h, w))
newgradientImage = np.zeros((h, w))
# offset by 1
for i in range(1, h - 1):
for j in range(1, w - 1):
horizontalGrad = (horizontal[0, 0] * gray_img[i - 1, j - 1]) + \
(horizontal[0, 1] * gray_img[i - 1, j]) + \
(horizontal[0, 2] * gray_img[i - 1, j + 1]) + \
(horizontal[1, 0] * gray_img[i, j - 1]) + \
(horizontal[1, 1] * gray_img[i, j]) + \
(horizontal[1, 2] * gray_img[i, j + 1]) + \
(horizontal[2, 0] * gray_img[i + 1, j - 1]) + \
(horizontal[2, 1] * gray_img[i + 1, j]) + \
(horizontal[2, 2] * gray_img[i + 1, j + 1])
newhorizontalImage[i - 1, j - 1] = abs(horizontalGrad)
verticalGrad = (vertical[0, 0] * gray_img[i - 1, j - 1]) + \
(vertical[0, 1] * gray_img[i - 1, j]) + \
(vertical[0, 2] * gray_img[i - 1, j + 1]) + \
(vertical[1, 0] * gray_img[i, j - 1]) + \
(vertical[1, 1] * gray_img[i, j]) + \
(vertical[1, 2] * gray_img[i, j + 1]) + \
(vertical[2, 0] * gray_img[i + 1, j - 1]) + \
(vertical[2, 1] * gray_img[i + 1, j]) + \
(vertical[2, 2] * gray_img[i + 1, j + 1])
newverticalImage[i - 1, j - 1] = abs(verticalGrad)
# Edge Magnitude
mag = np.sqrt(pow(horizontalGrad, 2.0) + pow(verticalGrad, 2.0))
newgradientImage[i - 1, j - 1] = mag
plt.figure()
plt.title('dancing-spider-sobel.png')
plt.imsave('dancing-spider-sobel.png', newgradientImage, cmap='gray', format='png')
plt.imshow(newgradientImage, cmap='gray')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment