sobel_demo.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """
  2. @file sobel_demo.py
  3. @brief Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector
  4. """
  5. import sys
  6. import cv2 as cv
  7. def main(argv):
  8. ## [variables]
  9. # First we declare the variables we are going to use
  10. window_name = ('Sobel Demo - Simple Edge Detector')
  11. scale = 1
  12. delta = 0
  13. ddepth = cv.CV_16S
  14. ## [variables]
  15. ## [load]
  16. # As usual we load our source image (src)
  17. # Check number of arguments
  18. if len(argv) < 1:
  19. print ('Not enough parameters')
  20. print ('Usage:\nmorph_lines_detection.py < path_to_image >')
  21. return -1
  22. # Load the image
  23. src = cv.imread(argv[0], cv.IMREAD_COLOR)
  24. # Check if image is loaded fine
  25. if src is None:
  26. print ('Error opening image: ' + argv[0])
  27. return -1
  28. ## [load]
  29. ## [reduce_noise]
  30. # Remove noise by blurring with a Gaussian filter ( kernel size = 3 )
  31. src = cv.GaussianBlur(src, (3, 3), 0)
  32. ## [reduce_noise]
  33. ## [convert_to_gray]
  34. # Convert the image to grayscale
  35. gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
  36. ## [convert_to_gray]
  37. ## [sobel]
  38. # Gradient-X
  39. # grad_x = cv.Scharr(gray,ddepth,1,0)
  40. grad_x = cv.Sobel(gray, ddepth, 1, 0, ksize=3, scale=scale, delta=delta, borderType=cv.BORDER_DEFAULT)
  41. # Gradient-Y
  42. # grad_y = cv.Scharr(gray,ddepth,0,1)
  43. grad_y = cv.Sobel(gray, ddepth, 0, 1, ksize=3, scale=scale, delta=delta, borderType=cv.BORDER_DEFAULT)
  44. ## [sobel]
  45. ## [convert]
  46. # converting back to uint8
  47. abs_grad_x = cv.convertScaleAbs(grad_x)
  48. abs_grad_y = cv.convertScaleAbs(grad_y)
  49. ## [convert]
  50. ## [blend]
  51. ## Total Gradient (approximate)
  52. grad = cv.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)
  53. ## [blend]
  54. ## [display]
  55. cv.imshow(window_name, grad)
  56. cv.waitKey(0)
  57. ## [display]
  58. return 0
  59. if __name__ == "__main__":
  60. main(sys.argv[1:])