Skip to content

Instantly share code, notes, and snippets.

@YHaruoka
Created May 11, 2022 03:20
Show Gist options
  • Save YHaruoka/5a17dcac5e08368673a5c2a6ea194149 to your computer and use it in GitHub Desktop.
Save YHaruoka/5a17dcac5e08368673a5c2a6ea194149 to your computer and use it in GitHub Desktop.
import numpy as np
import cv2
import sys
def main():
print("OpenCV Version: " + str(cv2.__version__))
# Loading image data (GRAYSCALE)
filename = "image.png"
image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
if image is None:
print("Cannot find image data : " + filename)
sys.exit()
# Sobel filter (horizontal)
image_sobel_h = sobel_horizontal(image)
# Sobel filter (vertical)
image_sobel_v = sobel_vertical(image)
# Sobel filter (horizontal & vertical)
image_sobel = sobel(image)
# Saving image
cv2.imwrite('image_sobel_h.png',image_sobel_h)
cv2.imwrite('image_sobel_v.png',image_sobel_v)
cv2.imwrite('image_sobel.png',image_sobel)
def sobel_horizontal(image):
kernel_sobel_h = np.array([[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]])
image_output = cv2.filter2D(image, cv2.CV_64F, kernel_sobel_h)
return image_output
def sobel_vertical(image):
kernel_sobel_v = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
image_output = cv2.filter2D(image, cv2.CV_64F, kernel_sobel_v)
return image_output
def sobel(image):
image_h = sobel_horizontal(image)
image_v = sobel_vertical(image)
image_output = np.sqrt(image_h ** 2 + image_v ** 2)
return image_output
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment