Created
May 11, 2022 05:48
-
-
Save YHaruoka/261f62022249324cf86d0dafbb0321fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 & vertical) | |
image_sobel = sobel(image) | |
# Prewitt filter (horizontal & vertical) | |
image_prewitt = prewitt(image) | |
# Prewitt filter (horizontal & vertical) | |
image_laplacian = laplacian_eight_neighbours(image) | |
# Saving image | |
cv2.imwrite('image_sobel.png',image_sobel) | |
cv2.imwrite('image_prewitt.png',image_prewitt) | |
cv2.imwrite('image_laplacian.png',image_laplacian) | |
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 | |
def prewitt_horizontal(image): | |
kernel_prewitt_h = np.array([[-1, -1, -1], | |
[0, 0, 0], | |
[1, 1, 1]]) | |
image_output = cv2.filter2D(image, cv2.CV_64F, kernel_prewitt_h) | |
return image_output | |
def prewitt_vertical(image): | |
kernel_prewitt_v = np.array([[-1, 0, 1], | |
[-1, 0, 1], | |
[-1, 0, 1]]) | |
image_output = cv2.filter2D(image, cv2.CV_64F, kernel_prewitt_v) | |
return image_output | |
def prewitt(image): | |
image_h = prewitt_horizontal(image) | |
image_v = prewitt_vertical(image) | |
image_output = np.sqrt(image_h ** 2 + image_v ** 2) | |
return image_output | |
def laplacian_eight_neighbours(image): | |
kernel_lap8 = np.array([[1, 1, 1], | |
[1, -8, 1], | |
[1, 1, 1]]) | |
image_output = cv2.filter2D(image, cv2.CV_64F, kernel_lap8) | |
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