LoginSignup
2
1

More than 1 year has passed since last update.

【Python】二値化処理のPタイル法による閾値の決定

Last updated at Posted at 2020-06-29

経緯

Pタイル法を使った画像の二値化処理に関する情報が不足しているため、Pythonで実装してみました。

Pタイル法とは

Pタイル法は、画像のヒストグラムをX%ごとに分割し、その中間点を閾値として画像を二値化するアルゴリズムです。

二値化とは

画像処理において、画素の濃度値をある基準値によって黒と白の2つの値に変換する処理のことを指します。

コード

 ptile.ipynb

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
file = "./sample.png"

#閾値を返す関数
def decideTh(area, ret):
    #閾値
    th = 0
    #背景
    background = 0
    #背景の面積比率
    bg_ratio = 1 / 2
    count = 0
    #背景を求める
    for i in ret[0]:
        background += i
        if background == 0:
            ratio = 0
        else:
            ratio = background /area
        #背景の面積比率が指定値以下になるまで、閾値を更新
        if ratio  <= bg_ratio:
            th = ret[1][count]
        count+=1

    return th

#画像をヒストグラムとして変換し、閾値として変換する関数
def binari(filename):
    #ヒストグラムの面積
    area = 0
    #画像をグレースケールに変換し、輝度値を取得
    img = np.array(Image.open(filename).convert("L")).reshape(-1,1)
    #輝度値をヒストグラムに変換し、代入
    ret = (plt.hist(img, bins=255))
    #ヒストグラムの面積を求める
    for i in ret[0]:
        area += i
    
    th = decideTh(area,ret)
    return th

print(binari(file))

img = np.array(Image.open(filename).convert("L")).reshape(-1,1)
    ret = (plt.hist(img, bins=255))

このコードは、@seigotさんのpythonで画像の輝度値のヒストグラムを表示するのコードを参考にしています。

参考

Pタイル法による二値化フィルタ

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1