# 15.3_Otsu's 二值化
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('ALL01.jpg', 0)
# global thresholding
ret1, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# Otsu's thresholding
ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# Otsu's thresholding after Gaussian filtering
# （9,9）為高斯核的大小，8 為標準差
blur = cv2.GaussianBlur(img, (9, 9), 8)
# 閥值一定要設為 0！
###########################一定要0!
ret3, th3 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# plot all the images and their histograms


cv2.imshow("origin", img)
cv2.imshow("th1", th1)
cv2.imshow("th2", th2)
cv2.imshow("th3", th3)
cv2.waitKey(0)
cv2.destroyAllWindows()






# #共有9張圖
# images = [img, 0, th1, img, 0, th2, blur, 0, th3]
# titles = ['Original Noisy Image', 'Histogram', 'Global Thresholding (v=127)', 'Original Noisy Image',
#           'Histogram', "Otsu's Thresholding", 'Gaussian filtered Image', 'Histogram', "Otsu's Thresholding"]
# # 這裡使用 pyplot 畫直方圖，plt.hist, 要注意的是它的参數是一维數组
# # 所以這裡使用了（numpy）ravel 方法，將多维數组轉換成一维，也可以使用 flatten 方法
# # ndarray.flat 1-D iterator over an array.
# # ndarray.flatten 1-D array copy of the elements of an array in row-major order
# for i in range(3):
#     plt.subplot(3, 3, i*3+1), plt.imshow(images[i*3], 'gray')
#     plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
#     plt.subplot(3, 3, i*3+2), plt.hist(images[i*3].ravel(), 256)
#     plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
#     plt.subplot(3, 3, i*3+3), plt.imshow(images[i*3+2], 'gray')
#     plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
# plt.show()
