Skip to content

Instantly share code, notes, and snippets.

@pknowledge
Created May 24, 2019 23:48
Show Gist options
  • Save pknowledge/05d68179cdb364e4fa4db608517f8d17 to your computer and use it in GitHub Desktop.
Save pknowledge/05d68179cdb364e4fa4db608517f8d17 to your computer and use it in GitHub Desktop.
Canny Edge Detection in OpenCV Python
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("lena.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
canny = cv2.Canny(img, 100, 200)
titles = ['image', 'canny']
images = [img, canny]
for i in range(2):
plt.subplot(1, 2, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("messi5.jpg", cv2.IMREAD_GRAYSCALE)
lap = cv2.Laplacian(img, cv2.CV_64F, ksize=3)
lap = np.uint8(np.absolute(lap))
sobelX = cv2.Sobel(img, cv2.CV_64F, 1, 0)
sobelY = cv2.Sobel(img, cv2.CV_64F, 0, 1)
edges = cv2.Canny(img,100,200)
sobelX = np.uint8(np.absolute(sobelX))
sobelY = np.uint8(np.absolute(sobelY))
sobelCombined = cv2.bitwise_or(sobelX, sobelY)
titles = ['image', 'Laplacian', 'sobelX', 'sobelY', 'sobelCombined', 'Canny']
images = [img, lap, sobelX, sobelY, sobelCombined, edges]
for i in range(6):
plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
@nagasrisai
Copy link

import cv2
import numpy as np
from matplotlib import pyplot as plt
def nothing(i):
pass

cv2.namedWindow("image")
cv2.createTrackbar('x',"image",0,100,nothing)
cv2.createTrackbar('y',"image",0,100,nothing)
while(True):
img = cv2.imread("lena.jpg")
x=cv2.getTrackbarPos('x',"image")
y=cv2.getTrackbarPos('y',"image")
canny= cv2.Canny(img,x,y)

cv2.imshow("image",img)
cv2.imshow("image",canny)
k=cv2.waitKey(0)
if(k==27):
    break

cv2.destroyAllWindows()
bro its not working bro can you please help me bro

@MazenMostafa1997
Copy link

Mr nagasrisai,
I tested your code and found out that the error lies in this line k=cv2.waitkey(0)
If you change it and write k=cv2.waitkey(1) , it will work well

@PratyushMishra02
Copy link

nice

@Sandyjiit
Copy link

Can you please help me with code for video data, to find edges of the extracted frames then subtracting the frames from the centered frame and hence save it into a directory?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment