Skip to content

Instantly share code, notes, and snippets.

@KittyLiou
Created March 31, 2019 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KittyLiou/ba33333ea64bd57e8c77b90a7efc4a45 to your computer and use it in GitHub Desktop.
Save KittyLiou/ba33333ea64bd57e8c77b90a7efc4a45 to your computer and use it in GitHub Desktop.
A simple edge detection example
import cv2
import numpy as np
# define vertical and horizontal filters
N = 3
vertical_filter = [[-1,0,1],
[-1,0,1],
[-1,0,1]]
horizontal_filter = [[-1,-1,-1],
[0,0,0],
[1,1,1]]
threshold = 100
# read in input image
im = cv2.imread('lenna.jpg', cv2.IMREAD_GRAYSCALE)
im_h = im.shape[0]
im_w = im.shape[1]
# create new images for edge detection results (without padding)
v_edge_im = np.zeros((im_h-N+1, im_w-N+1), dtype=np.uint8)
h_edge_im = np.zeros((im_h-N+1, im_w-N+1), dtype=np.uint8)
# slide over each location on the input image
for i in range(im_h):
for j in range(im_w):
# ignore 4 sides
if i > im_h-N or j > im_w-N:
continue
# convolution
v_conv_value = 0
h_conv_value = 0
for m in range(N):
for n in range(N):
v_conv_value += im[i+m][j+n] * vertical_filter[m][n]
h_conv_value += im[i+m][j+n] * horizontal_filter[m][n]
if v_conv_value > threshold:
v_edge_im[i][j] = 255
else:
v_edge_im[i][j] = 0
if h_conv_value > threshold:
h_edge_im[i][j] = 255
else:
h_edge_im[i][j] = 0
print(im.shape)
print(v_edge_im.shape)
print(h_edge_im.shape)
# show edge detection results
cv2.imshow('original', im)
cv2.imshow('vertical edge', v_edge_im)
cv2.imshow('horizontal edge', h_edge_im)
# exit after press any key
cv2.waitKey(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment