"""TEM 画像（Dryad の TEM_images.zip、ImageJ の縮尺入り）ごとに、層の繰り返し（板＋空気の周期）を2次元FFTの主ピークから測る。
縮尺は TIFF の解像度タグ（画素/nm）。部位のラベルが無いので、まず画像ごとの周期だけを並べる。"""
import glob, os, numpy as np
from PIL import Image
D = '../src/dryad/TEM/TEM_images/'
out = []
for f in sorted(glob.glob(D + '*.tif')):
    im = Image.open(f); ppn = float(im.tag_v2[282])      # 画素/nm
    a = np.asarray(im, float); a = a - a.mean()
    w = np.hanning(a.shape[0])[:, None]*np.hanning(a.shape[1])[None, :]
    F = np.abs(np.fft.fftshift(np.fft.fft2(a*w)))**2
    n = a.shape[0]; cy = cx = n//2
    yy, xx = np.indices(F.shape); r = np.hypot(yy-cy, xx-cx)
    # 周期 150〜500nm に当たる空間周波数の環だけ見る
    fr = r/(n/ppn)        # 1/nm
    m = (fr > 1/500) & (fr < 1/150)
    i = np.argmax(np.where(m, F, 0)); y, x = np.unravel_index(i, F.shape)
    per = 1/(np.hypot(y-cy, x-cx)/(n/ppn))
    ang = np.degrees(np.arctan2(y-cy, x-cx)) % 180
    # 環の中の主ピークの強さ（環全体の平均に対する倍率）
    out.append((os.path.basename(f), 1/ppn, per, ang, F.flat[i]/np.mean(F[m])))
print('file, nm/px, period(nm), angle, peak/ring-mean')
for o in out: print(f'{o[0]:30s} {o[1]:5.1f} {o[2]:6.0f} {o[3]:5.0f} {o[4]:7.0f}')
