Skip to content

Instantly share code, notes, and snippets.

@shijianjian
Created April 11, 2018 12:47
Show Gist options
  • Save shijianjian/e6e17958828c19fd0b6247f58b475f6e to your computer and use it in GitHub Desktop.
Save shijianjian/e6e17958828c19fd0b6247f58b475f6e to your computer and use it in GitHub Desktop.
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
'''
Read in image
'''
img = cv2.imread('./fruit_img.jpg', cv2.IMREAD_COLOR)
gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # use black and white for demostration
crop_img = gray_img[13:513, 113:613] # crop to 500x 500 for convience
# cv2.imshow('image',img) # uncomment this line to see your image if you are not using jupyter notebook
plt.imshow(crop_img, cmap='Greys_r') # avoid matplotlib using the default colour map
plt.xticks([]), plt.yticks([])
plt.show()
'''
Using opencv
'''
# sobel along x axis
sobelx = cv2.Sobel(crop_img,cv2.CV_64F,1,0,ksize=3)
plt.imshow(sobelx,cmap = 'gray')
plt.xticks([]), plt.yticks([])
plt.show()
# sobel along y axis
sobely = cv2.Sobel(crop_img,cv2.CV_64F,0,1,ksize=3)
plt.imshow(sobely,cmap = 'gray')
plt.xticks([]), plt.yticks([])
plt.show()
'''
This is a pure numpy implementation for sobel along x axis
'''
# we will use a squared kernel on a squared image for demonstration
sobel_x_kernel = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
stride = 1
padding = 1
# padding around with zeros for easier computation
pad_image = np.zeros((crop_img.shape[0] + 2*padding, crop_img.shape[1] + 2*padding))
pad_image[padding:crop_img.shape[0] + padding, padding:crop_img.shape[1] + padding] = crop_img
out_size = int((pad_image.shape[0] + 2*padding - sobel_x_kernel.shape[0])/stride + 1)
out = np.empty((out_size, out_size))
for i in range(out_size):
for j in range(out_size):
x_start = i*stride
x_end = i*stride + sobel_x_kernel.shape[0]
y_start = j*stride
y_end = j*stride + sobel_x_kernel.shape[1]
out[i, j] = np.sum( pad_image[x_start : x_end, y_start : y_end] * sobel_x_kernel[0:3 + out_size - x_end, 0:3 + out_size - y_end] )
out[i, j] = int(out[i, j])
'''
For those who is interested in computing the magnitude
just computing sobel_x and sobel_y, then do
magnitude = np.sqrt(sobel_x**2 + sobel_y**2)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment