"""図S1 の各パネルで、空気の粒（明るい塊）の縦÷横（2次モーメントから求めた、層に垂直な向きの長さ ÷ 層に沿った向きの長さ）を測る。
写真の横方向が層に沿った向き（層はほぼ水平）。"""
import numpy as np
from PIL import Image
from scipy import ndimage as ndi
im = np.asarray(Image.open('../src/si_figS1_0.png').convert('L')).astype(float)
from measure_figS1 import spans, rows, cols, label, names  # noqa
k=0
for (r0,r1) in rows:
    for (c0,c1) in cols:
        p = im[r0:r1, c0:c1]; h,w = p.shape
        sub = p[int(h*0.15):int(h*0.72), :]
        # 局所の背景を引いて、明るい塊を取り出す
        bg = ndi.uniform_filter(sub, 25)
        mask = (sub - bg) > 18
        mask = ndi.binary_opening(mask, iterations=1)
        lab, n = ndi.label(mask)
        ratios=[]; sizes=[]
        for i in range(1, n+1):
            ys, xs = np.nonzero(lab==i)
            if len(ys) < 12 or len(ys) > 2000: continue
            sy, sx = ys.std(), xs.std()
            if sx == 0: continue
            ratios.append(sy/sx); sizes.append(len(ys))
        r = np.array(ratios)
        print(f'{names[k]} {label[names[k]]:14s} 粒 {len(r):3d}個  縦/横 中央値 {np.median(r):.2f}  (四分位 {np.percentile(r,25):.2f}–{np.percentile(r,75):.2f})')
        k+=1
