"""SI 図S1 の9枚（A-C 喉、D-F 頭頂、G-I 尾。各 branickii・雑種・gularis）で、板の行の帯の中の明るい画素（空気の粒）の割合を測る。
行は、明るい画素の行ごとの割合が山になるところ。同じ撮り方・同じ閾値の規則で部位どうしを比べる。"""
import numpy as np
from PIL import Image
from scipy import ndimage as ndi
from skimage.filters import threshold_otsu
im = np.asarray(Image.open('../src/si_figS1_0.png').convert('L')).astype(float)
colw = (im > 250).mean(axis=0) > 0.97; roww = (im > 250).mean(axis=1) > 0.97
def spans(mask):
    out=[]; i=0
    while i < len(mask):
        if not mask[i]:
            j=i
            while j < len(mask) and not mask[j]: j+=1
            if j-i > 100: out.append((i,j))
            i=j
        else: i+=1
    return out
cols, rows = spans(colw), spans(roww)
lab = ['喉 branickii','喉 雑種','喉 gularis','頭頂 branickii','頭頂 雑種','頭頂 gularis','尾 branickii','尾 雑種','尾 gularis']
k = 0; res = {}
for (r0, r1) in rows:
    for (c0, c1) in cols:
        p = im[r0:r1, c0:c1]; h, w = p.shape
        core = p[int(h*0.18):int(h*0.80), int(w*0.04):int(w*0.96)]     # 上の背景・下の目盛りバーを除く
        t = threshold_otsu(core); m = core > t
        prof = ndi.gaussian_filter1d(m.mean(axis=1), 3)
        band = prof > 0.5*prof.max()                                    # 行の帯
        frac = m[band].mean()
        # 閾値を±10 動かしたときの幅
        fr = []
        for d in (-10, 10):
            mm = core > t+d; pr = ndi.gaussian_filter1d(mm.mean(axis=1), 3); fr.append(mm[pr > 0.5*pr.max()].mean())
        res[lab[k]] = (frac, min(fr), max(fr)); print(f'{lab[k]:14s} 閾値{t:.0f} 帯の明るい割合 {frac:.2f}（閾値±10で {min(fr):.2f}〜{max(fr):.2f}）')
        k += 1
for part in ('喉', '頭頂', '尾'):
    v = [res[x][0] for x in res if x.startswith(part)]; print(part, '平均 %.2f' % np.mean(v))
