栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

使用otsu方法的最优阈值处理

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用otsu方法的最优阈值处理

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 sigmathresh]=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 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/982097.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号