Python:Opencv Edge Detection© Karobben

Python:Opencv Edge Detection

Python:Opencv Edge Detection

Reference:

Example Image:

© Joe Jimbo
import cv2
import numpy as np

# Read the original image
img = cv2.imread('test.jpg')
# Convert to graycsale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Blur the image for better edge detection
img_blur = cv2.GaussianBlur(img_gray, (3,3), 0)

# Sobel Edge Detection
sobelx = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=5) # Sobel Edge Detection on the X axis
sobely = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=5) # Sobel Edge Detection on the Y axis
sobelxy = cv2.Sobel(src=img_blur, ddepth=cv2.CV_64F, dx=1, dy=1, ksize=5) # Combined X and Y Sobel Edge Detection
# Display Sobel Edge Detection Images
'''
cv2.imshow('Sobel X', sobelx)
cv2.waitKey(0)
cv2.imshow('Sobel Y', sobely)
cv2.waitKey(0)
cv2.imshow('Sobel X Y using Sobel() function', sobelxy)
cv2.waitKey(0)
'''

# Canny Edge Detection
edges = cv2.Canny(image=img_blur, threshold1=70, threshold2=70) # Canny Edge Detection
# Display Canny Edge Detection Image
cv2.imshow('Canny Edge Detection', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()


edges = cv2.Canny(image=img_blur, threshold1=70, threshold2=70) # Canny Edge Detection
edges[edges!=0]= 100
edges[edges==0]= 255
edges[edges==100]= 0

#img2 = cv2.dilate(edges,kernel,iterations = 1)

cv2.imshow('Canny Edge Detection', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()


kernel = np.ones((2,2),np.uint8)
erosion = cv2.erode(edges,kernel,iterations = 1)
img = cv2.cvtColor(erosion, cv2.COLOR_GRAY2RGB)
#img[np.all(img == (0, 0, 0), axis=-1)] = (128, 114, 250)

cv2.imshow('Canny Edge Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.imwrite("result2.png", img)

Author

Karobben

Posted on

2022-06-13

Updated on

2024-01-11

Licensed under

Comments