-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathfragment.py
1812 lines (1635 loc) · 68.4 KB
/
fragment.py
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
import json
import time
import math
# from queue import LifoQueue
from collections import deque
import numpy as np
import cv2
import rectpack
from scipy.spatial import Delaunay
from scipy.spatial.qhull import QhullError
from scipy.interpolate import (
LinearNDInterpolator,
NearestNDInterpolator,
CloughTocher2DInterpolator,
RegularGridInterpolator,
)
from scipy.interpolate import CubicSpline
from utils import Utils
from volume import Volume
from base_fragment import BaseFragment, BaseFragmentView
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
class FragmentsModel(QtCore.QAbstractTableModel):
def __init__(self, project_view, main_window):
super(FragmentsModel, self).__init__()
# note that self.project_view should not be
# changed after initialization; instead, a new
# instance of VolumesModel should be created
# and attached to the QTableView
self.project_view = project_view
self.main_window = main_window
columns = [
"Active",
"Visible",
"Hide\nMesh",
"Name",
"Color",
"Dir",
"Pts",
"cm^2"
]
ctips = [
"Select which fragment is active;\nclick box to select.\nNote that you can only select fragments\nwhich have the same direction (orientation)\nas the current volume view",
"Select which fragments are visible;\nclick box to select",
"Select which fragments have their mesh hidden;\nclick box to select",
"Name of the fragment; click to edit",
"Color of the fragment; click to edit",
"Direction (orientation) of the fragment",
"Number of points currently in fragment",
"Fragment area in square centimeters"
]
def flags(self, index):
col = index.column()
oflags = super(FragmentsModel, self).flags(index)
if col == 0:
nflags = Qt.ItemNeverHasChildren
nflags |= Qt.ItemIsUserCheckable
nflags |= Qt.ItemIsEnabled
return nflags
elif col == 1:
# print(col, int(oflags))
nflags = Qt.ItemNeverHasChildren
nflags |= Qt.ItemIsUserCheckable
nflags |= Qt.ItemIsEnabled
# nflags |= Qt.ItemIsEditable
return nflags
elif col == 2:
# print(col, int(oflags))
nflags = Qt.ItemNeverHasChildren
nflags |= Qt.ItemIsUserCheckable
nflags |= Qt.ItemIsEnabled
# nflags |= Qt.ItemIsEditable
return nflags
elif col== 3:
nflags = Qt.ItemNeverHasChildren
nflags |= Qt.ItemIsEnabled
nflags |= Qt.ItemIsEditable
return nflags
else:
return Qt.ItemNeverHasChildren|Qt.ItemIsEnabled
def headerData(self, section, orientation, role):
if orientation != Qt.Horizontal:
return
if role == Qt.DisplayRole:
if section == 0:
# print("HD", self.rowCount())
table = self.main_window.fragments_table
# make sure the color button in column 3 is always open
# (so no double-clicking required)
for i in range(self.rowCount()):
index = self.createIndex(i, 4)
table.openPersistentEditor(index)
return FragmentsModel.columns[section]
elif role == Qt.ToolTipRole:
return FragmentsModel.ctips[section]
def columnCount(self, parent=None):
return len(FragmentsModel.columns)
def rowCount(self, parent=None):
if self.project_view is None:
return 0
fragments = self.project_view.fragments
# print("row count", len(fragments.keys()))
return len(fragments.keys())
# columns: name, color, direction, xmin, xmax, xstep, y..., img...
def data(self, index, role):
if self.project_view is None:
return None
if role == Qt.DisplayRole:
return self.dataDisplayRole(index, role)
elif role == Qt.TextAlignmentRole:
return self.dataAlignmentRole(index, role)
elif role == Qt.BackgroundRole:
return self.dataBackgroundRole(index, role)
elif role == Qt.CheckStateRole:
return self.dataCheckStateRole(index, role)
return None
def dataCheckStateRole(self, index, role):
column = index.column()
row = index.row()
fragments = self.project_view.fragments
fragment = list(fragments.keys())[row]
fragment_view = fragments[fragment]
if column == 0:
if fragment_view.active:
return Qt.Checked
else:
return Qt.Unchecked
if column == 1:
if fragment_view.visible:
return Qt.Checked
else:
return Qt.Unchecked
if column == 2:
# Note that column is "Hide Mesh", but
# internal variable is mesh_visible
if fragment_view.mesh_visible:
return Qt.Unchecked
else:
return Qt.Checked
def dataAlignmentRole(self, index, role):
return Qt.AlignVCenter + Qt.AlignRight
def dataBackgroundRole(self, index, role):
row = index.row()
fragments = self.project_view.fragments
fragment = list(fragments.keys())[row]
fragment_view = fragments[fragment]
if self.project_view.mainActiveVisibleFragmentView() == fragment_view:
# return QtGui.QColor('beige')
return QtGui.QColor(self.main_window.highlightedBackgroundColor())
def dataDisplayRole(self, index, role):
row = index.row()
column = index.column()
fragments = self.project_view.fragments
fragment = list(fragments.keys())[row]
fragment_view = fragments[fragment]
if column == 3:
return fragment.name
elif column == 4:
# print("ddr", row, volume_view.color.name())
return fragment.color.name()
elif column == 5:
# print("data display role", row, volume_view.direction)
return ('X','Y')[fragment.direction]
elif column == 6:
return len(fragment.gpoints)
elif column == 7:
return "%.4f"%fragment_view.sqcm
else:
return None
def setData(self, index, value, role):
row = index.row()
column = index.column()
# print("setdata", row, column, value, role)
if role == Qt.CheckStateRole and column == 0:
# print("check", row, value)
fragments = self.project_view.fragments
fragment = list(fragments.keys())[row]
fragment_view = fragments[fragment]
exclusive = True
# print(self.main_window.app.keyboardModifiers())
if ((self.main_window.app.keyboardModifiers() & Qt.ControlModifier)
or
len(self.main_window.project_view.activeFragmentViews(unaligned_ok=True)) > 1):
exclusive = False
self.main_window.setFragmentActive(fragment, value==Qt.Checked, exclusive)
return True
elif role == Qt.CheckStateRole and column == 1:
# print(row, value)
fragments = self.project_view.fragments
fragment = list(fragments.keys())[row]
fragment_view = fragments[fragment]
self.main_window.setFragmentVisibility(fragment, value==Qt.Checked)
return True
elif role == Qt.CheckStateRole and column == 2:
# print(row, value)
fragments = self.project_view.fragments
fragment = list(fragments.keys())[row]
fragment_view = fragments[fragment]
# Note that column reads "Hide Mesh", but internal variable
# is mesh_visible
self.main_window.setFragmentMeshVisibility(fragment, value==Qt.Unchecked)
return True
elif role == Qt.EditRole and column == 3:
# print("setdata", row, value)
name = value
# print("sd name", value)
fragments = self.project_view.fragments
fragment = list(fragments.keys())[row]
# print("%s to %s"%(fragment.name, name))
if name != "":
self.main_window.renameFragment(fragment, name)
elif role == Qt.EditRole and column == 4:
# print("sd color", value)
fragments = self.project_view.fragments
fragment = list(fragments.keys())[row]
# print("setdata", row, color.name())
self.main_window.setFragmentColor(fragment, value)
return False
def scrollToRow(self, row):
index = self.createIndex(row, 0)
table = self.main_window.fragments_table
table.scrollTo(index)
def scrollToEnd(self):
row = self.rowCount()-1
if row < 0:
return
self.scrollToRow(row)
# note that FragmentView is defined after Fragment
class Fragment(BaseFragment):
# class variable
min_roundness = .1
def __init__(self, name, direction):
super(Fragment, self).__init__(name)
self.direction = direction
self.params = {}
# fragment points in global coordinates
self.gpoints = np.zeros((0,3), dtype=np.float32)
# History of gpoints, for undo functionality
# self.gpoints_history : LifoQueue = LifoQueue(100)
self.gpoints_history = deque(maxlen=50)
def createView(self, project_view):
return FragmentView(project_view, self)
def createCopy(self, name):
frag = Fragment(name, self.direction)
frag.setColor(self.color, no_notify=True)
frag.gpoints = np.copy(self.gpoints)
frag.valid = True
return frag
def toDict(self):
info = {}
info['name'] = self.name
info['created'] = self.created
info['modified'] = self.modified
info['direction'] = self.direction
info['color'] = self.color.name()
info['params'] = self.params
info['gpoints'] = self.gpoints.tolist()
if self.params.get('echo', '') != '':
info['gpoints'] = []
return info
def save(self, path):
info = self.toDict()
# print(info)
info_txt = json.dumps(info, indent=4)
file = path / (self.name + ".json")
print("writing to",file)
file.write_text(info_txt, encoding="utf8")
# class function
def saveList(frags, path, stem):
infos = []
for frag in frags:
if not hasattr(frag, "toDict"):
continue
info = frag.toDict()
infos.append(info)
info_txt = json.dumps(infos, indent=4)
file = path / (stem + ".json")
print("writing to",file)
file.write_text(info_txt, encoding="utf8")
def createErrorFragment(err):
frag = Fragment("", -1)
frag.error = err
return frag
# class function
def fragFromDict(info):
for attr in ['name', 'direction', 'gpoints']:
if attr not in info:
err = "file missing parameter %s"%(attr)
print(err)
return Fragment.createErrorFragment(err)
if 'color' in info:
color = QColor(info['color'])
else:
color = Utils.getNextColor()
name = info['name']
direction = info['direction']
gpoints = info['gpoints']
frag = Fragment(name, direction)
frag.setColor(color, no_notify=True)
frag.valid = True
# if len(name) > 0 and name[-1] == "∴":
# frag.no_mesh = True
if len(gpoints) > 0:
# frag.gpoints = np.array(gpoints, dtype=np.int32)
frag.gpoints = np.array(gpoints, dtype=np.float32)
if 'params' in info:
frag.params = info['params']
else:
frag.params = {}
if 'created' in info:
frag.created = info['created']
else:
# old file without "created" timestamp
# sleeping to make sure timestamp is unique
time.sleep(.1)
frag.created = Utils.timestamp()
if 'modified' in info:
frag.modified = info['modified']
else:
frag.modified = frag.created
return frag
# TODO: need "created" and "modified" timestamps
# class function
def load(json_file):
try:
json_txt = json_file.read_text(encoding="utf8")
except:
err = "Could not read file %s"%json_file
print(err)
return [Fragment.createErrorFragment(err)]
try:
infos = json.loads(json_txt)
except:
err = "Could not parse file %s"%json_file
print(err)
return [Fragment.createErrorFragment(err)]
if not isinstance(infos, list):
infos = [infos]
frags = []
for info in infos:
frag = Fragment.fragFromDict(info)
if not frag.valid:
return [frag]
frags.append(frag)
return frags
# class function
# performs an in-place sort of the list
def sortFragmentList(frags):
frags.sort(key=lambda f: f.name)
def minRoundness(self):
return Fragment.min_roundness
def badTrglsBySkinniness(self, tri, min_roundness):
simps = tri.simplices
# 2D coordinates
verts = tri.points
v0 = verts[simps[:,0]]
v1 = verts[simps[:,1]]
v2 = verts[simps[:,2]]
v01 = v1-v0
v02 = v2-v0
v12 = v2-v1
area = abs(.5*(v01[:,0]*v02[:,1] - v01[:,1]*v02[:,0]))
l01 = np.sqrt((v01*v01).sum(1))
l02 = np.sqrt((v02*v02).sum(1))
l12 = np.sqrt((v12*v12).sum(1))
circumference = l01+l02+l12
pmax = math.sqrt(.25*math.sqrt(3.))/3
roundness = np.sqrt(area)/(circumference*pmax)
bads = np.where(roundness < self.minRoundness())[0]
return bads
def badTrglsByMaxAngle(self, tri):
simps = tri.simplices
verts = tri.points
v0 = verts[simps[:,0]]
v1 = verts[simps[:,1]]
v2 = verts[simps[:,2]]
v01 = v1-v0
v02 = v2-v0
v12 = v2-v1
l01 = np.sqrt((v01*v01).sum(1))
l02 = np.sqrt((v02*v02).sum(1))
l12 = np.sqrt((v12*v12).sum(1))
d12 = (v01*v02).sum(1)/(l01*l02)
d01 = (v02*v12).sum(1)/(l02*l12)
d02 = -(v01*v12).sum(1)/(l01*l12)
ds = np.array((d01,d02,d12)).transpose()
# print("ds shape", ds.shape)
dmax = np.amax(ds, axis=1)
dmin = np.amin(ds, axis=1)
# print("dmax shape", dmax.shape)
mind = -.95
mind = -.99
bads = np.where(dmin < mind)[0]
return bads
def badTrglsByNormal(self, tri, pts):
simps = tri.simplices
v0 = pts[simps[:,0]]
v1 = pts[simps[:,1]]
v2 = pts[simps[:,2]]
v01 = v1-v0
v02 = v2-v0
l01 = np.sqrt((v01*v01).sum(1))
l02 = np.sqrt((v02*v02).sum(1))
norm = np.cross(v01, v02)/(l01*l02).reshape(-1,1)
# print("norm",v01.shape, v02.shape, norm.shape)
# print(norm[0:10])
bads = np.where(np.abs(norm[:,2]) < .1)
# bads = np.where(np.abs(norm[:,2]) < 0)
return bads
# given array of indices of "bad" trgls, return a subset of the list,
# consisting of bad trgls that are (recursively) on the border
def badBorderTrgls(self, tri, bads):
# print("bads", bads)
badbool = np.zeros((len(tri.simplices),), dtype=np.bool8)
badbool[bads] = True
borderlist = np.array((-1,), dtype=np.int32)
lbl = len(borderlist)
while True:
borderbool = np.isin(tri.neighbors, borderlist).any(axis=1)
badbordertrgls = np.where(np.logical_and(borderbool, badbool))[0]
# print("bad on border", len(badbordertrgls))
borderlist = np.unique(np.append(borderlist, badbordertrgls))
newlbl = len(borderlist)
if newlbl == lbl:
break
lbl = newlbl
return badbordertrgls
# Using self.gpoints, create new points in the
# global coordinate system to infill the grid at the given
# spacing. Infill points will be omitted wherever there
# is an existing grid point nearby. Returns the new gpoints.
def createInfillPoints(self, infill):
direction = self.direction
gijks = self.gpoints
# ngijks = np.zeros((0,3), dtype=np.int32)
ngijks = np.zeros((0,3), dtype=np.float32)
if infill <= 0:
return ngijks
tgijks = Volume.globalIjksToTransposedGlobalIjks(gijks, direction)
print("tgijks", tgijks.shape, tgijks.dtype)
if tgijks.shape == 0:
return ngijks
mini = np.amin(tgijks[:,0])
maxi = np.amax(tgijks[:,0])
minj = np.amin(tgijks[:,1])
maxj = np.amax(tgijks[:,1])
print("minmax", mini, maxi, minj, maxj)
minid = mini/infill
maxid = maxi/infill
minjd = minj/infill
maxjd = maxj/infill
id0 = math.floor(minid)
idm = math.floor(maxid)
if idm != maxid:
idm += 1
idn = idm-id0+1
jd0 = math.floor(minjd)
jdm = math.floor(maxjd)
if jdm != maxjd:
jdm += 1
jdn = jdm-jd0+1
print("id,jd", id0, idn, jd0, jdn)
# create an array to hold the coordinates of the infill points
sid = np.indices((jdn, idn))
print("sid", idn, jdn, sid.shape, sid.dtype)
# add a flag layer to indicate whether an existing gpoint
# is close to one of the proposed infill points
si = np.append(sid, np.zeros((1, jdn, idn), dtype=sid.dtype), axis=0)
# set the coordinates (in the transposed global frame) of
# the infill points
# notice si[0] corresponds to j and si[0] to i
si[1] = np.rint((si[1]+id0)*infill+infill/2).astype(si.dtype)
si[0] = np.rint((si[0]+jd0)*infill+infill/2).astype(si.dtype)
# calculate the position, in the si array, of the
# existing transposed gpoints
itgijks0 = np.int32(np.floor(tgijks[:,0]/infill - id0))
itgijks1 = np.int32(np.floor(tgijks[:,1]/infill - jd0))
# set the flag wherever there is an existing point
si[2,itgijks1,itgijks0] = 1
# print("si corners", si[:,0,0], si[:,-1,-1])
# sum should equal the number of gpoints (but may be
# smaller if more than one gpoint near a single infill point)
# print("sum", np.sum(si[2]))
# sib is a boolean of all the infill points that are not near an
# existing gpoint
sib = si[2,:,:] == 0
# print("si sib",si.shape, sib.shape)
# filter si by sib
si = si[:2, sib]
# print("si",si.shape)
# don't need the infill point in an array any more; flatten them
# notice si[0] corresponds to j and si[0] to i
newtis = si[1].flatten()
newtjs = si[0].flatten()
newtijs = np.array((newtis, newtjs)).transpose()
# print("newtijs", newtijs.shape)
try:
# triangulate the original gpoints
tri = Delaunay(tgijks[:,0:2])
except Exception as err:
err = str(err).splitlines()[0]
print("createInfillPoints triangulation error: %s"%err)
return ngijks
# bads = self.badBorderTrgls(tri, self.badTrglsByNormal(tri, tgijks))
bads = self.badBorderTrgls(tri, self.badTrglsBySkinniness(tri, self.minRoundness()))
badlist = bads.tolist()
interp = CloughTocher2DInterpolator(tri, tgijks[:,2])
newtks = interp(newtijs)
simpids = tri.find_simplex(newtijs)
newtks = np.reshape(newtks, (newtks.shape[0],1))
# print("newtks", newtks.shape)
# the list of infill points, in transposed global
# ijk coordinates
newtijks = np.append(newtijs, newtks, axis=1)
print("newtijks with nans", newtijks.shape)
# eliminate infill points in "bad" simplices
newtijks = newtijks[~np.isin(simpids, badlist)]
print("newtijks no bad trgls", newtijks.shape)
# eliminate infill points where k is nan
newtijks = newtijks[~np.isnan(newtijks[:,2])]
print("newtijks no nans", newtijks.shape)
ngijks = Volume.transposedGlobalIjksToGlobalIjks(newtijks, direction)
# TODO: shouldn't be hardwired here!
voxelSizeUm = self.project.voxel_size_um
meshCount = len(newtijks)
area_sq_mm_flat = meshCount*voxelSizeUm*voxelSizeUm*infill*infill/1000000
simps = tri.simplices
pts = tgijks
simps = simps[~(np.isin(simps, bads).any(1))]
v0 = pts[simps[:,0]].astype(np.float64)
v1 = pts[simps[:,1]].astype(np.float64)
v2 = pts[simps[:,2]].astype(np.float64)
v01 = v1-v0
v02 = v2-v0
norm = np.cross(v01, v02)
# print(norm.shape)
# print((norm*norm).shape)
normsq = np.sum(norm*norm, axis=1)
# print(norm.shape, normsq.shape)
# normsq = normsq[~np.isnan(normsq)]
# print(normsq[normsq < 0])
# print(normsq.shape)
area_sq_mm_trg = np.sum(np.sqrt(normsq))*voxelSizeUm*voxelSizeUm/(2*1000000)
print("areas", area_sq_mm_flat, area_sq_mm_trg)
return ngijks
class ExportFrag:
def __init__(self, fv, infill):
frag = fv.fragment
gpoints = frag.gpoints
fname = frag.name
self.err = ""
self.fv = fv
self.frag = frag
self.trgs = []
self.has_ssurf = False
if not fv.mesh_visible:
self.vrts = gpoints
return
print(fname,"gpoints before", len(gpoints))
newgps = frag.createInfillPoints(infill)
gpoints = np.append(gpoints, newgps, axis=0)
print(fname,"gpoints after", len(gpoints))
self.vrts = gpoints
tgps = Volume.globalIjksToTransposedGlobalIjks(gpoints, frag.direction)
try:
# triangulate the new gpoints
tri = Delaunay(tgps[:,0:2])
# except QhullError as err:
except Exception as err:
self.err = "%s triangulation error: %s"%(fname,err)
self.err = self.err.splitlines()[0]
print(self.err)
return
# bads = frag.badBorderTrgls(tri, frag.badTrglsByNormal(tri, tgps))
bads = frag.badBorderTrgls(tri, frag.badTrglsBySkinniness(tri, frag.minRoundness()))
badlist = bads.tolist()
for i,trg in enumerate(tri.simplices):
if i in badlist:
continue
self.trgs.append(trg)
print("all",len(tri.simplices),"good",len(self.trgs))
fv.createZsurf()
if fv.zsurf is not None and fv.ssurf is not None:
self.has_ssurf = True
self.data_rect = Fragment.ExportFrag.dataBounds(fv.zsurf)
self.shape = fv.zsurf.shape
# class function
# returns (x,y,w,h) of bounding box that contains
# all the data (data that is not NaN).
# w,h = 0 if nothing found.
# Note that if non-NaN data is found, w and h will be at least 1.
def dataBounds(arr):
# True if not nan
b = ~np.isnan(arr)
# True if row or col has at least one not-nan
b0 = np.any(b, axis=0)
b1 = np.any(b, axis=1)
b0t = b0.nonzero()[0]
b1t = b1.nonzero()[0]
if len(b0t) == 0:
b0min = -1
b0max = 0
else:
b0min = min(b0t)
b0max = max(b0t)
if len(b1t) == 0:
b1min = -1
b1max = 0
else:
b1min = min(b1t)
b1max = max(b1t)
x = b0min
w = b0max-b0min+1
y = b1min
h = b1max-b1min+1
# print(b.shape, b0.shape, len(b0t), len(b0min))
# print(frag.name, b0min, b0max, b1min, b1max)
return x,y,w,h
def addTexture(self, arr):
if not self.has_ssurf:
return
xt,yt = self.tex_orig
x0,y0 = self.data_rect[:2]
w,h = self.data_rect[2:]
x1 = x0+w
y1 = y0+h
arr[yt:yt+h,xt:xt+w] = self.fv.ssurf[y0:y1,x0:x1]
# class function
def pack(efs):
packer = rectpack.newPacker(
rotation=False, pack_algo=rectpack.MaxRectsBlsf)
pad = 1
incount = 0
for ef in efs:
if not ef.has_ssurf:
continue
dr = ef.data_rect
packer.add_rect(dr[2]+2*pad, dr[3]+2*pad)
incount += 1
ibin = (20000, 20000)
packer.add_bin(*ibin)
packer.pack()
if len(packer.rect_list()) == 0:
obin = []
else:
obin = packer[0]
'''
if incount != len(obin):
err = "Have %d valid efs but only %d rects in obin"%(incount,len(obin))
print(err)
return
'''
maxx = 0
maxy = 0
used = set()
for rect in obin:
(x, y, w, h) = rect.x, rect.y, rect.width, rect.height
found = False
for ef in efs:
if not ef.has_ssurf:
continue
if ef in used:
continue
dr = ef.data_rect
if w != dr[2]+2*pad or h != dr[3]+2*pad:
continue
ef.tex_orig = (x+pad,y+pad)
used.add(ef)
found = True
if not found:
self.err = "Could not find rect %d %d %d %d in efs"%(x,y,w,d)
print(err)
return
mx = x+w
maxx = max(maxx, mx)
my = y+h
maxy = max(maxy, my)
return (maxx, maxy)
def meshExportNeedsInfill(self):
return True
# class function
# takes a list of FragmentView's as input
# texture is taken from current volume, which may not
# be full resolution
def saveListAsObjMesh(fvs, filename, infill, ppm, class_count):
frags = [fv.fragment for fv in fvs]
print("slaom", len(frags), filename, infill)
filename = filename.with_suffix(".obj")
err = ""
rects = []
'''
# diagnostics only
for fv in fvs:
frag = fv.fragment
if fv.zsurf is None or fv.ssurf is None:
print("Zsurf or ssurf missing for", frag.name)
continue
x,y,w,h = Fragment.ExportFrag.dataBounds(fv.zsurf)
print(frag.name, x, y, w, h)
'''
efs = []
for fv in fvs:
ef = Fragment.ExportFrag(fv, infill)
if ef.err != "":
print("Fragment",ef.frag.name,"error",ef.err)
# err += ef.err + '\n'
# continue
efs.append(ef)
if len(efs) == 0:
err = "No exportable fragments"
print(err)
return err
try:
of = filename.open("w")
except Exception as e:
err = "Could not open %s: %s"%(str(filename), e)
print(err)
return err
mfilename = filename.with_suffix(".mtl")
print("# khartes .obj file", file=of)
print("#", file=of)
print("mtllib %s"%mfilename.name, file=of)
print("# vertices", file=of)
for ef in efs:
fv = ef.fv
mesh_visible = fv.mesh_visible
rgb = ef.frag.color.getRgbF()
r = rgb[0]
g = rgb[1]
b = rgb[2]
vrts = ef.vrts
if ppm is not None:
vrts = ppm.layerIjksToScrollIjks(vrts)
print("# fragment", ef.frag.name, file=of)
for vrt in vrts:
if mesh_visible:
print("v %.2f %.2f %.2f "%(vrt[0],vrt[1],vrt[2]), file=of)
else:
print("v %.2f %.2f %.2f %.4f %.4f %.4f"%(vrt[0],vrt[1],vrt[2], r, g, b), file=of)
tex_rect = Fragment.ExportFrag.pack(efs)
if tex_rect is None:
err = "Could not pack textures (see console message)"
print(err)
return err
for ef in efs:
if not ef.has_ssurf:
continue
print(" ", ef.frag.name, ef.data_rect, ef.tex_orig)
print("texture size", tex_rect)
tw,th = tex_rect
tfilename = ""
if tw > 0 and th > 0:
tex_out = np.zeros((th,tw), dtype=np.uint16)
for ef in efs:
ef.addTexture(tex_out)
tfilename = filename.with_suffix(".tif")
cv2.imwrite(str(tfilename), tex_out)
print("# texture vertices", file=of)
for ef in efs:
print("# fragment", ef.frag.name, file=of)
if not ef.has_ssurf:
for i in range(len(ef.vrts)):
print("vt %f %f"%(0.,0.), file=of)
continue
x0, y0 = ef.tex_orig
dx, dy, dw, dh = ef.data_rect
# for vrt in ef.vrts:
frag = ef.frag
fv = ef.fv
# tgps = Volume.globalIjksToTransposedGlobalIjks(ef.vrts, frag.direction)
tgps = fv.cur_volume_view.volume.globalPositionsToTransposedIjks(ef.vrts, frag.direction)
for fpt in tgps:
# print("v %d %d %d"%(vrt[0],vrt[1],vrt[2]), file=of)
vx, vy = fpt[0:2]
tx = (vx+x0-dx)/(tw-1)
ty = (vy+y0-dy)/(th-1)
ty = 1.-ty
print("vt %f %f"%(tx, ty), file=of)
print("# trgls", file=of)
i0 = 1
for i,ef in enumerate(efs):
print("# fragment", ef.frag.name, file=of)
print("usemtl frag%d"%i, file=of)
for trg in ef.trgs:
v0 = trg[0]+i0
v1 = trg[1]+i0
v2 = trg[2]+i0
print("f %d/%d %d/%d %d/%d"%(v0,v0,v1,v1,v2,v2), file=of)
i0 += len(ef.vrts)
try:
ofm = mfilename.open("w")
except Exception as e:
err = "Could not open %s: %s"%(str(mfilename), e)
print(err)
return err
for i,ef in enumerate(efs):
frag = ef.frag
rgba = frag.color.getRgbF()
print("newmtl frag%d"%i, file=ofm)
print("Ka %f %f %f"%(rgba[0],rgba[1],rgba[2]), file=ofm)
print("Kd %f %f %f"%(rgba[0],rgba[1],rgba[2]), file=ofm)
print("Ks 0.0 0.0 0.0", file=ofm)
print("illum 2", file=ofm)
print("d 1.0", file=ofm)
if tfilename != "":
print("map_Kd %s"%tfilename.name, file=ofm)
jfilename = filename.with_suffix(".json")
jdict = {}
for ef in efs:
frag = ef.frag
fv = ef.fv
fdict = {}
fdict["name"] = frag.name
fdict["area_sq_cm"] = fv.sqcm
fdict["n_vrts"] = len(ef.vrts)
fdict["n_trgls"] = len(ef.trgs)
jdict[frag.name] = fdict
info_txt = json.dumps(jdict, indent=4)
try:
ofj = jfilename.open("w")
print(info_txt, file=ofj)
except Exception as e:
err = "Could not open %s: %s"%(str(jfilename), e)
print(err)
# return err
return err
class FragmentView(BaseFragmentView):
# class variables
# general rule on class variables: they should only be
# used if the only way to change them is through the dev-tools UI
use_linear_interpolation = True
hide_skinny_triangles = False
def __init__(self, project_view, fragment):
super(FragmentView, self).__init__(project_view, fragment)
self.tri = None
self.line = None
self.lineAxis = -1
self.lineAxisPosition = 0
self.zsurf = None
self.prevZslice = -1
self.prevZslicePts = None
self.ssurf = None
self.nearbyNode = -1
self.live_zsurf_update = True
# gpoints converted to ijk coordinates relative
# to current volume, using trijk based on
# fragment's direction
self.fpoints = np.zeros((0,4), dtype=np.float32)
self.oldzs = None
self.oldtri = None
# same as above, but trijk based on cur_volume_view's
# direction
self.vpoints = np.zeros((0,4), dtype=np.float32)
def calculateSqCm(self):
# project_view is None if self.fragment is a working fragment
# of a TrglFragment
if self.tri is None or self.project_view is None:
self.sqcm = 0.
return 0.
pts = self.fragment.gpoints
simps = self.tri.simplices
voxel_size_um = self.project_view.project.voxel_size_um
sqcm = BaseFragment.calculateSqCm(pts, simps, voxel_size_um)
self.sqcm = sqcm
def clearCaches(self):
self.oldzs = None
self.oldtri = None
self.clearZsliceCache()
def clearZsliceCache(self):
self.prevZslice = -1
self.prevZslicePts = None
def aligned(self):
if self.cur_volume_view is None:
return False
if self.cur_volume_view.direction != self.fragment.direction:
return False
return True
# recursion_ok determines whether to call setLocalPoints in
# "echo" fragments. But this is safe to call only if all
# fragment views have had their current volume view set.
def setLocalPoints(self, recursion_ok, always_update_zsurf=True):
# print("set local points", self.cur_volume_view.volume.name)
# print("set local points", self.fragment.name)
if self.cur_volume_view is None:
self.fpoints = np.zeros((0,4), dtype=np.float32)
self.vpoints = np.zeros((0,4), dtype=np.float32)
return
self.fpoints = self.cur_volume_view.volume.globalPositionsToTransposedIjks(self.fragment.gpoints, self.fragment.direction)
npts = self.fpoints.shape[0]
if npts > 0:
indices = np.reshape(np.arange(npts), (npts,1))
self.fpoints = np.concatenate((self.fpoints, indices), axis=1)
self.vpoints = self.cur_volume_view.volume.globalPositionsToTransposedIjks(self.fragment.gpoints, self.cur_volume_view.direction)