edge.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python
  2. '''
  3. This sample demonstrates Canny edge detection.
  4. Usage:
  5. edge.py [<video source>]
  6. Trackbars control edge thresholds.
  7. '''
  8. # Python 2/3 compatibility
  9. from __future__ import print_function
  10. import cv2
  11. import numpy as np
  12. # relative module
  13. import video
  14. # built-in module
  15. import sys
  16. if __name__ == '__main__':
  17. print(__doc__)
  18. try:
  19. fn = sys.argv[1]
  20. except:
  21. fn = 0
  22. def nothing(*arg):
  23. pass
  24. cv2.namedWindow('edge')
  25. cv2.createTrackbar('thrs1', 'edge', 2000, 5000, nothing)
  26. cv2.createTrackbar('thrs2', 'edge', 4000, 5000, nothing)
  27. cap = video.create_capture(fn)
  28. while True:
  29. flag, img = cap.read()
  30. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  31. thrs1 = cv2.getTrackbarPos('thrs1', 'edge')
  32. thrs2 = cv2.getTrackbarPos('thrs2', 'edge')
  33. edge = cv2.Canny(gray, thrs1, thrs2, apertureSize=5)
  34. vis = img.copy()
  35. vis = np.uint8(vis/2.)
  36. vis[edge != 0] = (0, 255, 0)
  37. cv2.imshow('edge', vis)
  38. ch = cv2.waitKey(5) & 0xFF
  39. if ch == 27:
  40. break
  41. cv2.destroyAllWindows()