smoothing.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import sys
  2. import cv2 as cv
  3. import numpy as np
  4. # Global Variables
  5. DELAY_CAPTION = 1500
  6. DELAY_BLUR = 100
  7. MAX_KERNEL_LENGTH = 31
  8. src = None
  9. dst = None
  10. window_name = 'Smoothing Demo'
  11. def main(argv):
  12. cv.namedWindow(window_name, cv.WINDOW_AUTOSIZE)
  13. # Load the source image
  14. imageName = argv[0] if len(argv) > 0 else 'lena.jpg'
  15. global src
  16. src = cv.imread(cv.samples.findFile(imageName))
  17. if src is None:
  18. print ('Error opening image')
  19. print ('Usage: smoothing.py [image_name -- default ../data/lena.jpg] \n')
  20. return -1
  21. if display_caption('Original Image') != 0:
  22. return 0
  23. global dst
  24. dst = np.copy(src)
  25. if display_dst(DELAY_CAPTION) != 0:
  26. return 0
  27. # Applying Homogeneous blur
  28. if display_caption('Homogeneous Blur') != 0:
  29. return 0
  30. ## [blur]
  31. for i in range(1, MAX_KERNEL_LENGTH, 2):
  32. dst = cv.blur(src, (i, i))
  33. if display_dst(DELAY_BLUR) != 0:
  34. return 0
  35. ## [blur]
  36. # Applying Gaussian blur
  37. if display_caption('Gaussian Blur') != 0:
  38. return 0
  39. ## [gaussianblur]
  40. for i in range(1, MAX_KERNEL_LENGTH, 2):
  41. dst = cv.GaussianBlur(src, (i, i), 0)
  42. if display_dst(DELAY_BLUR) != 0:
  43. return 0
  44. ## [gaussianblur]
  45. # Applying Median blur
  46. if display_caption('Median Blur') != 0:
  47. return 0
  48. ## [medianblur]
  49. for i in range(1, MAX_KERNEL_LENGTH, 2):
  50. dst = cv.medianBlur(src, i)
  51. if display_dst(DELAY_BLUR) != 0:
  52. return 0
  53. ## [medianblur]
  54. # Applying Bilateral Filter
  55. if display_caption('Bilateral Blur') != 0:
  56. return 0
  57. ## [bilateralfilter]
  58. # Remember, bilateral is a bit slow, so as value go higher, it takes long time
  59. for i in range(1, MAX_KERNEL_LENGTH, 2):
  60. dst = cv.bilateralFilter(src, i, i * 2, i / 2)
  61. if display_dst(DELAY_BLUR) != 0:
  62. return 0
  63. ## [bilateralfilter]
  64. # Done
  65. display_caption('Done!')
  66. return 0
  67. def display_caption(caption):
  68. global dst
  69. dst = np.zeros(src.shape, src.dtype)
  70. rows, cols, _ch = src.shape
  71. cv.putText(dst, caption,
  72. (int(cols / 4), int(rows / 2)),
  73. cv.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255))
  74. return display_dst(DELAY_CAPTION)
  75. def display_dst(delay):
  76. cv.imshow(window_name, dst)
  77. c = cv.waitKey(delay)
  78. if c >= 0 : return -1
  79. return 0
  80. if __name__ == "__main__":
  81. main(sys.argv[1:])