日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python阈值分割_Python实现otsu阈值分割算法

發布時間:2024/8/1 python 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python阈值分割_Python实现otsu阈值分割算法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

轉載自:https://github.com/mohabmes/Otsu-Thresholding/blob/master/otsu.py,本文只做個人記錄學習使用,版權歸原作者所有。

"""

Created on Mon Oct 30 12:41:30 2017

@author: mohabmes

"""

import math

import numpy as np

from matplotlib import pyplot as plt

from PIL import Image

threshold_values = {}

h = [1]

def Hist(img):

row, col = img.shape

y = np.zeros(256)

for i in range(0,row):

for j in range(0,col):

y[img[i,j]] += 1

x = np.arange(0,256)

plt.bar(x, y, color='b', width=5, align='center', alpha=0.25)

plt.show()

return y

def regenerate_img(img, threshold):

row, col = img.shape

y = np.zeros((row, col))

for i in range(0,row):

for j in range(0,col):

if img[i,j] >= threshold:

y[i,j] = 255

else:

y[i,j] = 0

return y

def countPixel(h):

cnt = 0

for i in range(0, len(h)):

if h[i]>0:

cnt += h[i]

return cnt

def wieght(s, e):

w = 0

for i in range(s, e):

w += h[i]

return w

def mean(s, e):

m = 0

w = wieght(s, e)

for i in range(s, e):

m += h[i] * i

return m/float(w)

def variance(s, e):

v = 0

m = mean(s, e)

w = wieght(s, e)

for i in range(s, e):

v += ((i - m) **2) * h[i]

v /= w

return v

def threshold(h):

cnt = countPixel(h)

for i in range(1, len(h)):

vb = variance(0, i)

wb = wieght(0, i) / float(cnt)

mb = mean(0, i)

vf = variance(i, len(h))

wf = wieght(i, len(h)) / float(cnt)

mf = mean(i, len(h))

V2w = wb * (vb) + wf * (vf)

V2b = wb * wf * (mb - mf)**2

fw = open("trace.txt", "a")

fw.write('T='+ str(i) + "\n")

fw.write('Wb='+ str(wb) + "\n")

fw.write('Mb='+ str(mb) + "\n")

fw.write('Vb='+ str(vb) + "\n")

fw.write('Wf='+ str(wf) + "\n")

fw.write('Mf='+ str(mf) + "\n")

fw.write('Vf='+ str(vf) + "\n")

fw.write('within class variance='+ str(V2w) + "\n")

fw.write('between class variance=' + str(V2b) + "\n")

fw.write("\n")

if not math.isnan(V2w):

threshold_values[i] = V2w

def get_optimal_threshold():

min_V2w = min(threshold_values.itervalues())

optimal_threshold = [k for k, v in threshold_values.iteritems() if v == min_V2w]

print 'optimal threshold', optimal_threshold[0]

return optimal_threshold[0]

image = Image.open('img.jpg').convert("L")

img = np.asarray(image)

h = Hist(img)

threshold(h)

op_thres = get_optimal_threshold()

res = regenerate_img(img, op_thres)

plt.imshow(res)

plt.savefig("otsu.jpg")

總結

以上是生活随笔為你收集整理的python阈值分割_Python实现otsu阈值分割算法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。