"""TEM 1枚を格子状の領域に分け、領域ごとに構造テンソルで板の向きの揃い具合と、板に直交する方向の1次元プロファイルの周期を測る。
縮尺は TIFF の解像度タグ 282（画素/nm）。揃い具合が高く、背景（空）が少ない領域だけ残す。"""
import sys, numpy as np
from PIL import Image
from scipy import ndimage as ndi
def scale(im): return float(im.tag_v2[282][0]) if hasattr(im.tag_v2[282], '__len__') else float(im.tag_v2[282])
def regions(path, win_nm=1200, step_nm=400):
    im = Image.open(path); sc = scale(im); a = np.asarray(im, float)
    a = (a - a.mean())/a.std(); a = ndi.gaussian_filter(a, 1.0)
    gy, gx = np.gradient(a)
    w = int(win_nm*sc); st = int(step_nm*sc); out = []
    for y in range(0, a.shape[0]-w, st):
        for x in range(0, a.shape[1]-w, st):
            if y+w > 0.92*a.shape[0] and x+w > 0.75*a.shape[1]: continue   # 縮尺バー
            sl = (slice(y, y+w), slice(x, x+w)); p = a[sl]
            if p.std() < 0.35: continue                      # 背景・空の領域
            jxx, jyy, jxy = (gx[sl]**2).mean(), (gy[sl]**2).mean(), (gx[sl]*gy[sl]).mean()
            lam = np.linalg.eigvalsh([[jxx, jxy], [jxy, jyy]]); coh = (lam[1]-lam[0])/(lam[1]+lam[0]+1e-9)
            th = 0.5*np.arctan2(2*jxy, jxx-jyy)             # 勾配の向き＝板に直交する方向
            rot = ndi.rotate(p, np.degrees(th), reshape=False, mode='reflect')
            prof = rot[w//4:3*w//4].mean(axis=0)            # 板に直交する方向のプロファイル
            prof = prof - prof.mean(); n8 = 8*len(prof); f = np.abs(np.fft.rfft(prof*np.hanning(len(prof)), n8))**2
            fr = np.fft.rfftfreq(n8, 1/sc)           # 1/nm
            band = (fr > 1/500) & (fr < 1/120)
            if not band.any(): continue
            k = np.argmax(np.where(band, f, 0)); out.append((x/sc, y/sc, coh, 1/fr[k], f[k]/f[band].sum()))
    return out
if __name__ == '__main__':
    r = regions(sys.argv[1]); print(len(r), '領域')
    for x, y, c, per, pk in sorted(r, key=lambda t: -t[2])[:12]: print(f'x={x:.0f} y={y:.0f}nm 揃い={c:.2f} 周期={per:.0f}nm ピーク比={pk:.2f}')
