没有开放CV方法的Otsu二值化问题

时间:2019-02-15 10:09:55

标签: python

下面的代码是Otsu二值化的作用。

from numpy import *
from PIL import Image
from matplotib import pylot as plt 

def load_Image(file_name):
  img= Image.open(file_name)
  img.load ()
  bw=img.convert('L')
  bins= np.array(range(0,275))
  counts,pixels=np.histogram(bins,bw)
  pixels=pixels[:-1]
  plt.bar(pixels,counts,align='center')
  plt.savefig('histogram.png')
  plt.shows()

  total_counts=np.sum(counts)
  assert total_counts==bw.shape[0]*bw.shape[1]
  return bins,counts,pixels,bw, total_counts

因此,简单来说,它会根据图像直方图自动计算双峰图像的阈值

def otsu(gray):
    pixels = gray.shape[0] * gray.shape[1]
    mean_weigth = 1.0 / pixels
    histogram, bins = np.histogram(gray, np.arange(0, 265))
    final_thresh = -1
    final_value = -1
    for t in bins[1:-1]:  # this goes from 1 ti 254 units range
        wb = np.sum(histogram[:t]) * mean_weigth
        wf = np.sum(histogram[:t]) * mean_weigth

        mub = np.mean(histogram[:t])
        muf = np.mean(histogram[t:])
        value = wb * wf * (mub - muf) ** 2

        print("wb", wb, "wf", wf)
        print("t", t, "value", value)

        if value > final_value:
            final_thresh = t
            final_value = value
    final_img = gray.copy()
    print(final_thresh)
    final_img[gray > final_thresh] = 255
    final_img[gray < final_thresh] = 0

    return final_img
if __name__=="___main__":
    file_name='toureiffel.jpg'
    bins,counts,pixels,bw_data,total_counts=load_Image(file_name)
    final_img=otsu()
    plt.imshow(final_img)
    plt.savefig('otsu.png')
    plt.show()

阈值处理这是最简单,功能强大的图像分割方法,可用于区分前景和背景。阈值操作用于将灰度图像转换为二进制图像

0 个答案:

没有答案