sobel_filter.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # @Author : lightXu
  2. # @File : sobel_filter.py
  3. # @Time : 2019/7/8 0008 下午 16:26
  4. import numpy as np
  5. from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
  6. from digital_image_processing.filters.convolve import img_convolve
  7. def sobel_filter(image):
  8. kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
  9. kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
  10. dst_x = np.abs(img_convolve(image, kernel_x))
  11. dst_y = np.abs(img_convolve(image, kernel_y))
  12. # modify the pix within [0, 255]
  13. dst_x = dst_x * 255 / np.max(dst_x)
  14. dst_y = dst_y * 255 / np.max(dst_y)
  15. dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y)))
  16. dst_xy = dst_xy * 255 / np.max(dst_xy)
  17. dst = dst_xy.astype(np.uint8)
  18. theta = np.arctan2(dst_y, dst_x)
  19. return dst, theta
  20. if __name__ == "__main__":
  21. # read original image
  22. img = imread("../image_data/lena.jpg")
  23. # turn image in gray scale value
  24. gray = cvtColor(img, COLOR_BGR2GRAY)
  25. sobel_grad, sobel_theta = sobel_filter(gray)
  26. # show result images
  27. imshow("sobel filter", sobel_grad)
  28. imshow("sobel theta", sobel_theta)
  29. waitKey(0)