import cv2 import numpy as np import matplotlib.pyplot as plt import cv2 as cv import math def calc_gray_hist(image): rows,cols=image.shape gray_hist=np.zeros([256],dtype=np.uint64) for i in range(rows): for j in range(cols): gray_hist[image[i,j]]+=1 return gray_hist def otsu_thresh(image): rows,cols=image.shape #计算灰度直方图 gray_hist=calc_gray_hist(image) #直方图归一化处理 norm_hist=gray_hist/(rows*cols) #计算累计距,一阶累积矩 zero_cumu_moment=np.zeros([256],dtype=np.float64) one_cumu_moment = np.zeros([256], dtype=np.float64) variance_G= np.zeros([256], dtype=np.float64) for i in range(256): if i==0: zero_cumu_moment[i]=norm_hist[i] one_cumu_moment[i]=0 variance_G[i] = 0 else: zero_cumu_moment[i]=zero_cumu_moment[i-1]+norm_hist[i] one_cumu_moment[i]=one_cumu_moment[i-1]+zero_cumu_moment[i]*i #计算类间方差 mG=one_cumu_moment[255] thresh=0 sigma=0 for i in range(256): if i==0: variance_G[i] = 0 else: variance_G[i]=variance_G[i-1]+math.pow(i-mG,2)*norm_hist[i] for i in range(256): if zero_cumu_moment[i]==0 and zero_cumu_moment[i]==0: sigma_temp = 0 else: sigma_temp=math.pow(mG*zero_cumu_moment[i]-one_cumu_moment[i],2)/zero_cumu_moment[i]*(1-zero_cumu_moment[i]) if sigma<sigma_temp: sigma=sigma_temp thresh=i #阈值分割 variance_G=variance_G[255] #可分离测度 yita=sigma/variance_G thresh_img=image.copy() thresh_img[thresh_img>thresh]=255 thresh_img[thresh_img<=thresh] =0 return thresh,thresh_img,yita if __name__=='__main__': img=cv.imread('../data/1.jpg',0) gray_hist=calc_gray_hist(img) thresh,thresh_img,yita=otsu_thresh(img) print('阈值:',thresh,"可分离性测量度:",yita) cv2.imwrite('hhh.jpg',thresh_img) plt.plot(gray_hist) plt.show() cv.waitKey() cv.destroyAllWindows()
冈萨雷斯第四版P541