Repository navigation
Expand file tree
/
Copy pathplot_extractor.py
More file actions
4937 lines (4612 loc) · 233 KB
/
Copy pathplot_extractor.py
File metadata and controls
4937 lines (4612 loc) · 233 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
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
"""PlotExtractor — simple desktop tool to extract one raw image (and optionally a
deskewed orthomosaic crop) per plot from a Metashape project.
Inputs: Metashape project (.psx), plot boundaries (.shp or .geojson), optional raw
image folder (fallback when the project's photo paths are stale), output folder,
margin, images per plot, limit.
Runs on any Python 3.9+ with: Metashape (standalone wheel), Pillow, pyshp.
Launch with PlotExtractor.bat or: python plot_extractor.py
"""
import os, sys, re, json, math, csv, shutil, threading, queue, traceback
# Metashape standalone module license (floating license server config lives here)
os.environ.setdefault('agisoft_LICENSE', r"C:\Program Files\Agisoft\Licensing\licenses")
# When frozen (PyInstaller .exe) config.json lives NEXT TO the exe (writable);
# from source it lives next to this script.
if getattr(sys, 'frozen', False):
APP_DIR = os.path.dirname(sys.executable)
else:
APP_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(APP_DIR, "config.json")
RAW_EXTS = ['.jpg', '.jpeg', '.tif', '.tiff', '.png']
AUTO_ID = "(auto: plot id field or 1..N)"
FRAME_CHOICES = ["Whole plot first, else the photo holding the largest part",
"Nadir tiers first, then coverage (earlier ranking)"]
# --------------------------------------------------------------------------
# Plot boundary file reading (no Metashape required)
# --------------------------------------------------------------------------
def _ring_area(ring):
s = 0.0
for (x0, y0), (x1, y1) in zip(ring, ring[1:] + ring[:1]):
s += x0 * y1 - x1 * y0
return abs(s) / 2
def _ring_area_m2(ring_wgs):
"""Area (m^2) of a WGS84 lon/lat ring via local metres-per-degree shoelace."""
if len(ring_wgs) < 3:
return 0.0
cy = sum(q[1] for q in ring_wgs) / len(ring_wgs)
mlon = 111320 * math.cos(math.radians(cy))
mlat = 110540
pts = [(lon * mlon, lat * mlat) for lon, lat in ring_wgs]
s = 0.0
for (x0, y0), (x1, y1) in zip(pts, pts[1:] + pts[:1]):
s += x0 * y1 - x1 * y0
return abs(s) / 2
def _point_in_ring(x, y, ring):
"""Ray-cast point-in-polygon for an open ring of (x,y)."""
inside = False
n = len(ring)
for i in range(n):
x0, y0 = ring[i]
x1, y1 = ring[(i + 1) % n]
if (y0 > y) != (y1 > y):
xint = x0 + (y - y0) * (x1 - x0) / (y1 - y0)
if x < xint:
inside = not inside
return inside
def _clip_poly_rect(poly, w, h):
"""Sutherland-Hodgman clip of a polygon [(x,y), ...] to the rectangle
[0,w] x [0,h]. Returns the clipped polygon (possibly empty)."""
def clip(pts, inside, inter):
out = []
n = len(pts)
for i in range(n):
a = pts[i]
b = pts[(i + 1) % n]
ia, ib = inside(a), inside(b)
if ia:
out.append(a)
if not ib:
out.append(inter(a, b))
elif ib:
out.append(inter(a, b))
return out
def ix(a, b, xc): # crossing of a-b with x=xc
t = (xc - a[0]) / (b[0] - a[0]) if b[0] != a[0] else 0.0
return (xc, a[1] + t * (b[1] - a[1]))
def iy(a, b, yc): # crossing of a-b with y=yc
t = (yc - a[1]) / (b[1] - a[1]) if b[1] != a[1] else 0.0
return (a[0] + t * (b[0] - a[0]), yc)
pts = list(poly)
for inside, inter in (
(lambda p: p[0] >= 0.0, lambda a, b: ix(a, b, 0.0)),
(lambda p: p[0] <= w, lambda a, b: ix(a, b, w)),
(lambda p: p[1] >= 0.0, lambda a, b: iy(a, b, 0.0)),
(lambda p: p[1] <= h, lambda a, b: iy(a, b, h))):
if not pts:
return []
pts = clip(pts, inside, inter)
return pts
def frame_coverage(quad_px, w, h):
"""Fraction (0..1) of a plot quad, projected into a w x h frame, that is
actually inside the frame. Exact polygon clip - far more informative than
counting how many of the 4 corners land in the image (the old measure),
which is 2/4 for both a frame holding 51% of the plot and one holding 95%."""
a0 = _ring_area(quad_px)
if a0 <= 1e-9:
return 0.0
cl = _clip_poly_rect(quad_px, float(w), float(h))
if len(cl) < 3:
return 0.0
return max(0.0, min(1.0, _ring_area(cl) / a0))
# --------------------------------------------------------------------------
# Exact rectification (projected mesh) + minimum-error seam
# --------------------------------------------------------------------------
MESH_STEP_PX = 96 # target output-pixel size of one mesh cell
MESH_MAX_CELLS = 512 # per axis
def mesh_dims(wpx, hpx, step=MESH_STEP_PX):
"""Number of mesh cells across/down for an output crop of wpx x hpx.
The cell size matters because the plot surface is NOT smooth at plot scale:
the seed ridges are ~1-3 cm high and ~20 cm apart, so a mesh coarser than
the ridge spacing cannot follow the relief and the two frames of a stitch
still disagree over a ridge. Measured cross-frame misregistration on OZ
Barley York: 15-24 px mean with one quad, 4-6 px at 256 px cells,
~1-2 px at 64-96 px cells."""
nx = max(2, min(MESH_MAX_CELLS, int(math.ceil(wpx / float(step)))))
ny = max(2, min(MESH_MAX_CELLS, int(math.ceil(hpx / float(step)))))
return nx, ny
def mesh_uv_nodes(ring, nx, ny):
"""Ground positions of the (nx+1) x (ny+1) mesh nodes, bilinearly spread over
the plot quad `ring` = [A, B, C, D]. u runs A->B (output x), v runs A->D
(output y) - the same convention the QUAD warp used for its 4 corners."""
A, B, C, D = ring
out = []
for j in range(ny + 1):
v = j / float(ny)
for i in range(nx + 1):
u = i / float(nx)
out.append([(1 - u) * (1 - v) * A[k] + u * (1 - v) * B[k]
+ u * v * C[k] + (1 - u) * v * D[k] for k in (0, 1)])
return out
def build_pil_mesh(src_nodes, nx, ny, wpx, hpx):
"""Turn a grid of source-pixel coordinates into PIL's MESH transform data.
Each cell becomes (destination box, source quad). Because every frame is
sampled at the SAME ground nodes, two frames rectified through their own
meshes land on the ground identically - which is what stops a plant from
appearing twice across a stitch boundary. Cells with a node that failed to
project are dropped (they fall outside the frame anyway and would be black).
"""
mesh = []
for j in range(ny):
y0 = int(round(hpx * j / float(ny)))
y1 = int(round(hpx * (j + 1) / float(ny)))
if y1 <= y0:
continue
for i in range(nx):
x0 = int(round(wpx * i / float(nx)))
x1 = int(round(wpx * (i + 1) / float(nx)))
if x1 <= x0:
continue
ul = src_nodes[j * (nx + 1) + i]
ur = src_nodes[j * (nx + 1) + i + 1]
ll = src_nodes[(j + 1) * (nx + 1) + i]
lr = src_nodes[(j + 1) * (nx + 1) + i + 1]
if ul is None or ur is None or ll is None or lr is None:
continue
# PIL quad order: upper-left, lower-left, lower-right, upper-right
mesh.append(((x0, y0, x1, y1),
(ul[0], ul[1], ll[0], ll[1], lr[0], lr[1], ur[0], ur[1])))
return mesh
def min_error_seam(np, g_old, g_new, filled, vmask, slack=300, bias=0.05,
maxstep=4):
"""Choose where two frames should hand over to each other.
`filled` = pixels the composite already holds, `vmask` = pixels the new frame
can supply. Letting the new frame fill only the holes puts the boundary
exactly on the old frame's footprint edge, wherever that happens to land -
including straight through a seedling, which is then drawn twice because its
top is displaced differently in the two views. So the boundary is allowed to
move up to `slack` pixels back into the overlap and is routed along the path
where the two frames look most alike, i.e. over bare soil. Classic
minimum-error boundary cut, solved with dynamic programming.
`slack` is deliberately small (300 px is ~10 cm here, several times a
seedling) and `bias` pulls the path back towards the footprint edge: the
point is to step around a plant, NOT to hand half the plot to a second
frame. Letting the seam settle mid-overlap looks tidy but throws away the
best frame's pixels over a large area.
Returns a dict (take-mask, path, orientation) or None when the geometry
isn't a clean band, in which case the caller falls back to plain hole
filling.
"""
ov = vmask & filled
need = vmask & (~filled)
if not need.any() or ov.sum() < 5000:
return None
# Which way does the boundary run? Count membership flips between vertical
# vs horizontal neighbours; the seam is a function of the other axis.
m = need.astype(np.int8) - ov.astype(np.int8)
flips_v = int(np.count_nonzero(np.diff(m, axis=0))) # changes down a column
flips_h = int(np.count_nonzero(np.diff(m, axis=1))) # changes along a row
transposed = flips_h > flips_v
if transposed:
g_old = g_old.T; g_new = g_new.T
ov = ov.T; need = need.T; vmask = vmask.T
H, W = ov.shape
idx = np.arange(H)[:, None]
ov_any = ov.any(0)
need_any = need.any(0)
active = ov_any & need_any
if active.sum() < 0.2 * W:
return None
# per-column overlap band and which side of it the new pixels sit on
big = H + 10
lo = np.where(ov_any, np.where(ov, idx, big).min(0), 0)
hi = np.where(ov_any, np.where(ov, idx, -1).max(0), -1)
need_c = np.where(need_any, np.where(need, idx, 0).sum(0) /
np.maximum(need.sum(0), 1), 0.0)
ov_c = np.where(ov_any, np.where(ov, idx, 0).sum(0) /
np.maximum(ov.sum(0), 1), 0.0)
side_col = np.sign(need_c - ov_c)[active]
if side_col.size == 0:
return None
side = 1.0 if side_col.sum() >= 0 else -1.0 # +1: new frame is BELOW
# The plain hole-fill boundary, per column: the last overlap row on the side
# the new pixels come from. The seam may retreat up to `slack` from it.
edge = hi if side > 0 else lo
slack = max(8, int(slack))
if side > 0:
Lo = int(max(0, edge[active].min() - slack))
Hi = int(min(H - 1, edge[active].max()))
else:
Lo = int(max(0, edge[active].min()))
Hi = int(min(H - 1, edge[active].max() + slack))
if Hi - Lo < 2:
return None
band = slice(Lo, Hi + 1)
BH = Hi - Lo + 1
if BH * W > 120_000_000: # keep the DP affordable
return None
cost = np.abs(g_old[band].astype(np.float32) - g_new[band].astype(np.float32))
rows = np.arange(Lo, Hi + 1, dtype=np.float32)[:, None]
# legal: inside the overlap AND within `slack` of this column's own edge
eg = edge[None, :].astype(np.float32)
if side > 0:
legal = ov[band] & (rows <= eg) & (rows >= eg - slack)
else:
legal = ov[band] & (rows >= eg) & (rows <= eg + slack)
PEN = 1e4
cost = np.where(legal, cost, PEN)
if bias: # pull back towards the footprint edge
cost = cost + bias * np.abs(rows - eg)
# DP left->right. The step limit has to be more than 1 row per column: a
# seedling is only ~30-90 px across, and at +/-1 the path needs ~50 columns
# to descend past it and 50 more to climb back, so it could not detour around
# anything narrower than ~100 px - exactly the obstacles that matter here.
ms = max(1, int(maxstep))
offs = list(range(-ms, ms + 1)) # back value = prev row - cur row
acc = np.empty((BH, W), np.float32)
back = np.zeros((BH, W), np.int8)
acc[:, 0] = cost[:, 0]
stk = np.empty((len(offs), BH), np.float32)
ar = np.arange(BH)
offa = np.asarray(offs, np.int8)
for c in range(1, W):
prev = acc[:, c - 1]
for i, d in enumerate(offs):
col = stk[i]
if d == 0:
col[:] = prev
elif d < 0: # came from |d| rows above
col[:-d] = np.inf
col[-d:] = prev[:d]
else: # came from d rows below
col[-d:] = np.inf
col[:-d] = prev[d:]
k = np.argmin(stk, 0)
acc[:, c] = stk[k, ar] + cost[:, c]
back[:, c] = offa[k]
path = np.empty(W, np.int32)
path[W - 1] = int(np.argmin(acc[:, W - 1]))
for c in range(W - 1, 0, -1):
path[c - 1] = path[c] + int(back[path[c], c])
path = np.clip(path + Lo, 0, H - 1)
# columns with no overlap keep the plain hole-fill boundary
take = need.copy()
if side > 0:
seam_take = idx > path[None, :]
else:
seam_take = idx < path[None, :]
take |= (ov & seam_take & active[None, :])
take &= vmask
return dict(take=(take.T if transposed else take), path=path,
transposed=transposed, side=side, active=active,
cut=float(np.mean(np.abs(np.diff(path)))))
def feather_seam(np, out, ra, seam, width=600, halfband=24, block=256):
"""Erase the residual brightness/colour LINE along a stitch boundary WITHOUT
mixing pixels from two frames.
The step across the seam is measured column-by-column in a thin band on
either side, smoothed hard along the seam, and then added to the incoming
frame as an offset that fades to zero `width` pixels away. Only a smooth
low-frequency offset is applied - every output pixel keeps 100% of one
frame's texture, so nothing is averaged and nothing is duplicated.
`ra` (float32) is corrected IN PLACE and clipped to 0..255. Everything is
done in row blocks: a 13000x3400 crop would otherwise need ~1 GB of
full-size float temporaries per worker, times however many cores are busy.
"""
path = seam['path']
side = seam['side']
active = seam['active']
# transpose() returns a view, so in-place writes reach the caller's array
o = out.transpose(1, 0, 2) if seam['transposed'] else out
r = ra.transpose(1, 0, 2) if seam['transposed'] else ra
H, W = o.shape[:2]
pf = path[None, :].astype(np.float32)
sgn = np.float32(1.0 if side >= 0 else -1.0)
def rel_of(y0, y1):
rows = np.arange(y0, y1, dtype=np.float32)[:, None]
return (rows - pf) * sgn # <0 = old side, >0 = new side
# --- measure the step across the seam, per column, in thin bands ---
no = np.zeros(W, np.float32); nn = np.zeros(W, np.float32)
so = np.zeros((3, W), np.float32); sn = np.zeros((3, W), np.float32)
for y0 in range(0, H, block):
y1 = min(H, y0 + block)
rel = rel_of(y0, y1)
ob = (rel < 0) & (rel >= -halfband)
nb = (rel >= 0) & (rel <= halfband)
if not (ob.any() or nb.any()):
continue
no += ob.sum(0); nn += nb.sum(0)
for c in range(3):
so[c] += (o[y0:y1, :, c] * ob).sum(0)
sn[c] += (r[y0:y1, :, c] * nb).sum(0)
good = (no > 4) & (nn > 4) & active
step = np.zeros((3, W), np.float32)
if good.any():
k = max(3, int(W / 12) | 1)
ker = np.ones(k, np.float32)
den = np.convolve(good.astype(np.float32), ker, 'same')
for c in range(3):
d = np.zeros(W, np.float32)
d[good] = so[c][good] / no[good] - sn[c][good] / nn[good]
# smooth hard along the seam, and carry the value into dead columns
num = np.convolve(np.where(good, d, 0.0), ker, 'same')
step[c] = np.clip(np.where(den > 0, num / np.maximum(den, 1e-6), 0.0),
-60.0, 60.0)
# --- apply it, fading out away from the seam ---
for y0 in range(0, H, block):
y1 = min(H, y0 + block)
ramp = np.clip(1.0 - np.maximum(rel_of(y0, y1), 0.0) / float(width),
0.0, 1.0)
for c in range(3):
r[y0:y1, :, c] += step[c][None, :] * ramp
np.clip(ra, 0, 255, out=ra)
return ra
def _tilt_from_vertical(pu):
"""Acute angle (deg, 0-90) between a plot's long edge and the image vertical,
from its 4 corners [A,B,C,D] in pixel coords. 0 = already upright."""
if len(pu) < 4:
return 0.0
ax, ay = pu[0]
dx, dy = pu[3]
a = abs(math.degrees(math.atan2(dx - ax, dy - ay))) % 180.0
return min(a, 180.0 - a)
def _geojson_crs(data):
"""Extract a Metashape-parseable CRS spec from a GeoJSON 'crs' member, if any.
Handles 'EPSG:xxxx', 'EPSG::xxxx' and 'urn:ogc:def:crs:EPSG::xxxx'."""
name = (((data.get('crs') or {}).get('properties')) or {}).get('name', '')
m = re.search(r'EPSG:*(\d+)', str(name), re.I)
if m:
return f"EPSG::{m.group(1)}"
return None
def read_plot_file(path):
"""Return (plots, crs_def, field_names).
plots = [{ring: [[x,y],...] (open, exterior only), props: {...}}, ...]
crs_def = WKT string or 'EPSG::xxxx'; None means 'assume WGS84 lon/lat'."""
ext = os.path.splitext(path)[1].lower()
if ext in ('.geojson', '.json'):
with open(path, encoding='utf-8') as f:
data = json.load(f)
plots, fields = [], []
for ft in data.get('features', []):
geom = ft.get('geometry') or {}
gtype, coords = geom.get('type'), geom.get('coordinates')
if gtype == 'Polygon':
ring = coords[0]
elif gtype == 'MultiPolygon':
ring = max(coords, key=lambda poly: _ring_area(poly[0]))[0]
else:
continue
ring = [list(p[:2]) for p in ring]
if len(ring) > 1 and ring[0] == ring[-1]:
ring = ring[:-1]
props = ft.get('properties') or {}
for k in props:
if k not in fields:
fields.append(k)
plots.append(dict(ring=ring, props=props))
return plots, _geojson_crs(data), fields
if ext == '.shp':
import shapefile
rdr = shapefile.Reader(path)
fields = [f[0] for f in rdr.fields[1:]]
plots = []
for sr in rdr.iterShapeRecords():
shp = sr.shape
if 'POLYGON' not in shp.shapeTypeName.upper():
continue
parts = list(shp.parts) + [len(shp.points)]
rings = [shp.points[parts[i]:parts[i + 1]] for i in range(len(parts) - 1)]
ring = max(rings, key=_ring_area) # exterior ring
ring = [list(p[:2]) for p in ring]
if len(ring) > 1 and ring[0] == ring[-1]:
ring = ring[:-1]
plots.append(dict(ring=ring, props=dict(zip(fields, sr.record))))
wkt = None
prj = os.path.splitext(path)[0] + '.prj'
if os.path.exists(prj):
with open(prj) as f:
wkt = f.read().strip()
return plots, wkt, fields
raise ValueError("Unsupported plot boundary file (use .shp or .geojson): " + path)
def pick_id_field(fields):
"""Best guess for the plot-id attribute."""
low = {f.lower(): f for f in fields}
for cand in ('plot_id', 'plotid', 'plot', 'id'):
if cand in low:
return low[cand]
return None
def safe_name(val):
s = str(val).strip()
return "".join(c if (c.isalnum() or c in '-_.') else '_' for c in s) or "unnamed"
# --------------------------------------------------------------------------
# Extraction engine (worker thread)
# --------------------------------------------------------------------------
def _periodicity(prof):
"""Strength of the dominant ridge/row oscillation in a 1-D profile."""
import numpy as np
n = len(prof)
if n < 32:
return 0.0
x = np.arange(n, dtype='float64')
p = prof - np.polyval(np.polyfit(x, prof, 3), x) # drop illumination trend
f = np.abs(np.fft.rfft((p - p.mean()) * np.hanning(n)))
lo, hi = max(2, n // 120), max(3, n // 5)
if hi <= lo:
return 0.0
band = f[lo:hi]
return float(band.max() / (band.mean() + 1e-9))
def _across_row_axis(im, hint=None):
"""Which image axis runs ACROSS the planted rows: 'x' (rows vertical) or
'y' (rows horizontal). Rows run along the plot's LONG axis, so the
across-row axis is the SHORT image axis - which side that is depends on the
shapefile's vertex order, so it must be measured, not assumed. Near-square
crops fall back to whichever axis carries the stronger row periodicity."""
if hint in ('x', 'y'):
return hint
W, H = im.size
ar = W / float(H or 1)
if ar <= 0.8:
return 'x'
if ar >= 1.25:
return 'y'
import numpy as np
a = np.asarray(im.resize((min(W, 700), min(H, 700))).convert('L')).astype('float32')
return 'x' if _periodicity(a.mean(0)) >= _periodicity(a.mean(1)) else 'y'
def _refit_gcps_box(gcps, x0, y0, x1, y1):
"""Rebuild 4 corner GCPs for a sub-window (x0,y0,x1,y1) of the current frame.
Same bilinear refit used when auto-fit trims a crop: fit
v = a + b*row + c*col + d*row*col through the existing corner GCPs, then
evaluate at the new corners. Filtering GCPs by whether they fall inside the
window is NOT equivalent - the corners always sit outside it, so filtering
leaves none at all.
"""
if len(gcps) < 4:
return [(r - y0, c - x0, lon, lat, z) for (r, c, lon, lat, z) in gcps]
A = [[1.0, g[0], g[1], g[0] * g[1]] for g in gcps]
coefs = []
for k in (2, 3, 4):
coefs.append(_lstsq4(A, [g[k] for g in gcps]))
out = []
for r_src, r_dst in ((y0, 0.0), (y1, float(y1 - y0))):
for c_src, c_dst in ((x0, 0.0), (x1, float(x1 - x0))):
vals = [cf[0] + cf[1] * r_src + cf[2] * c_src + cf[3] * r_src * c_src
for cf in coefs]
out.append((r_dst, c_dst, vals[0], vals[1], vals[2]))
return out
def _lstsq4(A, b):
"""Least-squares solve of a 4-column design matrix without numpy.
Used to refit GCPs when auto-fit trims the crop (see _apply_auto_fit). Solves
the 4x4 normal equations by Gaussian elimination with partial pivoting; that
is plenty for 4 corner points and keeps this module free of a numpy import at
module scope.
"""
n = 4
M = [[sum(A[k][i] * A[k][j] for k in range(len(A))) for j in range(n)]
+ [sum(A[k][i] * b[k] for k in range(len(A)))] for i in range(n)]
for i in range(n):
p = max(range(i, n), key=lambda r: abs(M[r][i]))
if abs(M[p][i]) < 1e-12:
raise ValueError("singular GCP design matrix")
M[i], M[p] = M[p], M[i]
inv = 1.0 / M[i][i]
for j in range(i, n + 1):
M[i][j] *= inv
for r in range(n):
if r == i:
continue
f = M[r][i]
if f:
for j in range(i, n + 1):
M[r][j] -= f * M[i][j]
return [M[i][n] for i in range(n)]
def detect_row_fit(im, rows_target=0, mode='width', buffer_frac=0.5, across=None):
"""Find the planted crop rows in a rectified plot image and return a pixel
crop box that tightly encloses them. Uses the ROW/RIDGE periodicity
(detrended-brightness oscillation) reinforced by greenness, so it works even
before emergence and doesn't chase stray edge grass.
Because the caller renders WIDER than the grid boundary, this can INCLUDE rows
the grid clipped, then crop to exactly `rows_target` rows (or all detected).
mode: 'width' (band width, keep original centre) | 'width_shift' (band as
detected, recentre on rows) | 'width_length' (also trim along-row ends).
`across` is the image axis running across the rows ('x' = rows vertical,
'y' = rows horizontal); None decides from the crop shape.
Returns dict(box=(x0,x1,y0,y1), rows, spacing_px, peaks, across) or None.
"""
import numpy as np
from PIL import Image
if _across_row_axis(im, across) == 'y':
# rows are horizontal bands here: detect on the transposed image (which
# puts them upright) and map the box back, so the trimming happens
# ACROSS the rows instead of along the plot's length
r = detect_row_fit(im.transpose(Image.TRANSPOSE), rows_target=rows_target,
mode=mode, buffer_frac=buffer_frac, across='x')
if r:
bx0, bx1, by0, by1 = r['box']
r['box'] = (by0, by1, bx0, bx1)
r['across'] = 'y'
return r
W0, H0 = im.size
ds = max(1, int(max(W0, H0) / 1800))
a = np.asarray(im.resize((max(1, W0 // ds), max(1, H0 // ds))).convert('RGB')
).astype('float32')
H, W, _ = a.shape
def sm(v, k):
return np.convolve(v, np.ones(2 * k + 1) / (2 * k + 1), 'same') if k > 0 else v
lum = a.mean(2)
r, g, b = a[..., 0], a[..., 1], a[..., 2]
exg = np.clip(2 * g - r - b, 0, None)
# ignore uncovered pixels (BLACK or WHITE nodata) so column means reflect
# only real imagery
valid = ((lum > 12) & (a.min(2) < 245)).astype('float32')
vcount = valid.sum(0)
denom = np.maximum(vcount, 1.0)
lum_col = (lum * valid).sum(0) / denom
exg_col = (exg * valid).sum(0) / denom
lum_col[vcount < 0.2 * H] = np.median(lum_col) # mostly-black columns -> neutral
trend = sm(lum_col, max(3, W // 15))
osc = lum_col - trend
# row spacing via FFT of the cross-row oscillation
f = np.abs(np.fft.rfft((osc - osc.mean()) * np.hanning(W)))
f[:max(2, W // 200)] = 0
lo, hi = max(2, W // 120), max(3, W // 5)
k = lo + int(np.argmax(f[lo:hi])) if hi > lo else 0
sp = (W / k) if k > 0 else (W / 8.0)
# row centres from greenness (fallback: ridge crests)
sig = sm(exg_col, max(1, int(sp * 0.25)))
if sig.max() < 1e-3:
sig = sm(np.clip(osc, 0, None), max(1, int(sp * 0.25)))
sign = sig / (sig.max() + 1e-6)
sep = max(2, int(sp * 0.55))
thr = max(0.12, float(np.percentile(sign, 55)))
peaks = []
i = 0
while i < W:
if sign[i] >= thr:
j = min(W, i + sep)
c = i + int(np.argmax(sign[i:j]))
if not peaks or c - peaks[-1] >= sep:
peaks.append(c)
i = c + sep
else:
i += 1
if len(peaks) < 2:
return None
if rows_target and rows_target < len(peaks):
best = None
for s in range(0, len(peaks) - rows_target + 1):
grp = peaks[s:s + rows_target]
score = abs((grp[0] + grp[-1]) / 2.0 - W / 2.0)
if best is None or score < best[0]:
best = (score, grp)
grp = best[1]
else:
grp = peaks
half = sp * buffer_frac
bx0 = max(0.0, grp[0] - half)
bx1 = min(float(W), grp[-1] + half)
if mode == 'width':
bw = bx1 - bx0
cc = W / 2.0
x0 = max(0.0, cc - bw / 2.0)
x1 = min(float(W), cc + bw / 2.0)
else:
x0, x1 = bx0, bx1
y0, y1 = 0, H
if mode == 'width_length':
ry = sm(exg.mean(1), max(2, H // 60))
ryn = ry / (np.percentile(ry, 95) + 1e-6)
yon = np.where(ryn > 0.20)[0]
if len(yon) > H * 0.3:
y0, y1 = int(yon[0]), int(yon[-1])
return dict(box=(int(x0 * ds), int(x1 * ds), int(y0 * ds), int(y1 * ds)),
rows=len(grp), spacing_px=sp * ds, across='x',
peaks=[int(p * ds) for p in grp])
def read_psx_chunks(psx_path):
"""List chunk labels in a .psx by reading its project zips directly - no
Metashape/licence needed. Returns (labels, active_label); ([],None) on error."""
import zipfile
try:
base = psx_path[:-4] if psx_path.lower().endswith('.psx') else psx_path
files_dir = base + '.files'
with zipfile.ZipFile(os.path.join(files_dir, 'project.zip')) as z:
docxml = z.read('doc.xml').decode('utf-8', 'replace')
m = re.search(r'active_id="(\d+)"', docxml)
active_id = m.group(1) if m else None
entries = re.findall(r'<chunk id="(\d+)" path="([^"]+)"', docxml)
labels, active_label = [], None
for cid, cpath in entries:
lbl = f"chunk {cid}"
try:
with zipfile.ZipFile(os.path.join(files_dir, cpath)) as cz:
cxml = cz.read('doc.xml').decode('utf-8', 'replace')
mm = re.search(r'label="([^"]*)"', cxml)
if mm and mm.group(1):
lbl = mm.group(1)
except Exception:
pass
labels.append(lbl)
if cid == active_id:
active_label = lbl
return labels, active_label
except Exception:
return [], None
_DTYPE_CACHE = {}
def _tif_dtype(path):
"""Sample type of a TIFF ('uint8', 'uint16', ...), None for other files."""
if not str(path).lower().endswith(('.tif', '.tiff')):
return None
if path not in _DTYPE_CACHE:
try:
import rasterio
with rasterio.open(path) as d:
_DTYPE_CACHE[path] = d.dtypes[0]
except Exception:
_DTYPE_CACHE[path] = None
return _DTYPE_CACHE[path]
def _image_size(path):
"""(width, height) of an image without decoding it."""
if _tif_dtype(path):
import rasterio
with rasterio.open(path) as d:
return d.width, d.height
from PIL import Image
with Image.open(path) as im:
return im.size
def _read_box(path, x0=0, y0=0, w=None, h=None):
"""HxWx3 array of a TIFF (bands 1-3), whole or the box, values unchanged."""
import warnings
import rasterio
from rasterio.windows import Window
with warnings.catch_warnings():
warnings.simplefilter('ignore')
with rasterio.open(path) as d:
win = None if w is None else Window(x0, y0, w, h)
a = d.read([1, 2, 3] if d.count >= 3 else [1, 1, 1], window=win)
return a.transpose(1, 2, 0)
def _to8(arr):
"""16-bit -> 8-bit, round(value / 257) (65535 -> 255)."""
import numpy as np
if arr.dtype == np.uint8:
return arr
return np.clip(np.round(arr.astype(np.float32) / 257.0), 0, 255).astype(np.uint8)
def run_extraction(p, log, set_progress, cancel):
"""p: dict of parameters. log(str), set_progress(done,total), cancel: threading.Event"""
import Metashape as ms
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
lic = ms.License()
if not lic.valid:
raise RuntimeError("No valid Metashape license found (license server unreachable?).")
# --- use the GPU for Metashape compute (ortho raster export etc.) if present ---
try:
gpus = list(ms.app.enumGPUDevices())
if gpus:
def _gname(g):
try:
return g['name'] if isinstance(g, dict) else getattr(g, 'name', str(g))
except Exception:
return 'GPU'
ms.app.gpu_mask = (1 << len(gpus)) - 1 # enable every device
ms.app.cpu_enable = True # keep CPU helping alongside GPU
log(f"GPU acceleration ON: {len(gpus)} device(s) - "
+ ", ".join(_gname(g) for g in gpus))
else:
log("GPU acceleration: no CUDA/OpenCL GPU detected - running on CPU")
except Exception as e:
log(f"GPU setup skipped ({e}) - running on CPU")
plots, wkt, fields = read_plot_file(p['plots'])
if not plots:
raise RuntimeError("No polygons found in " + p['plots'])
log(f"Loaded {len(plots)} plot polygons from {os.path.basename(p['plots'])}")
wgs84 = ms.CoordinateSystem("EPSG::4326")
override = (p.get('crs_override') or '').strip()
if override and override.lower() != 'auto':
spec = override if not override.isdigit() else f"EPSG::{override}"
spec = re.sub(r'^EPSG:+', 'EPSG::', spec, flags=re.I)
try:
src_crs = ms.CoordinateSystem(spec)
except Exception:
raise RuntimeError(f"Could not parse CRS override '{override}'. "
"Use an EPSG code like 28350, or leave it on auto.")
log(f"Plot CRS (user override): {src_crs.name}")
elif wkt:
try:
src_crs = ms.CoordinateSystem(wkt)
except Exception:
raise RuntimeError("Could not parse the coordinate system stored in the plot "
"file. Set the 'Plot CRS' EPSG code manually.")
log(f"Plot CRS (from file): {src_crs.name}")
else:
src_crs = wgs84
xs = [abs(v) for pl in plots[:5] for v in pl['ring'][0]]
if xs and max(xs) > 360:
raise RuntimeError("The plot file carries no CRS information and its coordinates "
"do not look like lon/lat degrees. Set the 'Plot CRS' EPSG "
"code (e.g. 28350 for GDA2020 / MGA zone 50).")
log("Plot CRS: assumed WGS84 lon/lat (file carries no CRS)")
# plot ids
id_field = p.get('id_field')
if id_field in (None, '', AUTO_ID):
id_field = pick_id_field(fields)
for i, pl in enumerate(plots, 1):
pl['id'] = safe_name(pl['props'].get(id_field, i)) if id_field else str(i)
if id_field:
log(f"Plot IDs from field '{id_field}'")
else:
log("No plot-id field found; using sequential IDs 1..N")
only = p.get('plot_filter') # optional: process only these plot ids
if only:
want = set(str(x) for x in only)
plots = [pl for pl in plots if str(pl['id']) in want]
log(f"Plot filter: {len(plots)} of the requested {len(want)} plot id(s)")
limit = int(p.get('limit') or 0)
if limit:
plots = plots[:limit]
log(f"Limit: first {limit} plots only (test run)")
log("Opening Metashape project ...")
doc = ms.Document()
doc.open(p['psx'], read_only=True)
chunks = [c for c in doc.chunks if c is not None]
if not chunks:
raise RuntimeError("Project has no chunks.")
log("Project chunks: " + ", ".join(f"'{c.label}'" for c in chunks))
want = (p.get('chunk') or '').strip()
ch = None
if want and want.lower() not in ('active', '(active)', 'auto', ''):
for c in chunks: # match by label first
if (c.label or '').strip() == want:
ch = c
break
if ch is None: # then by index
try:
i = int(want)
if 0 <= i < len(chunks):
ch = chunks[i]
except ValueError:
pass
if ch is None:
raise RuntimeError(
f"Chunk '{want}' not found. Available: "
+ ", ".join(f"'{c.label}'" for c in chunks))
if ch is None:
ch = doc.chunk or chunks[0] # fall back to active
if ch is None:
raise RuntimeError("Project has no chunk.")
log(f"Using chunk: '{ch.label}' ({len(ch.cameras)} cameras)")
if ch.crs is None or ch.transform.matrix is None:
raise RuntimeError("Project chunk is not georeferenced (no CRS / transform).")
T = ch.transform.matrix
Tinv = T.inv()
dem = ch.elevation
cams = [c for c in ch.cameras if c.transform]
log(f"Chunk '{ch.label}': {len(cams)} aligned cameras, CRS: {ch.crs.name}, "
f"DEM: {'yes' if dem else 'NO'}, orthomosaic: {'yes' if ch.orthomosaic else 'no'}")
if not cams:
raise RuntimeError("No aligned cameras in the project.")
def tr(v, a, b):
return ms.CoordinateSystem.transform(v, a, b)
# fallback ground height = chunk region centre height (chunk CRS)
centre_chunk = ch.crs.project(T.mulp(ch.region.center))
z_fallback = centre_chunk.z
# sanity check: does the first plot actually sit near the project?
p0 = plots[0]['ring'][0]
p0w = tr(ms.Vector([p0[0], p0[1], 0]), src_crs, wgs84)
c0w = tr(ms.Vector([centre_chunk.x, centre_chunk.y, centre_chunk.z]), ch.crs, wgs84)
dist_km = math.hypot((p0w.x - c0w.x) * 111.32 * math.cos(math.radians(c0w.y)),
(p0w.y - c0w.y) * 110.54)
if dist_km > 10:
log(f"[!] WARNING: plots are ~{dist_km:.0f} km away from the project centre - "
"wrong CRS or wrong project? Continuing anyway ...")
def ground_z(pt_chunk_2d):
if dem is not None:
z = dem.altitude(pt_chunk_2d)
if z is not None and not math.isnan(z):
return z
return z_fallback
margin = float(p.get('margin') or 0.0)
def expand_wgs(ring, m):
"""Grow the plot ring outward by m metres on ALL sides (uniform perpendicular
buffer), so every edge — including the long sides where the outer plant rows
sit — gains m metres of extra ground. Done in a local metric frame, then
converted back to WGS84 degrees.
(The old method pushed each corner radially from the centroid, which for a
long thin plot is just a scale: it added ~m at the short ends but almost
nothing on the long sides, clipping the edge rows. A true buffer fixes that.)"""
if m <= 0:
return ring
cx = sum(q[0] for q in ring) / len(ring)
cy = sum(q[1] for q in ring) / len(ring)
mlon = 111320 * math.cos(math.radians(cy))
mlat = 110540
# ring -> local metres relative to centroid
pts_m = [((lon - cx) * mlon, (lat - cy) * mlat) for lon, lat in ring]
try:
from shapely.geometry import Polygon
poly = Polygon(pts_m)
if not poly.is_valid:
poly = poly.buffer(0)
grown = poly.buffer(m, join_style='mitre', mitre_limit=10.0)
ext = list(grown.exterior.coords)[:-1] # drop closing duplicate
if len(ring) == 4 and len(ext) == 4: # keep A,B,C,D order/count
# re-order buffered corners to match each original corner (nearest)
ext = [min(ext, key=lambda e: (e[0]-px)**2 + (e[1]-py)**2)
for px, py in pts_m]
return [[cx + x / mlon, cy + y / mlat] for x, y in ext]
except Exception:
# fallback: radial push from centroid (legacy behaviour)
out = []
for lon, lat in ring:
dx = (lon - cx) * mlon
dy = (lat - cy) * mlat
d = math.hypot(dx, dy) or 1.0
out.append([lon + dx / d * m / mlon, lat + dy / d * m / mlat])
return out
# pixel source: the image files (JPEG/TIFF renditions, default) or the IIQ raw
# files developed by the Phase One SDK (tab 3b Direct from IIQ, iiq.py)
iiq_mode = (p.get('raw_source') or 'image').lower() == 'iiq'
raw_cfa = iiq_mode and str(p.get('iiq_pixels') or '').lower() in ('cfa', 'raw_sensor')
iiq_dev = None
_exts = RAW_EXTS
if iiq_mode:
import iiq as _iiq
if not p.get('rawdir') or not os.path.isdir(p['rawdir']):
raise RuntimeError("IIQ extraction needs the folder with the .IIQ files.")
_iiq.assert_safe_output([p['rawdir']], p['outdir'])
os.makedirs(p['outdir'], exist_ok=True)
_exts = _iiq.IIQ_EXTS
if raw_cfa:
# the sensor values themselves (LibRaw): nothing developed, nothing lost
iiq_dev = _iiq.RawSensor(log)
with open(os.path.join(p['outdir'], 'IIQ_run.json'), 'w') as _f:
json.dump(dict(iiq_dir=p['rawdir'], pixels='raw_sensor',
settings=iiq_dev.settings, sdk_root=iiq_dev.sdk['root'],
sdk_version=iiq_dev.sdk['version']), _f, indent=1)
log("Pixel source: IIQ RAW SENSOR VALUES (Bayer colour filter mosaic, 16-bit, "
f"not developed; read with {iiq_dev.sdk['version']}). One band per image; "
"the Bayer pattern of each box is in the PE_CFA_PATTERN tag.")
else:
iiq_dev = _iiq.Developer(p.get('iiq_settings'),
os.path.join(p['outdir'], '_iiq_work'),
p.get('iiq_sdk', ''), log, parallel=2)
shutil.copy2(p['iiq_settings'], os.path.join(p['outdir'], 'IIQ_settings_used.json'))
with open(os.path.join(p['outdir'], 'IIQ_run.json'), 'w') as _f:
json.dump(dict(iiq_dir=p['rawdir'], pixels='developed',
settings=p['iiq_settings'], sdk_root=iiq_dev.sdk['root'],
sdk_version=iiq_dev.sdk.get('version', '')), _f, indent=1)
log(_iiq.CREDIT)
log("Pixel source: IIQ raw files developed by the Phase One ImageSDK ("
+ _iiq.sdk_status(p.get('iiq_sdk', ''))[1] + ")")
log(f"Development settings: {os.path.basename(p['iiq_settings'])} "
"(copy: IIQ_settings_used.json)")
# raw image fallback index (basename and stem, lowercase)
raw_index = {}
if p.get('rawdir') and os.path.isdir(p['rawdir']):
n = 0
for root, _dirs, files in os.walk(p['rawdir']):
for fn in files:
if os.path.splitext(fn)[1].lower() in _exts:
full = os.path.join(root, fn)
raw_index.setdefault(fn.lower(), full)
raw_index.setdefault(os.path.splitext(fn)[0].lower(), full)
n += 1
log(f"Raw image folder indexed: {n} image files "
"(preferred over the project's own photo paths)")
def resolve_photo(cam):
# the user-supplied raw folder wins over the project's own photo path,
# so extraction always uses the rendition the user considers original
path = cam.photo.path
base = os.path.basename(path).lower()
stem = os.path.splitext(base)[0]
for key in (base, stem, cam.label.lower()):
if key in raw_index:
return raw_index[key]
for e in _exts:
key = (cam.label + e).lower()
if key in raw_index:
return raw_index[key]