-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
1413 lines (1086 loc) · 53.6 KB
/
main.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 sys
import os
import glob
from PyQt5.QtWidgets import QApplication, QWidget,QMainWindow,QFileDialog,QMessageBox,QSlider,QLineEdit,QCheckBox,QListWidget,QListWidgetItem,QAbstractItemView, QInputDialog, QTabWidget, QStyledItemDelegate, QPushButton, QRadioButton,QProgressBar
from PyQt5.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton
from PyQt5.QtGui import QColor, QIcon, QPen
from PyQt5.QtWidgets import QStyle
from PyQt5.uic import loadUiType
from PyQt5.QtGui import QIntValidator
from PyQt5.QtCore import Qt
from scenemanager import SceneManager
import numpy as np
import scipy
import matplotlib.pyplot as plt
import zarr
from tqdm import tqdm
from modules.optical_flow_module import OpticFlowClass
from modules.structure_tensor_module import StructureTensorClass
from visualization.dialog_box_module import MetadataDialogBox, ValidationMetadataDialogBox
from tools.validate_tractograms import validate
from modules.act_module import ACTClass
from visualization.flythrough_module import MovieClass
import pickle
from dipy.segment.clustering import QuickBundles
import distinctipy
from PIL import Image
from tools.compare_tractograms import compare_tractogram_clusters
import ctypes
# Load GUI
Ui_MainWindow = loadUiType("mainwindow.ui")[0]
# Needed for drawing a border around selected items in a list of colors
class ColorDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
painter.save()
# Call the base paint method to draw the default item background and foreground
super().paint(painter, option, index)
# If the item is selected, draw a red border around it
if option.state & QStyle.State_Selected:
color_rect = option.rect.adjusted(1, 1, -1, -1)
painter.setPen(QPen(QColor(255, 0, 0), 3))
painter.drawRect(color_rect)
painter.restore()
# MainWindow class inheriting QMainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.initVTK()
# Initialize variables
self.imagesPath = None
self.maskImageForSeedsFilePath = None
self.fascicleSegmentationsPath = None
self.metadata = dict()
self.affine = None
self.streamlines = None
self.color = None
self.maskImage = None
self.trackingAlgoLK = 0
self.trackingAlgoST = 0
self.streamlineClusters = None
self.streamlineClustersColors = None
self.userSelectedColor = None
self.startSliceIndex = None
# Set current tab
self.tabWidget.setCurrentWidget(self.visualizationTab)
self.ieTabSelected = 0
# Disable interactive editing tab until streamlines are created/loaded or image, mask and metadata are loaded
self.tabWidget.setTabEnabled(1, False)
# Threads for optic flow analysis and structure tensor analysis
self.opticFlowThread = None
self.structureTensorThread = None
# Flags to describe whether image stack and metadata are successfully loaded
self.imageStackAvailable = False
self.metadataAvailable = False
# Validate inputs
winSizeValidator = QIntValidator(3, 1000, self.windowSizeEdit)
self.windowSizeEdit.setValidator(winSizeValidator)
# We need to call QVTKWidget's show function before initializing the interactor
def initVTK(self):
self.show()
self.SceneManager = SceneManager(self.vtkContext)
# Save the folder path to the images
def OpenFolderImages(self):
title = "Open Folder with PNG images"
flags = QFileDialog.ShowDirsOnly
self.imagesPath = QFileDialog.getExistingDirectory(self,
title,
os.path.expanduser("."),
flags)
if self.imagesPath == '':
self.imagesPath = None
return
self.imageStackAvailable = True
self.statusBar().showMessage('Image folder location saved', 2000)
# Open and load the mask image to memory
def OpenMaskImageForSeeds(self):
title = "Open Mask Image with Regions For Seeds (corresponds to an arbitrary slice in image stack)"
self.maskImageForSeedsFilePath = QFileDialog.getOpenFileName(self,
title,
os.path.expanduser("."),
"Mask File (*.png *.PNG)")
if self.maskImageForSeedsFilePath[0] == '':
self.maskImageForSeedsFilePath = None
return
self.LoadMaskImage()
self.statusBar().showMessage('Mask image location saved', 2000)
# Read metadata from a dialog box or pre-defined XML file
def OpenImageMetadataXML(self):
dialog = MetadataDialogBox()
if dialog.exec_() == QDialog.Accepted:
self.metadata = dialog.get_metadata()
self.readMetadata()
# Read metadata and create image data and bounding box actors
def readMetadata(self):
if self.imagesPath is None:
msgBox = QMessageBox()
msgBox.setText("Folder path for images is not set, please set it first.")
msgBox.exec()
return None
# Read the first image in the directory and infer the image shape
if self.metadata['image_type'] == '.png':
filelist = glob.glob(self.imagesPath + '\\*' + self.metadata['image_type'])
pil_image = Image.open(filelist[0])
image = np.asarray(pil_image)
else:
dataset = zarr.open(self.imagesPath)
muse_dataset = dataset['muse']
image = np.squeeze(np.array(muse_dataset[0, 0, :, :]))
self.metadata['x_size_pixels'] = image.shape[1]
self.metadata['y_size_pixels'] = image.shape[0]
self.statusBar().showMessage('Reading metadata, creating XY image plane object for display..')
self.progressBar.setMinimum(0)
self.progressBar.setMaximum(self.metadata['num_images_to_read'])
self.progressBar2.setMinimum(0)
self.progressBar2.setMaximum(self.metadata['num_images_to_read'])
self.affine = np.eye(4)
self.affine[0, 0] = self.metadata['pixel_size_xy']
self.affine[1, 1] = self.metadata['pixel_size_xy']
self.affine[2, 2] = self.metadata['image_slice_thickness']
# Update slice view sliders and streamline clip slider
self.xySlider.setMaximum(self.metadata['num_images_to_read'] - 1)
self.xySlider2.setMaximum(self.metadata['num_images_to_read'] - 1)
self.clipStreamlinesSlider.setMinimum(1)
self.clipStreamlinesSlider.setMaximum(100)
# Remove existing actors
self.SceneManager.removeXYSliceActor()
self.SceneManager.removeBBActor()
# Add new actors for XY slice and BB
self.SceneManager.createXYSliceActor(self.imagesPath, self.metadata['pixel_size_xy'],
self.metadata['image_slice_thickness'], self.metadata['x_size_pixels'],
self.metadata['y_size_pixels'], self.metadata['num_images_to_read'], self.metadata['image_type'])
self.SceneManager.createBBActor()
validator = QIntValidator(0, self.metadata['num_images_to_read'] - 1, self.tracksStartingSliceIndex)
self.tracksStartingSliceIndex.setValidator(validator)
self.downsampleFactor = str(int(round(self.metadata['image_slice_thickness'] / self.metadata['pixel_size_xy'])))
self.metadataAvailable = True
if self.imageStackAvailable and self.metadataAvailable:
self.tabWidget.setTabEnabled(1, True)
self.statusBar().showMessage('Metadata reading complete', 2000)
# Save path to the fascicle segmentation masks
def OpenFascicleSegmentationsFolder(self):
title = "Open Folder with Fascicle Segmentation Images"
flags = QFileDialog.ShowDirsOnly
self.fascicleSegmentationsPath = QFileDialog.getExistingDirectory(self,
title,
os.path.expanduser("."),
flags)
if self.fascicleSegmentationsPath == '':
self.fascicleSegmentationsPath = None
return
self.statusBar().showMessage('Fascicle segmentation folder location saved', 2000)
# Load the select mask image into memory
def LoadMaskImage(self):
if self.maskImageForSeedsFilePath is None:
msgBox = QMessageBox()
msgBox.setText("Mask Image path is not set, please set it first.")
msgBox.exec()
return None
if self.metadata is None:
msgBox = QMessageBox()
msgBox.setText("Image metadata should be provided in a .xml file, please load it first.")
msgBox.exec()
return None
self.maskImage = (plt.imread(self.maskImageForSeedsFilePath[0])* 255).astype('uint8')
self.maskImage = self.maskImage.astype('uint8')
self.maskImage[self.maskImage > 0] = 255
self.statusBar().showMessage('Finished reading mask image for seeds into memory.', 2000)
# Save streamlines and colors to the disk (pickle file)
def exportStreamlinesAndColors(self):
text, ok = QInputDialog.getText(self, 'Export streamlines and colors', 'Provide sample name')
if ok:
try:
sample_name = str(text)
except:
msgBox = QMessageBox()
msgBox.setText("Could not convert value entered into string, please try again.")
msgBox.exec()
return None
# Sync variables first, then write
self.SceneManager.updateStreamlinesAndColors(self.streamlines, self.color)
if self.trackingAlgoLK:
self.SceneManager.exportStreamlinesAndColorsLK(self.windowSizeEdit.text(), self.maxLevelEdit.text(), self.seedsPerPixelEdit.text(), self.blurEdit.text(), sample_name)
if self.trackingAlgoST:
self.SceneManager.exportStreamlinesAndColorsST(self.neighborhoodScaleEdit.text(), self.noiseScaleEdit.text(), self.seedsPerPixelEdit.text(), self.downsampleFactor, sample_name)
self.statusBar().showMessage('Saved streamlines and colors data into pickle files folder.', 2000)
# Save streamline cluster to the disk (pickle file)
def exportStreamlinesClusters(self):
text, ok = QInputDialog.getText(self, 'Export streamlines clusters', 'Provide sample name')
if ok:
try:
sample_name = str(text)
except:
msgBox = QMessageBox()
msgBox.setText("Could not convert value entered into string, please try again.")
msgBox.exec()
return None
# Sync variables first, then write
self.SceneManager.updateClusters(self.streamlineClusters, self.streamlineClustersColors)
if self.trackingAlgoLK:
self.SceneManager.exportStreamlinesClustersLK(self.windowSizeEdit.text(), self.maxLevelEdit.text(), self.seedsPerPixelEdit.text(), self.blurEdit.text(), self.clusteringThresholdEdit.text(), sample_name)
if self.trackingAlgoST:
self.SceneManager.exportStreamlinesClustersST(self.neighborhoodScaleEdit.text(), self.noiseScaleEdit.text(), self.seedsPerPixelEdit.text(), self.downsampleFactor, self.clusteringThresholdEdit.text(), sample_name)
self.statusBar().showMessage('Saved streamline clusters into pickle files folder.', 2000)
# Load streamlines from pickle file
def loadStreamlines(self):
title = "Open Streamlines Pickle file, needs colors pickle file in the same folder."
self.streamlinesPickleFile = QFileDialog.getOpenFileName(self,
title,
os.path.expanduser("."),
"Pickle Files (*.pkl)")
if self.streamlinesPickleFile[0] == '':
self.streamlinesPickleFile = None
return
# Find the colors pickle file in the same folder
colorsFileName = 'colors_' + os.path.basename(self.streamlinesPickleFile[0])[12:]
self.colorsPickleFile = os.path.dirname(self.streamlinesPickleFile[0]) + '\\' + colorsFileName
if not os.path.exists(self.colorsPickleFile):
msgBox = QMessageBox()
msgBox.setText("Did not find the colors pickle file in the same folder, please verify and try again.")
msgBox.exec()
return None
# Read the streamline pickle file and sync variables here and in SceneManager
with open(self.streamlinesPickleFile[0], 'rb') as f:
self.streamlines = pickle.load(f)
# Read the colors pickle file and sync variables here and in SceneManager
with open(self.colorsPickleFile, 'rb') as f:
self.color = pickle.load(f)
self.SceneManager.removeStreamlinesActor()
self.SceneManager.updateStreamlinesAndColors(self.streamlines, self.color)
self.SceneManager.createStreamlinesActor()
self.SceneManager.visualizeStreamlines(self.streamlinesVisibilityCheckbox.isChecked())
self.statusBar().showMessage('Loading streamlines complete', 2000)
# Clear and update the colors list widget
self.selectTracksListWidget.clear()
self.unique_colors = np.unique(self.color, axis = 0)
for i in np.arange(self.unique_colors.shape[0]):
listItem = QListWidgetItem('')
listItem.setBackground(QColor(int(self.unique_colors[i][0] * 255), int(self.unique_colors[i][1] * 255),
int(self.unique_colors[i][2] * 255), 200))
self.selectTracksListWidget.addItem(listItem)
self.selectTracksListWidget.setItemDelegate(ColorDelegate(self.selectTracksListWidget))
self.selectTracksListWidget.setSelectionMode(QAbstractItemView.MultiSelection)
self.statusBar().showMessage('Loading colors complete, can display streamlines', 2000)
# Enable the interactive editing tab and update visualization
if self.color is not None and self.streamlines is not None:
self.tabWidget.setTabEnabled(1, True)
self.uncheckStreamlinesUIElements()
# Set flags to identify which tracking algorithm was used
if '_st_' in self.streamlinesPickleFile[0]:
self.trackingAlgoST = 1
self.trackingAlgoLK = 0
else:
self.trackingAlgoLK = 1
self.trackingAlgoST = 0
# Uncheck streamline specific UI elements to start afresh
def uncheckStreamlinesUIElements(self):
self.clipStreamlinesCheckbox.setChecked(False)
self.selectTracksByColorCheckbox.setChecked(False)
self.clusterCheckbox.setChecked(False)
# Visualize bounding box, checkbox signal from UI
def visualizeBoundingBox(self, value):
self.SceneManager.visualizeBoundingBox(value)
# Connect the forward/backward radio button group's buttonReleased() signal to this function
# Checks if at least one box is checked
def trackingDirection(self):
if not self.forwardTrackingButton.isChecked() and not self.backwardTrackingButton.isChecked():
self.sender().setChecked(True)
if not self.forwardTrackingButton2.isChecked() and not self.backwardTrackingButton2.isChecked():
self.sender().setChecked(True)
# Cluster the streamlines and render them in the window
def clusterStreamlines(self, isChecked):
if isChecked:
if self.streamlines is None:
msgBox = QMessageBox()
msgBox.setText("Need streamlines to be computed/loaded prior to clusering.")
msgBox.exec()
return None
self.statusBar().showMessage('Running quick bundles clustering..')
# Do not consider streamlines that do not cover full length of the stack, else short streamlines will get their own clusters
# Computational modeling considers streamlines over the full length of the stack
streamline_lengths = [streamline.shape[0] for streamline in self.streamlines]
# Length of the full stack is the most commonly occuring streamline length
full_length = scipy.stats.mode(streamline_lengths, keepdims=False)[0]
# Create a new streamlines variable that only contains streamlines across the full length.
streamlines_for_clustering = []
colors_for_clustering = []
for k in range(len(self.streamlines)):
if self.streamlines[k].shape[0] == full_length:
streamlines_for_clustering.append(self.streamlines[k])
colors_for_clustering.append(self.color[k])
colors_for_clustering = np.array(colors_for_clustering)
# Larger threshold, fewer clusters
qb = QuickBundles(threshold = float(self.clusteringThresholdEdit.text()))
self.streamlineClusters = qb.cluster(streamlines_for_clustering)
self.streamlineClustersColors = np.empty((len(self.streamlineClusters.centroids), 3))
for k in np.arange(len(self.streamlineClusters.centroids)):
self.streamlineClustersColors[k,:] = self.SceneManager.mode_rows(colors_for_clustering[self.streamlineClusters[k].indices, :])
# Synchronize variables, remove actor, create actor, visualize
self.SceneManager.removeClustersActor()
self.SceneManager.updateClusters(self.streamlineClusters, self.streamlineClustersColors)
self.SceneManager.createClustersActor()
self.SceneManager.visualizeClusters(isChecked)
self.statusBar().showMessage('Creating and visualizing cluster bundles complete.', 2000)
# Progress bar update from threads
def progressUpdate(self, value):
self.progressBar.setValue(value)
self.progressBar2.setValue(value)
# Progress bar minimum value update from threads
def progressMinimum(self, value):
self.progressBar.setMinimum(value)
self.progressBar2.setMinimum(value)
# Progress bar maximum value update from threads
def progressMaximum(self, value):
self.progressBar.setMaximum(value)
self.progressBar2.setMaximum(value)
# Set status bar from threads
def statusBarMessage(self, string):
self.statusBar().showMessage(string)
# Tracking complete signal slot mechanism from threads, sync variables with Scenemanager, update actors
def trackingComplete(self, value):
if value:
if value == 1:
self.streamlines, self.color = self.opticFlowThread.get_streamlines_and_colors()
self.opticFlowThread.terminate_thread()
if value == 2:
self.streamlines, self.color = self.structureTensorThread.get_streamlines_and_colors()
self.structureTensorThread.terminate_thread()
if self.streamlines is None and self.color is None:
msgBox = QMessageBox()
msgBox.setText('Could not read image files, possible error in metadata file for image size fields or images not present in specified path')
msgBox.exec()
return None
self.SceneManager.removeStreamlinesActor()
self.SceneManager.updateStreamlinesAndColors(self.streamlines, self.color)
self.SceneManager.createStreamlinesActor()
self.SceneManager.visualizeStreamlines(self.streamlinesVisibilityCheckbox.isChecked())
self.unique_colors = np.unique(self.color, axis = 0)
self.selectTracksListWidget.clear()
for i in np.arange(self.unique_colors.shape[0]):
listItem = QListWidgetItem('')
listItem.setBackground(QColor(int(self.unique_colors[i][0] * 255), int(self.unique_colors[i][1] * 255),
int(self.unique_colors[i][2] * 255), 200))
self.selectTracksListWidget.addItem(listItem)
self.selectTracksListWidget.setItemDelegate(ColorDelegate(self.selectTracksListWidget))
self.selectTracksListWidget.setSelectionMode(QAbstractItemView.MultiSelection)
self.statusBar().showMessage('Tracks calculated', 5000)
if value == 1:
self.trackingAlgoST = 0
self.trackingAlgoLK = 1
else:
self.trackingAlgoLK = 0
self.trackingAlgoST = 1
# Enable the interactive editing tab
if self.color is not None and self.streamlines is not None:
self.tabWidget.setTabEnabled(1, True)
# Uncheck UI elements to start afresh
self.uncheckStreamlinesUIElements()
# Enable the push buttons back
self.computeTracksLKButton.setEnabled(True)
self.computeTracksSTButton.setEnabled(True)
self.anatomicallyConstrainStreamlinesButton.setEnabled(True)
# Compute tracks with Lucas Kanade slot
def computeTracksLK(self):
try:
windowSize = int(self.windowSizeEdit.text())
maxLevel = int(self.maxLevelEdit.text())
seedsPerPixel = float(self.seedsPerPixelEdit.text())
blur = float(self.blurEdit.text())
except:
msgBox = QMessageBox()
msgBox.setText("Incorrect value for window size and max. level and seeds per pixel, expect integers/floats.")
msgBox.exec()
return None
if self.maskImage is None:
msgBox = QMessageBox()
msgBox.setText("Need to load mask image into memory prior to computing tracks, please click that button.")
msgBox.exec()
return None
if self.imagesPath is None:
msgBox = QMessageBox()
msgBox.setText("Folder path for images is not set, please set it first.")
msgBox.exec()
return None
if len(self.metadata) == 0:
msgBox = QMessageBox()
msgBox.setText("Metadata is not set, please set it first.")
msgBox.exec()
return None
self.opticFlowThread = OpticFlowClass(self.imagesPath, self.maskImage,
self.affine, self.metadata, windowSize, maxLevel,
seedsPerPixel, blur, int(self.tracksStartingSliceIndex.text()),
self.forwardTrackingButton.isChecked(), self.backwardTrackingButton.isChecked())
self.opticFlowThread.progressSignal.connect(self.progressUpdate)
self.opticFlowThread.progressMinimumSignal.connect(self.progressMinimum)
self.opticFlowThread.progressMaximumSignal.connect(self.progressMaximum)
self.opticFlowThread.completeSignal.connect(self.trackingComplete)
self.opticFlowThread.statusBarSignal.connect(self.statusBarMessage)
self.computeTracksLKButton.setEnabled(False)
self.computeTracksSTButton.setEnabled(False)
self.anatomicallyConstrainStreamlinesButton.setEnabled(False)
self.opticFlowThread.start()
# Compute tracks with Structure tensor slot
def computeTracksST(self):
try:
neighborhoodScale = int(self.neighborhoodScaleEdit.text())
noiseScale = float(self.noiseScaleEdit.text())
seedsPerPixel = float(self.seedsPerPixelEdit.text())
downsampleFactor = int(self.downsampleFactor)
except:
msgBox = QMessageBox()
msgBox.setText("Incorrect value for window size and max. level and seeds per pixel, expect integers/floats.")
msgBox.exec()
return None
if self.maskImage is None:
msgBox = QMessageBox()
msgBox.setText("Need to load mask image into memory prior to computing tracks, please click that button.")
msgBox.exec()
return None
if self.imagesPath is None:
msgBox = QMessageBox()
msgBox.setText("Folder path for images is not set, please set it first.")
msgBox.exec()
return None
if len(self.metadata) == 0:
msgBox = QMessageBox()
msgBox.setText("Metadata is not set, please set it first.")
msgBox.exec()
return None
self.structureTensorThread = StructureTensorClass(self.imagesPath, self.maskImage,
self.affine, self.metadata, neighborhoodScale, noiseScale,
seedsPerPixel, downsampleFactor, int(self.tracksStartingSliceIndex.text()),
self.forwardTrackingButton.isChecked(), self.backwardTrackingButton.isChecked())
self.structureTensorThread.progressSignal.connect(self.progressUpdate)
self.structureTensorThread.progressMinimumSignal.connect(self.progressMinimum)
self.structureTensorThread.progressMaximumSignal.connect(self.progressMaximum)
self.structureTensorThread.completeSignal.connect(self.trackingComplete)
self.structureTensorThread.statusBarSignal.connect(self.statusBarMessage)
self.computeTracksLKButton.setEnabled(False)
self.computeTracksSTButton.setEnabled(False)
self.anatomicallyConstrainStreamlinesButton.setEnabled(False)
self.structureTensorThread.start()
# Visualize streamlines checkbox slot
def visualizeStreamlines(self, value):
if self.SceneManager.streamlinesActor is None:
msgBox = QMessageBox()
msgBox.setText("Streamlines not created, click compute tracks button or load existing streamlines file.")
msgBox.exec()
self.streamlinesVisibilityCheckbox.setChecked(False)
return None
self.SceneManager.visualizeStreamlines(value)
# Opacity of streamlines modification slot
def streamlinesOpacity(self, value):
if self.SceneManager.streamlinesActor is None:
msgBox = QMessageBox()
msgBox.setText("Streamlines not created, click compute tracks button or load existing streamlines file.")
msgBox.exec()
return None
self.SceneManager.opacityStreamlines(value)
self.SceneManager.opacityClusters(value)
# Streamline clipping slot
def clipStreamlines(self, isChecked):
if self.SceneManager.streamlinesActor is None:
msgBox = QMessageBox()
msgBox.setText("Streamlines not created, click compute tracks button or load existing streamlines file.")
msgBox.exec()
return None
self.SceneManager.clipStreamlines(isChecked, self.clipStreamlinesSlider.value(), self.xySlider.value(), self.ieTabSelected)
# Streamline clipping slider update slot
def clipStreamlinesSliderUpdate(self, value):
self.clipStreamlinesEdit.setText(str(value))
self.SceneManager.clipStreamlines(self.clipStreamlinesCheckbox.isChecked(), value, self.xySlider.value(), self.ieTabSelected)
# Streamline clipping edit slot
def clipStreamlinesEdit_changed(self):
try:
self.clipStreamlinesSlider.setValue(int(self.clipStreamlinesEdit.text()))
except:
msgBox = QMessageBox()
msgBox.setText("Incorrect value for clip streamlines, expect integer")
msgBox.exec()
return None
self.SceneManager.clipStreamlines(self.clipStreamlinesCheckbox.isChecked(), int(self.clipStreamlinesEdit.text()), self.xySlider.value(), self.ieTabSelected)
# Visualize streamlines by selected colors
def visualizeStreamlinesByColor(self, isChecked):
if isChecked:
selected_indices = self.selectTracksListWidget.selectionModel().selectedIndexes()
if len(selected_indices) == 0:
msgBox = QMessageBox()
msgBox.setWindowTitle("Error")
msgBox.setText("Select streamline colors to keep from list")
msgBox.exec()
self.selectTracksByColorCheckbox.setChecked(False)
return None
unique_colors = np.unique(self.color, axis = 0)
selected_colors = np.zeros((len(selected_indices), 3))
for i in np.arange(len(selected_indices)):
selected_colors[i,:] = unique_colors[int(selected_indices[i].row()), :]
self.SceneManager.visualizeStreamlinesByColor(selected_colors, isChecked, self.streamlinesVisibilityCheckbox.isChecked(), self.streamlinesOpacitySlider.value())
self.SceneManager.visualizeClustersByColor(selected_colors, self.clusterCheckbox.isChecked(), self.streamlinesOpacitySlider.value())
else:
self.SceneManager.removeStreamlinesActor()
self.SceneManager.updateStreamlinesAndColors(self.streamlines, self.color)
self.SceneManager.createStreamlinesActor()
self.SceneManager.visualizeStreamlines(self.streamlinesVisibilityCheckbox.isChecked())
self.SceneManager.removeClustersActor()
self.SceneManager.updateClusters(self.streamlineClusters, self.streamlineClustersColors)
self.SceneManager.createClustersActor()
self.SceneManager.visualizeClusters(self.clusterCheckbox.isChecked())
self.selectTracksListWidget.selectionModel().clear()
# Update color list widget in interactive editing tab, sync XY slice, show streamlines and clip
def interactiveEditingTabSelect(self, tabIndex):
if tabIndex == 1:
self.ieTabSelected = True
self.SceneManager.interactiveEditingTabSelected()
if self.streamlines is not None:
self.pickColorsListWidget.clear()
for i in np.arange(self.unique_colors.shape[0]):
listItem = QListWidgetItem('')
listItem.setBackground(QColor(int(self.unique_colors[i][0] * 255), int(self.unique_colors[i][1] * 255),
int(self.unique_colors[i][2] * 255), 200))
self.pickColorsListWidget.addItem(listItem)
self.pickColorsListWidget.setSelectionMode(QAbstractItemView.SingleSelection)
current_slice_num = int(self.XYSliceEdit.text())
self.streamlinesVisibilityCheckbox.setChecked(True)
self.SceneManager.visualizeXYSlice(current_slice_num, self.streamlinesVisibilityCheckbox.isChecked())
self.SceneManager.visualizeStreamlines(self.streamlinesVisibilityCheckbox.isChecked())
self.clusterCheckbox.setChecked(False)
self.selectTracksByColorCheckbox.setChecked(False)
# Always clip streamlines by 5 slices in interactive editing tab
self.SceneManager.clipStreamlines(self.streamlinesVisibilityCheckbox.isChecked(), 5, current_slice_num, self.ieTabSelected)
else:
current_slice_num = int(self.XYSliceEdit.text())
self.SceneManager.visualizeXYSlice(current_slice_num, False)
if tabIndex == 0:
self.ieTabSelected = False
self.SceneManager.visualizationTabSelected()
current_slice_num = int(self.XYSliceEdit2.text())
# Clip as desired by the user
self.SceneManager.clipStreamlines(self.clipStreamlinesCheckbox.isChecked(), self.clipStreamlinesSlider.value(), current_slice_num, self.ieTabSelected)
# Draw ROI slot, creates the tracer widget
def drawROI(self):
self.startSliceIndex = int(self.XYSliceEdit2.text())
self.SceneManager.tracerWidget('roi', self.startSliceIndex)
self.statusBar().showMessage('Draw a closed contour.', 3000)
# Create a new color and add to list
def addNewColorROI(self):
# Get a new color that is different from all existing colors
unique_colors_transpose = self.unique_colors.T
current_colors_as_list_of_tuples = list(zip(unique_colors_transpose[0], unique_colors_transpose[1], unique_colors_transpose[2]))
current_colors_as_list_of_tuples.append((0, 0, 0))
current_colors_as_list_of_tuples.append((1, 1, 1))
self.userSelectedColor = distinctipy.get_colors(1, current_colors_as_list_of_tuples)
self.statusBar().showMessage('New color created, track with LK or ST!', 3000)
# Pick a color for streamlines from the ROI
def pickColorROI(self, listWidgetItem):
selected_indices = self.pickColorsListWidget.selectionModel().selectedIndexes()
if not len(selected_indices) == 1:
msgBox = QMessageBox()
msgBox.setText("More than one color picked from list, please select only one.")
msgBox.exec()
return None
self.userSelectedColor = np.expand_dims(self.unique_colors[int(selected_indices[0].row()), :], axis = 1).T
self.statusBar().showMessage('Color pick complete, track with LK or ST!', 3000)
# Tracking ROI complete signal
def trackingROIComplete(self, value):
if value:
if value == 1:
streamlines, _ = self.opticFlowThread.get_streamlines_and_colors()
self.opticFlowThread.terminate_thread()
if value == 2:
streamlines, _ = self.structureTensorThread.get_streamlines_and_colors()
self.structureTensorThread.terminate_thread()
if self.streamlines is None and self.color is None:
msgBox = QMessageBox()
msgBox.setText('Could not read image files, possible error in metadata file for image size fields or images not present in specified path')
msgBox.exec()
return None
# Concatenate new streamlines to existing
self.streamlines.extend(streamlines)
# Get user selected color and update self.color
color = np.repeat(self.userSelectedColor, len(streamlines), axis = 0)
self.color = np.concatenate((self.color, color), axis = 0)
self.SceneManager.updateStreamlinesAndColors(self.streamlines, self.color)
self.SceneManager.removeStreamlinesActor()
self.SceneManager.createStreamlinesActor()
self.SceneManager.visualizeStreamlines(self.streamlinesVisibilityCheckbox.isChecked())
self.unique_colors = np.unique(self.color, axis = 0)
self.selectTracksListWidget.clear()
for i in np.arange(self.unique_colors.shape[0]):
listItem = QListWidgetItem('')
listItem.setBackground(QColor(int(self.unique_colors[i][0] * 255), int(self.unique_colors[i][1] * 255),
int(self.unique_colors[i][2] * 255), 200))
self.selectTracksListWidget.addItem(listItem)
self.selectTracksListWidget.setItemDelegate(ColorDelegate(self.selectTracksListWidget))
self.selectTracksListWidget.setSelectionMode(QAbstractItemView.MultiSelection)
self.pickColorsListWidget.clear()
for i in np.arange(self.unique_colors.shape[0]):
listItem = QListWidgetItem('')
listItem.setBackground(QColor(int(self.unique_colors[i][0] * 255), int(self.unique_colors[i][1] * 255),
int(self.unique_colors[i][2] * 255), 200))
self.pickColorsListWidget.addItem(listItem)
self.pickColorsListWidget.setSelectionMode(QAbstractItemView.SingleSelection)
self.statusBar().showMessage('Tracks calculated', 5000)
if value == 1:
self.trackingAlgoST = 0
self.trackingAlgoLK = 1
else:
self.trackingAlgoLK = 0
self.trackingAlgoST = 1
# Remove contour
self.SceneManager.removeContour()
# Visualize streamlines
self.SceneManager.visualizeStreamlines(self.streamlinesVisibilityCheckbox.isChecked())
# Enable push buttons back again
self.trackROI_LKButton.setEnabled(True)
self.trackROI_STButton.setEnabled(True)
# Track with optic flow, ROI only
def trackROI_LK(self):
try:
windowSize = int(self.windowSizeEdit.text())
maxLevel = int(self.maxLevelEdit.text())
seedsPerPixel = float(self.seedsPerPixelEdit.text())
blur = float(self.blurEdit.text())
except:
msgBox = QMessageBox()
msgBox.setText("Incorrect value for window size and max. level and seeds per pixel, expect integers/floats.")
msgBox.exec()
return None
if self.imagesPath is None:
msgBox = QMessageBox()
msgBox.setText("Folder path for images is not set, please set it first.")
msgBox.exec()
return None
if len(self.metadata) == 0:
msgBox = QMessageBox()
msgBox.setText("Metadata is not set, please set it first.")
msgBox.exec()
return None
if self.userSelectedColor is None:
msgBox = QMessageBox()
msgBox.setText("Color not selected, please select from list or click Add a new color button.")
msgBox.exec()
return None
# Start tracking from this slice and use image ROI as mask
mask_image = Image.open('.\\masks\\user-selection.png')
mask_image = np.asarray(mask_image)
self.opticFlowThread = OpticFlowClass(self.imagesPath, mask_image,
self.affine, self.metadata, windowSize, maxLevel,
seedsPerPixel, blur, self.startSliceIndex,
self.forwardTrackingButton2.isChecked(), self.backwardTrackingButton2.isChecked())
self.opticFlowThread.progressSignal.connect(self.progressUpdate)
self.opticFlowThread.progressMinimumSignal.connect(self.progressMinimum)
self.opticFlowThread.progressMaximumSignal.connect(self.progressMaximum)
self.opticFlowThread.completeSignal.connect(self.trackingROIComplete)
self.opticFlowThread.statusBarSignal.connect(self.statusBarMessage)
self.trackROI_LKButton.setEnabled(False)
self.trackROI_STButton.setEnabled(False)
self.opticFlowThread.start()
# Track with structure tensor analysis, ROI only
def trackROI_ST(self):
try:
neighborhoodScale = int(self.neighborhoodScaleEdit.text())
noiseScale = float(self.noiseScaleEdit.text())
seedsPerPixel = float(self.seedsPerPixelEdit.text())
downsampleFactor = int(self.downsampleFactor)
except:
msgBox = QMessageBox()
msgBox.setText("Incorrect value for window size and max. level and seeds per pixel, expect integers/floats.")
msgBox.exec()
return None
if self.imagesPath is None:
msgBox = QMessageBox()
msgBox.setText("Folder path for images is not set, please set it first.")
msgBox.exec()
return None
if len(self.metadata) == 0:
msgBox = QMessageBox()
msgBox.setText("Metadata is not set, please set it first.")
msgBox.exec()
return None
if self.userSelectedColor is None:
msgBox = QMessageBox()
msgBox.setText("Color not selected, please select from list or click Add a new color button.")
msgBox.exec()
return None
# Start tracking from this slice and use image ROI as mask
mask_image = Image.open('.\\masks\\user-selection.png')
mask_image = np.asarray(mask_image)
self.structureTensorThread = StructureTensorClass(self.imagesPath, mask_image,
self.affine, self.metadata, neighborhoodScale, noiseScale,
seedsPerPixel, downsampleFactor, self.startSliceIndex,
self.forwardTrackingButton2.isChecked(), self.backwardTrackingButton2.isChecked())
self.structureTensorThread.progressSignal.connect(self.progressUpdate)
self.structureTensorThread.progressMinimumSignal.connect(self.progressMinimum)
self.structureTensorThread.progressMaximumSignal.connect(self.progressMaximum)
self.structureTensorThread.completeSignal.connect(self.trackingROIComplete)
self.structureTensorThread.statusBarSignal.connect(self.statusBarMessage)
self.trackROI_LKButton.setEnabled(False)
self.trackROI_STButton.setEnabled(False)
self.structureTensorThread.start()
# Remove tracks through ROI
def removeTracksThroughROI(self):
sliceZcoordinates_physical = self.startSliceIndex * self.metadata['image_slice_thickness']
mask_image = Image.open('.\\masks\\user-selection.png')
mask_image = np.asarray(mask_image)
trackIndicesToDelete = []
for i in np.arange(len(self.streamlines)):
for j in np.arange(len(self.streamlines[i])):
if self.streamlines[i][j][2] == sliceZcoordinates_physical:
y_index = self.metadata['y_size_pixels'] - self.streamlines[i][j][1]/self.metadata['pixel_size_xy']
x_index = self.streamlines[i][j][0]/self.metadata['pixel_size_xy']
if mask_image[int(y_index), int(x_index)] == 255:
trackIndicesToDelete.append(int(i))
# Delete select indices
self.streamlines = [ele for idx, ele in enumerate(self.streamlines) if idx not in trackIndicesToDelete]
self.color = np.delete(self.color, trackIndicesToDelete, axis = 0)
# Update variables in SceneManager, update actors
self.SceneManager.removeStreamlinesActor()
self.SceneManager.updateStreamlinesAndColors(self.streamlines, self.color)
self.SceneManager.createStreamlinesActor()
self.unique_colors = np.unique(self.color, axis = 0)
self.selectTracksListWidget.clear()
for i in np.arange(self.unique_colors.shape[0]):
listItem = QListWidgetItem('')
listItem.setBackground(QColor(int(self.unique_colors[i][0] * 255), int(self.unique_colors[i][1] * 255),
int(self.unique_colors[i][2] * 255), 200))
self.selectTracksListWidget.addItem(listItem)
self.selectTracksListWidget.setItemDelegate(ColorDelegate(self.selectTracksListWidget))
self.selectTracksListWidget.setSelectionMode(QAbstractItemView.MultiSelection)
self.pickColorsListWidget.clear()
for i in np.arange(self.unique_colors.shape[0]):
listItem = QListWidgetItem('')
listItem.setBackground(QColor(int(self.unique_colors[i][0] * 255), int(self.unique_colors[i][1] * 255),
int(self.unique_colors[i][2] * 255), 200))
self.pickColorsListWidget.addItem(listItem)
self.pickColorsListWidget.setSelectionMode(QAbstractItemView.SingleSelection)
self.SceneManager.visualizeStreamlines(self.streamlinesVisibilityCheckbox.isChecked())
self.clusterCheckbox.setChecked(False)
self.selectTracksByColorCheckbox.setChecked(False)
self.statusBar().showMessage('Deleted tracks passing through selected ROI', 3000)
# Remove contour
self.SceneManager.removeContour()
# Remove tracks from ROI
def removeTracksFromROI(self):
sliceZcoordinates_physical = self.startSliceIndex * self.metadata['image_slice_thickness']
mask_image = Image.open('.\\masks\\user-selection.png')
mask_image = np.asarray(mask_image)
trackIndicesToDelete = []
locationToDeleteFrom = []
for i in np.arange(len(self.streamlines)):
for j in np.arange(len(self.streamlines[i])):
if self.streamlines[i][j][2] == sliceZcoordinates_physical:
y_index = self.metadata['y_size_pixels'] - self.streamlines[i][j][1]/self.metadata['pixel_size_xy']
x_index = self.streamlines[i][j][0]/self.metadata['pixel_size_xy']
if mask_image[int(y_index), int(x_index)] == 255:
trackIndicesToDelete.append(int(i))
locationToDeleteFrom.append(int(j))
for i in np.arange(len(trackIndicesToDelete)):
currentTrackIndexToClip = trackIndicesToDelete[int(i)]
full_streamline = self.streamlines[currentTrackIndexToClip]
self.streamlines[currentTrackIndexToClip] = full_streamline[:locationToDeleteFrom[int(i)]]
# Sync variables, update actors, visualize
self.SceneManager.removeStreamlinesActor()
self.SceneManager.updateStreamlinesAndColors(self.streamlines, self.color)