segmentation¶
nrxrdct.laue.segmentation ¶
nrxrdct.laue.segmentation¶
Detection and characterisation of diffraction spots in micro-Laue detector images.
Overview¶
Each detector frame goes through a fixed pipeline before orientation fitting:
-
Background subtraction (:func:
gaussian_background) — a large-sigma Gaussian (FFT-based, O(N log N)) estimates and removes the slowly varying background so that spot detection operates on a flat baseline. -
Segmentation — converts the background-subtracted image into a binary mask where
Truemarks candidate spot pixels. Three algorithms are available (see below). -
Cleaning (:func:
clean_segmentation) — removes objects that are too small (noise) or too large (artefacts), and discards spots that touch detector module gaps. -
Spot fitting (:func:
write_h5_spotsfile) — crops a small ROI around each connected component, fits a mixture of rotated 2-D Gaussians, and writes the fitted peak positions and shape parameters to an HDF5 file. Passfit_spots=Falseto skip fitting and store only the weighted centroids (much faster, sufficient for orientation indexing).
Segmentation methods¶
All three methods share the same interface:
method(image, mask, **kwargs) → binary_mask. They all begin with
log-scaling (log1p) and intensity normalisation so that the response is
approximately independent of the absolute intensity level.
LoG — Laplacian-of-Gaussian (:func:LoG_segmentation)
Best for round or ring-shaped spots of a predictable size. Applies a
band-pass filter tuned by sigmas: small sigma → sensitive to small
spots; large sigma → picks up extended features. A multi-scale list of
sigmas yields a pixel-wise maximum so spots of different sizes are all
detected. Works poorly on spots that sit on a strong, rapidly varying
background.
WTH — White Top-Hat (:func:WTH_segmentation)
Best for compact bright features on an uneven background (e.g.
fluorescence halo, detector artefacts). The top-hat transform
WTH = image − opening(image) cancels any background structure larger
than the structuring element (disk of radius disk_radius) while
preserving smaller bright spots. Multi-scale via a list of radii.
HYBRID — LoG + WTH union (:func:hybrid_segmentation)
Runs LoG and WTH concurrently (all scales in a single thread pool),
thresholds each family independently, then ORs the two masks. Useful
when the frame contains both round spots (better by LoG) and sharp
streaks or asymmetric peaks (better by WTH).
Choosing a method¶
- Start with LoG and a scalar sigmas matched to the typical spot FWHM
(roughly
FWHM / 2.35). - If many spots are missed due to uneven background, switch to WTH and set disk_radius slightly larger than the largest expected spot.
- Use HYBRID when the frame contains a mix of morphologies or when either method alone leaves significant false negatives.
- Tune threshold_percentile last: raise it to reduce false positives (only the very brightest pixels survive), lower it to recover dim spots at the cost of more background noise.
HDF5 spot file format¶
Each frame is written to seg_dir/frame_{idx:05d}.h5. Inside, spots are
stored in groups named spot_{ii:04d}_{jj} where ii is the region label
and jj is the Gaussian component index (0 = unfitted fallback, 1+ = fitted
components). Fields per group:
peak_X, peak_Y
Sub-pixel centroid in detector pixel coordinates (column, row).
peak_Itot, peak_Isub, peak_bkg
Total amplitude, background-subtracted amplitude, and constant background
of the fitted Gaussian.
peak_fwaxmaj, peak_fwaxmin, peak_inclination
Full-width at half-maximum along the major/minor axis (pixels) and tilt
angle of the major axis (degrees).
Xdev, Ydev
Offset between the fitted centre and the ROI centre (pixels).
r_squared
Coefficient of determination of the Gaussian fit. -1 when
fit_spots=False; 0 when fitting failed at runtime.
image
Raw ROI sub-image (cropped around the centroid).
yxcen, bbox
Weighted centroid and bounding box from :func:measure_peaks.
LoG_segmentation ¶
LoG_segmentation(image: ndarray, mask: ndarray, sigmas=0.01, threshold_percentile: float = 99.9, local_threshold: bool = False, local_block_size: int = 256) -> np.ndarray
Segment diffraction spots using a Laplacian-of-Gaussian (LoG) filter.
The LoG acts as a band-pass filter that responds strongly to blobs whose
spatial extent matches the filter scale. The negative LoG response
(−∇²G * I) has a local maximum at the centre of each bright blob,
making it well suited for detecting round or weakly elongated Laue spots.
The image is log-scaled (log1p) and intensity-normalised before
filtering so the response is approximately gain-independent. When multiple
sigmas are given, the pixel-wise maximum across all scales is taken,
enabling simultaneous detection of spots with different sizes.
| Parameters: |
|
|---|
| Returns: |
|
|---|
See Also
WTH_segmentation : White top-hat segmentation (better for uneven backgrounds). hybrid_segmentation : LoG + WTH combined. clean_segmentation : Post-processing (size filter, border removal, gap exclusion).
Source code in src/nrxrdct/laue/segmentation.py
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 | |
WTH_segmentation ¶
WTH_segmentation(image: ndarray, mask: ndarray, disk_radius=7, threshold_percentile: float = 99.9, local_threshold: bool = False, local_block_size: int = 256) -> np.ndarray
Segment diffraction spots using a white top-hat transform.
The white top-hat WTH(I) = I - opening(I) suppresses slowly varying
background while preserving bright compact features (spots) smaller than
the structuring element. It is complementary to
:func:LoG_segmentation: LoG excels at ring/blob detection; WTH is more
robust when spots sit on a strong, uneven background (e.g. fluorescence
or detector artefacts).
| Parameters: |
|
|---|
| Returns: |
|
|---|
See Also: LoG_segmentation : Laplacian-of-Gaussian based segmentation. clean_segmentation : Post-processing (size filter, border removal, etc.).
Source code in src/nrxrdct/laue/segmentation.py
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 | |
auto_init_gaussian_mixture_global ¶
auto_init_gaussian_mixture_global(image, n_components=None, smooth_sigma=2, threshold_rel=0.2, min_distance=6)
Heuristic init for gaussian mixture: - smooth image - find local maxima via maximum_filter - keep peaks above threshold_rel * max - compute centers (y,x) sorted by peak value, optionally keep top n_components - build weights based on distance to centers with Gaussian kernel (smooth_sigma) - for each component: weighted mean + covariance -> (A, xm, ym, sx, sy, theta) - background C0 = median(img) - clamp params within bounds
Source code in src/nrxrdct/laue/segmentation.py
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
clean_segmentation ¶
clean_segmentation(segmented_image, detector_mask, intensity_image, min_size: int = 3, max_size: int = 500, gap_exclude: int = 3, gap_closing: int = 3)
Post-process a binary segmentation mask.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in src/nrxrdct/laue/segmentation.py
convert_spotsfile2peaklist ¶
Read the spots HDF5 file and return an (N, 9) array of peak quantities, sorted by descending peak intensity.
peak_X, peak_Y, peak_I (Isub), peak_fwaxmaj, peak_fwaxmin,
peak_inclination, Xdev, Ydev, peak_bkg.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in src/nrxrdct/laue/segmentation.py
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 | |
convert_spotsfiles_to_dat ¶
convert_spotsfiles_to_dat(seg_dir: str, target_dir: str, *, include_unfitted: bool = False, r_squared_min: float = 0.9, n_workers: int | None = None, overwrite: bool = False) -> int
Convert all frame_?????.h5 spot files in seg_dir to DAT files in
target_dir, using a process pool for true parallelism.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in src/nrxrdct/laue/segmentation.py
fill_gaps_nearest ¶
Fast nearest-neighbor gap filling.
Source code in src/nrxrdct/laue/segmentation.py
filter_and_rescale_images ¶
Reduce a stack of images (N, ny, nx) to a 2D image by applying a reduction along axis 0 (min/max/mean/std/median), then apply a Butterworth filter and rescale to float32 in a [0,1]-like range (min-subtracted).
Source code in src/nrxrdct/laue/segmentation.py
fit_gaussian_2d_rotated ¶
Fit a single rotated 2D gaussian to an image using curve_fit. Returns (popt, pcov, fit_img, x, y)
Source code in src/nrxrdct/laue/segmentation.py
fit_gaussian_mixture_2d ¶
Fit mixture of n_components rotated Gaussians + constant background. init_params should be a list of length 6*n_components + 1 (including C). Returns (popt, pcov, fitted, X, Y)
Source code in src/nrxrdct/laue/segmentation.py
fwhm_from_sigma ¶
gaussian_2d_rotated ¶
Rotated 2D Gaussian + offset, returns raveled model. coords = (x, y) as 2 arrays (meshgrid flattened later).
Source code in src/nrxrdct/laue/segmentation.py
gaussian_background ¶
Estimate a smooth background via FFT-based Gaussian filtering.
Uses FFT convolution (O(N log N)) so large sigma values are fast.
workers=-1 lets scipy use all available CPU cores for the FFT.
Source code in src/nrxrdct/laue/segmentation.py
gaussian_mixture_2d ¶
Sum of n rotated Gaussians + constant background C (last param). params layout: [A1, x01, y01, sx1, sy1, th1, A2, x02, y02, sx2, sy2, th2, ..., C]
Source code in src/nrxrdct/laue/segmentation.py
get_spot_limits ¶
Return (ymin, ymax, xmin, xmax) for a 2d × 2d ROI centred at (ycen, xcen),
clipped to the image boundaries.
Source code in src/nrxrdct/laue/segmentation.py
hybrid_segmentation ¶
hybrid_segmentation(image: ndarray, mask: ndarray, log_sigmas=None, wth_disk_radius=None, threshold_percentile: float = 99.9, local_threshold: bool = False, local_block_size: int = 256) -> np.ndarray
Segment diffraction spots by combining LoG (large/round spots) and WTH (small/sharp spots) responses.
All scales from both methods are submitted to a single
ThreadPoolExecutor so every allocated CPU is used without
thread-pool nesting or oversubscription. The two families are
thresholded independently at threshold_percentile and the results
are combined with a logical OR.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in src/nrxrdct/laue/segmentation.py
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 | |
label_segmented_image ¶
Label segmented boolean image, clear borders, return: (label_image, n_labels, label_img_rgb)
Source code in src/nrxrdct/laue/segmentation.py
load_images ¶
Load all .tif images in a directory into a 3D array: (Nimages, ny, nx). Uses ProcessPoolExecutor to parallelize skimage.io.imread.
Source code in src/nrxrdct/laue/segmentation.py
measure_peaks ¶
r_squared_image ¶
R^2 = 1 - SS_res / SS_tot, computed on flattened arrays, optionally using boolean mask.
Source code in src/nrxrdct/laue/segmentation.py
reduced_chi_squared ¶
Reduced chi^2 with optional per-pixel noise_std. If noise_std is None, estimate using MAD of residuals.
Source code in src/nrxrdct/laue/segmentation.py
reduced_chi_squared_poisson ¶
reduced_chi_squared_poisson(data, model, n_params: int = 2, gain: float = 1.0, read_noise: float = 0.0, eps: float = 1e-12, mask=None)
Reduced chi^2 assuming Poisson + read noise. Converts ADU->e- using gain. variance = model_e + read_noise^2, clipped by eps.
Source code in src/nrxrdct/laue/segmentation.py
run_segmentation_local ¶
run_segmentation_local(image_stack: ndarray, seg_dir: str, detector_mask: ndarray | None = None, method: str = 'LoG', method_kwargs: dict | None = None, min_size: int = 3, max_size: int = 500, gap_exclude: int = 3, gap_closing: int = 3, bg_sigma: float = 251.0, max_components: int = 1, n_workers: int | None = None, overwrite: bool = False, frame_indices=None) -> list
Run the Laue segmentation pipeline locally using multiple CPU cores.
Mirrors the SLURM worker pipeline (background subtraction → segmentation
→ cleaning → Gaussian fitting → HDF5 output) but runs in-process using
a ProcessPoolExecutor instead of submitting cluster jobs.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in src/nrxrdct/laue/segmentation.py
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 | |
segment_image ¶
segment_image(im_array: ndarray, kernel_size: int = 3, sigma: float = 0.1, iterations: int = 1, threshold: float = None)
Segment image into a boolean mask.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in src/nrxrdct/laue/segmentation.py
simulation_guided_segmentation ¶
simulation_guided_segmentation(image: ndarray, spots: list, mask: ndarray, outpath: str | None = None, *, psf_sigma: float = 1.0, search_radius: int = 7, min_distance: int = 1, min_snr: float = 1.0, bg_sigma: float = 60.0, d: int = 10, r_squared_min: float = 0.8, include_unfitted: bool = True, fit_spots: bool = False, overwrite: bool = False) -> np.ndarray
Simulation-guided peak search optimised for small and faint spots.
Unlike the blind segmentation methods (LoG, WTH, Hybrid), this function
starts from a list of predicted spot positions obtained from
:func:~nrxrdct.laue.simulate_laue_stack or
:func:~nrxrdct.laue.simulate_laue_darwin and restricts the search to
small imagettes around each prediction. This makes it insensitive to
the global frame background and is effective for:
- Faint or small spots that fall below the threshold of blind methods.
- Dense patterns where blind thresholding merges neighbouring spots.
- Frames with strong parasitic background (fluorescence streaks, beam stop shadows) that produce many false positives in a global search.
The output is fully compatible with the standard pipeline —
:func:convert_spotsfile2peaklist, :func:plot_measured_vs_simulated,
and :func:~nrxrdct.laue.fitting.fit_orientation_stack all accept it
unchanged. At the :class:~nrxrdct.laue.LayeredMap scale the function
is wrapped by
:meth:~nrxrdct.laue.LayeredMap.submit_guided_segmentation
for parallel SLURM execution.
Per-spot pipeline¶
- Extract a
(2·search_radius) × (2·search_radius)imagette from the background-subtracted image centred on the predicted position. - Apply a light Gaussian smoothing (sigma = psf_sigma) to suppress single-pixel noise before peak finding.
- Run :func:
skimage.feature.peak_local_maxwith minimum peak separation min_distance to collect all local maxima candidates. - For each candidate: compute SNR against a background annulus
(outer radius 3×search_radius, inner exclusion search_radius)
so that a bright neighbouring streak does not inflate the threshold for
a faint spot sitting next to it. Reject if
SNR < min_snr. - Optionally fit a 2-D rotated Gaussian to the raw image ROI around each accepted candidate for sub-pixel position refinement.
- Write results to HDF5 in the same format as :func:
write_h5_spotsfile, fully compatible with :func:convert_spotsfile2peaklist.
Note that multiple peaks can be found per predicted position — useful when the simulation predicts one reflection but the actual pattern contains a satellite or split spot nearby.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in src/nrxrdct/laue/segmentation.py
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 | |
write_h5_spotsfile ¶
write_h5_spotsfile(image_array: ndarray, regionprops, outpath: str = 'segmented_spotsfile.h5', d: int = 10, overwrite: bool = False, max_components: int = 2, include_unfitted: bool = True, r_squared_min: float = 0.9, fit_spots: bool = True)
Writes per-spot images and fitted parameters into an HDF5 file.
Tries to fit a Gaussian mixture on a cropped ROI of size 2d around the
region weighted centroid. Spots whose fit reaches r² ≥ r_squared_min are
stored in spot_{ii}_{jj} groups (jj = 1, 2, …).
| Parameters: |
|
|---|
Source code in src/nrxrdct/laue/segmentation.py
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 | |
write_peaklist_dat ¶
Write an (N, 9) peaklist array to a space-separated DAT file.
The column order matches :func:convert_spotsfile2peaklist:
peak_X peak_Y peak_I peak_fwaxmaj peak_fwaxmin
peak_inclination Xdev Ydev peak_bkg.
A .dat extension is appended automatically if absent.