"""Measure the physical scale of the rice scan from the height map. python3 measure_scan_scale.py Everything about apparent grain size depends on how much real rice the texture covers, and ambientCG does not publish that. A spectral peak is useless here: the radial average is dominated by pile-scale undulation (~240 px). Counting grain crowns and measuring their second moments gives the grain scale directly. """ import numpy as np from PIL import Image from scipy import ndimage as ndi HEIGHT = "tex/food_0015_height_2k.png" TEX_PX = 2048.0 # Long-grain white rice, typical figure used to convert pixels to millimetres. GRAIN_LENGTH_MM = 6.5 def measure(path=HEIGHT): height = np.array(Image.open(path)).astype(np.float64) # Remove pile-scale undulation so individual grains dominate. flattened = height - ndi.gaussian_filter(height, 40) crowns = flattened > np.percentile(flattened, 62) labels, count = ndi.label(ndi.binary_opening(crowns, np.ones((5, 5)))) lengths, widths = [], [] for index, window in enumerate(ndi.find_objects(labels)): if window is None: continue mask = labels[window] == index + 1 ys, xs = np.nonzero(mask) if len(ys) < 300: continue values = np.sort(np.linalg.eigvalsh(np.cov(np.vstack([ys, xs])))) if values[0] <= 0 or values[1] <= 0: continue lengths.append(4.0 * np.sqrt(values[1])) # 2 sigma each side widths.append(4.0 * np.sqrt(values[0])) return (count, len(lengths), float(np.median(lengths)), float(np.median(widths))) def main(): count, kept, length_px, width_px = measure() print(f"grain crowns: {kept} used of {count} components") print(f"median crown length {length_px:.1f} px, width {width_px:.1f} px, " f"aspect {length_px / width_px:.2f}") mm_per_px = GRAIN_LENGTH_MM / length_px print(f"if a grain is {GRAIN_LENGTH_MM} mm long, the map spans " f"{TEX_PX * mm_per_px:.0f} mm of rice") print(f"grain as a fraction of the patch: {length_px / TEX_PX:.4f}") print(f"true-scale patch for a 40 mm face: {GRAIN_LENGTH_MM * TEX_PX / length_px:.0f} mm") if __name__ == "__main__": main()