Skip to content

Instantly share code, notes, and snippets.

@Eligijus112
Created May 27, 2020 19:41
Show Gist options
  • Save Eligijus112/2ac787d9e4d1560d9f81ae795237de72 to your computer and use it in GitHub Desktop.
Save Eligijus112/2ac787d9e4d1560d9f81ae795237de72 to your computer and use it in GitHub Desktop.
Edge detection using a simple filter
import cv2
import numpy as np
from scipy import misc
import matplotlib.pyplot as plt
# Getting the image of ascent
i = misc.ascent()
# Ploting the original image
plt.grid(False)
plt.gray()
plt.imshow(i)
plt.show()
# Copying the image in order to apply the kernel filter
i_transformed = np.copy(i)
size_x = i_transformed.shape[0]
size_y = i_transformed.shape[1]
# Defining the filter for edge detection
filter = [[0, 1, 0], [1, -4, 1], [0, 1, 0]]
# Applying the filter
for x in range(1,size_x-1):
for y in range(1,size_y-1):
convolution = 0.0
convolution = convolution + (i[x - 1, y-1] * filter[0][0])
convolution = convolution + (i[x, y-1] * filter[0][1])
convolution = convolution + (i[x + 1, y-1] * filter[0][2])
convolution = convolution + (i[x-1, y] * filter[1][0])
convolution = convolution + (i[x, y] * filter[1][1])
convolution = convolution + (i[x+1, y] * filter[1][2])
convolution = convolution + (i[x-1, y+1] * filter[2][0])
convolution = convolution + (i[x, y+1] * filter[2][1])
convolution = convolution + (i[x+1, y+1] * filter[2][2])
if(convolution<0):
convolution=0
if(convolution>255):
convolution=255
i_transformed[x, y] = convolution
# Ploting the transformed image
plt.grid(False)
plt.gray()
plt.imshow(i_transformed)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment