gaussian_filter.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. Implementation of gaussian filter algorithm
  3. """
  4. from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
  5. from numpy import pi, mgrid, exp, square, zeros, ravel, dot, uint8
  6. def gen_gaussian_kernel(k_size, sigma):
  7. center = k_size // 2
  8. x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center]
  9. g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma)))
  10. return g
  11. def gaussian_filter(image, k_size, sigma):
  12. height, width = image.shape[0], image.shape[1]
  13. # dst image height and width
  14. dst_height = height - k_size + 1
  15. dst_width = width - k_size + 1
  16. # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
  17. image_array = zeros((dst_height * dst_width, k_size * k_size))
  18. row = 0
  19. for i in range(0, dst_height):
  20. for j in range(0, dst_width):
  21. window = ravel(image[i : i + k_size, j : j + k_size])
  22. image_array[row, :] = window
  23. row += 1
  24. # turn the kernel into shape(k*k, 1)
  25. gaussian_kernel = gen_gaussian_kernel(k_size, sigma)
  26. filter_array = ravel(gaussian_kernel)
  27. # reshape and get the dst image
  28. dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8)
  29. return dst
  30. if __name__ == "__main__":
  31. # read original image
  32. img = imread(r"../image_data/lena.jpg")
  33. # turn image in gray scale value
  34. gray = cvtColor(img, COLOR_BGR2GRAY)
  35. # get values with two different mask size
  36. gaussian3x3 = gaussian_filter(gray, 3, sigma=1)
  37. gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8)
  38. # show result images
  39. imshow("gaussian filter with 3x3 mask", gaussian3x3)
  40. imshow("gaussian filter with 5x5 mask", gaussian5x5)
  41. waitKey()