edge_drawing.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/python
  2. '''
  3. This example illustrates how to use cv.ximgproc.EdgeDrawing class.
  4. Usage:
  5. ed.py [<image_name>]
  6. image argument defaults to board.jpg
  7. '''
  8. # Python 2/3 compatibility
  9. from __future__ import print_function
  10. import numpy as np
  11. import cv2 as cv
  12. import random as rng
  13. import sys
  14. rng.seed(12345)
  15. def main():
  16. try:
  17. fn = sys.argv[1]
  18. except IndexError:
  19. fn = 'board.jpg'
  20. src = cv.imread(cv.samples.findFile(fn))
  21. gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
  22. cv.imshow("source", src)
  23. ssrc = src.copy()*0
  24. lsrc = src.copy()
  25. esrc = src.copy()
  26. ed = cv.ximgproc.createEdgeDrawing()
  27. # you can change parameters (refer the documentation to see all parameters)
  28. EDParams = cv.ximgproc_EdgeDrawing_Params()
  29. EDParams.MinPathLength = 50 # try changing this value between 5 to 1000
  30. EDParams.PFmode = False # defaut value try to swich it to True
  31. EDParams.MinLineLength = 10 # try changing this value between 5 to 100
  32. EDParams.NFAValidation = True # defaut value try to swich it to False
  33. ed.setParams(EDParams)
  34. # Detect edges
  35. # you should call this before detectLines() and detectEllipses()
  36. ed.detectEdges(gray)
  37. segments = ed.getSegments()
  38. lines = ed.detectLines()
  39. ellipses = ed.detectEllipses()
  40. #Draw detected edge segments
  41. for i in range(len(segments)):
  42. color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
  43. cv.polylines(ssrc, [segments[i]], False, color, 1, cv.LINE_8)
  44. cv.imshow("detected edge segments", ssrc)
  45. #Draw detected lines
  46. if lines is not None: # Check if the lines have been found and only then iterate over these and add them to the image
  47. lines = np.uint16(np.around(lines))
  48. for i in range(len(lines)):
  49. cv.line(lsrc, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 1, cv.LINE_AA)
  50. cv.imshow("detected lines", lsrc)
  51. #Draw detected circles and ellipses
  52. if ellipses is not None: # Check if circles and ellipses have been found and only then iterate over these and add them to the image
  53. ellipses = np.uint16(np.around(ellipses))
  54. for i in range(len(ellipses)):
  55. color = (0, 0, 255)
  56. if ellipses[i][0][2] == 0:
  57. color = (0, 255, 0)
  58. cv.ellipse(esrc, (ellipses[i][0][0], ellipses[i][0][1]), (ellipses[i][0][2]+ellipses[i][0][3],ellipses[i][0][2]+ellipses[i][0][4]),ellipses[i][0][5],0, 360, color, 2, cv.LINE_AA)
  59. cv.imshow("detected ellipses", esrc)
  60. cv.waitKey(0)
  61. print('Done')
  62. if __name__ == '__main__':
  63. print(__doc__)
  64. main()
  65. cv.destroyAllWindows()