median_filter.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """
  2. Implementation of median filter algorithm
  3. """
  4. from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
  5. from numpy import zeros_like, ravel, sort, multiply, divide, int8
  6. def median_filter(gray_img, mask=3):
  7. """
  8. :param gray_img: gray image
  9. :param mask: mask size
  10. :return: image with median filter
  11. """
  12. # set image borders
  13. bd = int(mask / 2)
  14. # copy image size
  15. median_img = zeros_like(gray_img)
  16. for i in range(bd, gray_img.shape[0] - bd):
  17. for j in range(bd, gray_img.shape[1] - bd):
  18. # get mask according with mask
  19. kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1])
  20. # calculate mask median
  21. median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)]
  22. median_img[i, j] = median
  23. return median_img
  24. if __name__ == "__main__":
  25. # read original image
  26. img = imread("../image_data/lena.jpg")
  27. # turn image in gray scale value
  28. gray = cvtColor(img, COLOR_BGR2GRAY)
  29. # get values with two different mask size
  30. median3x3 = median_filter(gray, 3)
  31. median5x5 = median_filter(gray, 5)
  32. # show result images
  33. imshow("median filter with 3x3 mask", median3x3)
  34. imshow("median filter with 5x5 mask", median5x5)
  35. waitKey(0)