otsu_method.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import cv2
  2. from matplotlib.ticker import FuncFormatter
  3. from matplotlib import pyplot as plt
  4. from otsu_implementation import otsu_implementation
  5. def call_otsu_threshold(img_title="boat.jpg", is_reduce_noise=False):
  6. # Read the image in a greyscale mode
  7. image = cv2.imread(img_title, 0)
  8. # Apply GaussianBlur to reduce image noise if it is required
  9. if is_reduce_noise:
  10. image = cv2.GaussianBlur(image, (5, 5), 0)
  11. # View initial image histogram
  12. plt.hist(image.ravel(), 256)
  13. plt.xlabel('Colour intensity')
  14. plt.ylabel('Number of pixels')
  15. plt.savefig("image_hist.png")
  16. plt.close()
  17. # Applying Otsu's method setting the flag value into cv.THRESH_OTSU.
  18. # Use bimodal image as an input.
  19. # Optimal threshold value is determined automatically.
  20. otsu_threshold, image_result = cv2.threshold(
  21. image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU,
  22. )
  23. print("Obtained threshold: ", otsu_threshold)
  24. # View the resulting image histogram
  25. fig = plt.figure()
  26. ax = fig.add_subplot(111)
  27. ax.hist(image_result.ravel(), 256)
  28. ax.set_xlabel('Colour intensity')
  29. ax.set_ylabel('Number of pixels')
  30. # Get rid of 1e7
  31. ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: ('%1.1fM') % (x*1e-6)))
  32. plt.savefig("image_hist_result.png")
  33. plt.close()
  34. # Visualize the image after the Otsu's method application
  35. cv2.imshow("Otsu's thresholding result", image_result)
  36. cv2.waitKey(0)
  37. cv2.destroyAllWindows()
  38. def main():
  39. call_otsu_threshold()
  40. otsu_implementation()
  41. if __name__ == "__main__":
  42. main()