-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathROIView.py
executable file
·1563 lines (1456 loc) · 78 KB
/
ROIView.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
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 16:30:54 2013
Class to display and analyze phantom data, mostly MRI data
modules required (most can be installed using 'pip install package' or 'pip install package --upgrade':
Python 2.7.11 (64 bit is better, Python, PyQT4, Numpy can be installed easier using the Anaconda build)
pydicom Version: 0.9.9:
pyqtgraph Version: 0.9.10
lmfit Version: 0.9.0 Used for fitting routines
unwrap Version: 0.1.1
scikit-image Version: 0.11.3: uses unwrap_phase from skimage.resoration
PyOpenGL Used for 3D plotting
Uses ROIViewGui created from ROIViewGui.ui by QT4
execute "pyuic4 ROIViewGui.ui -o ROIViewGui.py" from system shell to regenerate ROIViewGui.py from ROIViewGui.ui
@author: Stephen Russek
Units: times in ms, distances in mm, ADC in mm2/s, Temperature in C,
last modification: 12-25-15
"""
import sys
import os #operating system file/directory names
import copy #copies objects eg ROIsets
import time # use for time, date and sleep
import numpy as np
import numpy.ma as ma #masked arrays eg ROI arrays
from PyQt4 import QtGui, QtCore
import dicom #import pydicom to read DICOM data sets and DICOMDIR
import pyqtgraph as pg #uses pyqtgraph PlotWidget for graphs and ImageView windows for images, http://www.pyqtgraph.org/documentation/introduction.html
import pyqtgraph.opengl as gl
import pyqtgraph.functions as fn
import lmfit #used for nonlinear least square fits,builds on Levenberg-Marquardt algorithm of scipy.optimize.leastsq(),
try:
from unwrap import unwrap #package for phase unwrapping https://pypi.python.org/pypi/unwrap
except:
pass
from skimage.restoration import unwrap_phase
#PhantomViewer modules
from ROIViewGui import Ui_ROIViewGui #main window Gui
import ROIProperties, ROIInfo, PhantomProperties
import T1IRabs, T1VFA, T1VTR, T2SE, DifModel # models for data fitting
import Report, Info
import FitPlots #Plot window to compare data to fits
import ImageList #class to make an image list from a stack of image files
import DICOMDIRlist
import VPhantom, SystemPhantom, DiffusionPhantom,NISThcpPhantom, NISTKTPhantom, NISThcpCoronalPhantom
class ROIView(QtGui.QMainWindow):
"""Main ROI viewing window, customized for different analysis eg geometric distortion, T1, T2, SNR etc"""
def __init__(self, dt,parent = None):
super(ROIView, self).__init__()
pg.setConfigOption('background', 0.2) #Background on plots 0 = black, 1 = white
pg.setConfigOption('foreground', 'w')
self.ui = Ui_ROIViewGui()
self.ui.setupUi(self)
self.modDate = '12/25/2015'
self.wTitle = "PhantomViewer " + self.modDate + ': '
self.setWindowTitle(self.wTitle)
self.nImages=0
self.nCurrentImage=0
self.ims=imageStackWindow(self) #define separate window object for the image stack
self.imswin=self.ims.win #image stack window
self.imv = self.ims.imv #image stack pyqtgraph image view object
# self.ui.gvDicomViewer=pg.ImageView(self.ui.gvDicomViewer,view = pg.PlotItem()) #main image view window
# self.imv=self.ui.gvDicomViewer
try:
self.imv.ui.normBtn.hide() #new pyqtgraph does not have this button
except:
pass
self.imv.ui.roiBtn.setText("Line scan")
self.imv.ui.histogram.plot.setLogMode(None,True) #set the histogram y axis to a log scale
self.imv.vLine = pg.InfiniteLine(angle=90, movable=False) #cross hair
self.imv.hLine = pg.InfiniteLine(angle=0, movable=False)
self.imv.addItem(self.imv.vLine, ignoreBounds=True)
self.imv.addItem(self.imv.hLine, ignoreBounds=True)
self.proxy = pg.SignalProxy(self.imv.view.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
self.proxy2 = pg.SignalProxy(self.imv.view.scene().sigMouseClicked, rateLimit=60, slot=self.mouseClicked)
self.rdPlot=self.ui.gvRawData #plot widget for raw data
self.resultsPlot=self.ui.gvResults #plot widget for results of data fitting
self.dicomHeader = "DICOM Header"
self.setWindowTitle('ROI Viewer')
self.ui.lblnImages.setText((str(self.nImages)))
self.ui.lblCurrentImage.setText("none")
self.ds= ImageList.ImageList() #list of data sets, can be dicom, tiff, fdf
self.seriesFileNames = []
self.image3D = np.array ([1,1])
#signals and slots
# Menu items
#Images
self.ui.actionSelectImages.triggered.connect(self.openFile)
#self.imwinOpenImages.addAction(self.openFile)
self.ui.actionClear_All_Images.triggered.connect(self.clearImages)
self.ui.actionDelete_Current_Image.triggered.connect(self.deleteCurrentImage)
self.ui.actionSort_on_Slice_Loc.triggered.connect(self.sortOnSliceLoc)
self.ui.actionSort_on_TE.triggered.connect(self.sortOnTE)
self.ui.actionWrite_Animated_GIF.triggered.connect(self.writeAnimatedGIF)
#Phantoms
self.ui.actionOpenPhantomFile.triggered.connect(self.openPhantomFile)
self.ui.actionSystem_Phantom.triggered.connect(self.SystemPhantom)
self.ui.actionDiffusion_Phantom.triggered.connect(self.DiffusionPhantom)
self.ui.actionBreast_Phantom.triggered.connect(self.BreastPhantom)
self.ui.actionNIST_hcp_Phantom.triggered.connect(self.NISThcpPhantom)
self.ui.actionNIST_hcp_Coronal_Phantom.triggered.connect(self.NISThcpCoronalPhantom)
self.ui.actionNIST_KT_Phantom.triggered.connect(self.NISTKTPhantom)
self.ui.actionShowPhantomInfo.triggered.connect(self.showPhantomProperties)
self.ui.actionSave_phantom_file.triggered.connect(self.savePhantomFile)
#ROIs
self.ui.actionOpen_ROI_File.triggered.connect(self.openROIFile)
self.ui.actionShow_ROI_Properties.triggered.connect(self.showROIInfo)
self.ui.actionShowHide_ROIs.triggered.connect(self.toggleShowROIs)
self.ui.actionReset_ROIs.triggered.connect(self.resetROIs)
self.ui.actionROI_Color.triggered.connect(self.ROIColor)
#Analysis
self.ui.actionT1_Analysis.triggered.connect(self.T1Analysis)
self.ui.actionT2_Analysis.triggered.connect(self.T2Analysis)
self.ui.actionProton_density_SNR.triggered.connect(self.PDSNRAnalysis)
self.ui.actionDiffusion.triggered.connect(self.diffusionAnalysis)
self.ui.actionPhase_Unwrap.triggered.connect(self.unWrapCurrentImage)
self.ui.actionPlane_Background_Subtract.triggered.connect(self.planeBackgroundSubtract)
self.ui.actionParabola_Background_Subtract.triggered.connect(self.ParabolaBackgroundSubtract)
self.ui.actionImage_Subtraction.triggered.connect(self.imageSubtraction)
#Tools
self.ui.action3dViewer.triggered.connect(self.View3d)
self.ui.actionView3D_color.triggered.connect(self.view3DColor)
self.ui.actionView3D_transparency.triggered.connect(self.view3DTransparency)
self.ui.actionView3D_invert_image.triggered.connect(self.view3Dinvert)
self.ui.actionWrite_to_DICOM.triggered.connect(self.writeDicomFiles)
self.ui.actionFitting_Results.triggered.connect(self.outputReport)
self.ui.actionSave_Results.triggered.connect(self.saveReport)
self.ui.actionClear_Report.triggered.connect(self.clearReport)
self.ui.txtDicomHeader.setHidden(False)
self.ui.txtResults.setHidden(False)
# push buttons and sliders
self.ui.hsROISet.valueChanged.connect(self.changeROISet)
self.ui.vsImage.valueChanged.connect(self.imageSlider)
self.ui.pbReflectX.clicked.connect(self.reflectX)
self.ui.pbReflectY.clicked.connect(self.reflectY)
self.ui.pbReflectZ.clicked.connect(self.reflectZ)
self.ui.pbShowRawData.clicked.connect(self.showRawData)
self.ui.pbFitData.clicked.connect(self.fitData)
self.ui.pbViewFits.clicked.connect(self.viewFits)
self.ui.hsAngle.valueChanged.connect(self.rotateROIs)
self.ui.hsSize.valueChanged.connect(self.reSizeROIs)
self.ui.rbEditROIset.clicked.connect(self.editROISet)
self.ui.rbEditSingleROI.clicked.connect(self.editSingleROI)
self.ui.rbAllSlices.clicked.connect(self.allSlices)
self.ui.rbSelectedSlice.clicked.connect(self.currentSlice)
self.ui.rbUseROIValues.clicked.connect(self.useROIValues) #flag self.useROIValues = True use nominal values as initial guess
self.ui.rbUseBestGuess.clicked.connect(self.useBestGuess) #flag self.useROIValues = False
self.ui.rbViewDicomHeader.toggled.connect(self.viewDicomHeader)
self.ui.txtDicomHeader.setHidden(True) #Image header normally hidden
self.ui.chShowBackgroundROIs.clicked.connect(self.showROIs)
#self.ui.rbViewMessages.toggled.connect(self.viewMessages)
self.ui.lblTE.textChanged.connect(self.TEChanged)
self.TEChangedFlag = True #flag to input new TE values
self.ui.lblTR.textChanged.connect(self.TRChanged)
self.TRChangedFlag = True #flag to input new TR values
# setup regions of interest (ROIs)
self.dataType = str(dt) #string indicating data type "T1", "T2", "PD-SNR", DIF ; determines what fitting models are accessible
self.setDataType(self.dataType)
self.ADCmap = False
self.Phantom = VPhantom.VPhantom()
self.ui.lblPhantomType.setText(self.Phantom.phantomName)
self.ROIset = "T1Array" #determines which ROI set to use via ROIsetdict
self.InitialROIs = VPhantom.ROISet("default") #Current ROIs are initial ROIs with global rotation and translation
self.currentROIs=copy.deepcopy(self.InitialROIs)
self.currentROI = 1 #currently selected ROI
self.useROIValues = False #flag to instruct fits to take initial guesses from the current ROI values
self.pgROIs=[] #list of pyqtgraph ROIs
self.pgROIlabels = [] #List of labels that go with ROIs
self.bShowROIs = False #Flag to determine if ROIs are shown or hidden
self.roiPen = pg.mkPen('g', width=3) #one of: r, g, b, c, m, y, k, w or R, G, B, [A] integers 0-255 or (R, G, B, [A]) tuple of integers 0-255
self.lblColor=(255,204,0)
self.lblFont=QtGui.QFont()
self.lblFont.setPixelSize(18)
self.bShowSNRROIs = False #flag to show SNR ROIs to measure background signal; used to determine points that are in the background
self.bSNRROIs = False #flag to indicate SNR ROIs are plotted
self.snrPen = pg.mkPen('c', width=3)
self.ROItrans=np.array([0,0,0], float) #ROI translation
self.bResetROIs = True #flag to reset ROIs to initials positions
self.relativeOffseth = 0.0 #horizontal and vertical offsets of the ROI positions
self.relativeOffsetv = 0.0
self.theta = 0.0 #current rotation of the ROIs in radians
self.bEditROISet = True #flag to specify whether to edit ROI set or an individual ROI
self.bAllSlices = False #flag to specify if all slices will be analyzed or just currently selected one
self.view3DColor = QtGui.QColor(255, 255 ,255 , alpha=10)
self.view3DBackground = QtGui.QColor(155, 155 ,255 , alpha=10)
self.view3DTransparency = 1.75 #set transparency scaling for 3dview, 1 = transparency set by voxel value
self.view3Dinvert = False #flag to invert contrast in 3d image
#global data structures
self.rdy = np.array([0.,0.]) # 2d numpy array of raw data (usually signal averaged i= ROI j=image number in stack)
self.rdx = np.array([0.]) # numpy array of imaging parameter that is varied ie TE, TI, FA etc; usually a 1d array (independent variable)
self.rdBackground = np.array([0.]) #average background counts in signal free region in reduced image array
self.background = 0. #background averaged over images
self.noisefactor= 1.5 #data below noisefactor*background will not be fit
self.fity=np.zeros((14,100)) # 2d numpy array of fitting model using optimized parameters
self.fitx = np.arange(100) # 100 element numpy array of imaging parameter spanning range of image data (independent variable)
self.clickArray = [] # list of numpy array of points generated from mouse clicks on the images
self.T1Params = [] #list of lmfit dictionaries
self.report="" # String to record all output to allow printing or saving a report
self.imageDirectory = '' #last opened image directory
self.showReferenceValues = True #flag to show reference parameter values listed in phantom type or ROI file
self.sliceList = [] #ordered list of slices in the current image stack
self.reverseSliceOrder = False #flag to reverse slice order
self.reverseTEOrder = False #flag to reverse TE order
def setupPhantom(self, phantom):
self.Phantom=phantom
self.ui.lblPhantomType.setText(self.Phantom.phantomName)
self.currentROIs = self.Phantom.ROIsets[0] #Current ROIs are initial ROIs with global rotation and translation
self.ui.hsROISet.setMaximum(len(self.Phantom.ROIsets)-1)
self.ui.hsROISet.setValue(0)
self.ui.lblROISet.setText(self.Phantom.ROIsets[0].ROIName)
self.ROIset = self.Phantom.ROIsets[0].ROIName #determines which ROI set to use via ROIsetdict
self.InitialROIs=copy.deepcopy(self.currentROIs) #make copy to reset if necessary
self.roiPen = pg.mkPen(self.currentROIs.ROIColor, width=3)
self.useROIValues = False #default use best guess for initial fitting parameters, if true use ROI values
self.ui.rbUseBestGuess.setChecked(True) #does not seem to work
self.showReferenceValues = True
self.resetROIs()
def SystemPhantom (self):
self.setupPhantom(SystemPhantom.SystemPhantom())
def DiffusionPhantom (self):
self.setupPhantom(DiffusionPhantom.DiffusionPhantom())
self.dataType = "Dif"
self.setDataType(self.dataType)
def BreastPhantom (self):
pass
def NISThcpPhantom (self):
self.setupPhantom(NISThcpPhantom.hcpPhantom())
def NISThcpCoronalPhantom (self):
self.setupPhantom(NISThcpCoronalPhantom.hcpCoronalPhantom())
def NISTKTPhantom (self):
self.setupPhantom(NISTKTPhantom.KTPhantom())
def showPhantomInfo(self):
'''Shows phantom information and image'''
if hasattr(self,"InfoWindow")==False:
self.InfoWindow = Info.InfoWindow()
self.InfoWindow.show()
self.InfoWindow.setWindowTitle(self.Phantom.phantomName )
self.InfoWindow.ui.lblInfo.setPixmap(QtGui.QPixmap('MRISystemPhantom.jpg'))
self.InfoWindow.ui.lblInfo.show()
def showPhantomProperties(self):
'''Shows phantom image'''
if hasattr(self,"PhantomProperties")==False:
self.PhantomProperties = PhantomProperties.PhantomProperties(self.Phantom)
self.PhantomProperties.show()
self.PhantomProperties.setWindowTitle(self.Phantom.phantomName )
def openDICOMdir (self,filename):
"""Opens DICOMDIR and selected image series"""
d1= [] #d1 is 3d data stack for 3d images
dcmdir = dicom.read_dicomdir(str(filename))
if hasattr(self,"DICOMDIRGui")==False:
self.DICOMDIRlist=DICOMDIRlist.DICOMDIRlist(self)
self.DICOMDIRlist.setWindowTitle("DICOMDIR list" )
self.DICOMDIRlist.ui.lblDICOMDIR.setText(filename)
dv=self.DICOMDIRlist.ui.listDICOMDIR
for patrec in dcmdir.patient_records:
s = "Patient: {0.PatientID}: {0.PatientsName}".format(patrec)
studies = patrec.children
for study in studies:
s= s + " Study {0.StudyID}: {0.StudyDate}".format(study)
try:
s= s + " Study description {0.StudyDescription}".format(study)
except:
pass
dv.addItem(s)
all_series = study.children
for series in all_series:
nImages = len(series.children)
plural = ('', 's')[nImages > 1]
if not 'SeriesDescription' in series:
series.SeriesDescription = "N/A"
s= "Series={0.SeriesNumber}, {0.Modality}: {0.SeriesDescription}" " ({1} image{2})".format(series, nImages, plural)
dv.addItem(s)
image_records = series.children
image_filenames = [os.path.join(self.imageDirectory, *image_rec.ReferencedFileID) for image_rec in image_records]
if self.DICOMDIRlist.exec_(): #dialog to return list of selected DICOM series to open
nSeries=self.DICOMDIRlist.selectedSeries()
else:
return
nImages = 0
for study in studies:
all_series = study.children
for series in all_series:
if str(series.SeriesNumber) in nSeries:
nImages += len(series.children)
image_records = series.children
image_filenames = [os.path.join(self.imageDirectory, *image_rec.ReferencedFileID) for image_rec in image_records]
self.seriesFileNames.extend(image_filenames)
nFiles= len(image_filenames)
dialogBox = QtGui.QProgressDialog(labelText = 'Importing Files...',minimum = 0, maximum = nFiles)
dialogBox.setCancelButton(None)
dsets= [dicom.read_file(image_filename)for image_filename in image_filenames]
for i,dcds in enumerate(dsets): #unpack DICOM data sets (dcds)
self.ds.unpackImageFile (dcds, image_filenames[i], "dcm")
d1.append(self.ds.PA[i+1])
dialogBox.setValue(i)
self.nImages += nImages
self.ui.lblnImages.setText(str(self.nImages))
self.ui.vsImage.setMinimum(1) #set slider to go from 1 to the number of images
self.ui.vsImage.setMaximum(self.nImages)
self.nCurrentImage=1
self.ui.vsImage.setValue(self.nCurrentImage)
self.displayCurrentImage()
self.image3D= np.dstack(d1)
self.imswin.show()
def openFile (self):
d1= [] #d1 is 3d data stack for 3d images
self.fileNames = QtGui.QFileDialog.getOpenFileNames(self,"Open Image Files or DICOMDIR",self.imageDirectory )
if not self.fileNames: #if cancel is pressed return
return None
self.imageDirectory=os.path.dirname(str(self.fileNames[0]))#Save current directory
if len(self.fileNames) == 1: #check to see if file is a DICOMDIR
filename=self.fileNames[0]
if "DICOMDIR" in filename:
self.openDICOMdir(filename)
return None
self.seriesFileNames.extend(self.fileNames) #concatenate new file list with previous file list
nFiles= len(self.fileNames)
dialogBox = QtGui.QProgressDialog(labelText = 'Importing Files...',minimum = 0, maximum = nFiles)
dialogBox.setCancelButton(None)
for i in range(nFiles):
fileName = self.fileNames[i]
fstatus=self.ds.addFile(fileName)
if fstatus[0]:
d1.append(self.ds.PA[i+1])
dialogBox.setValue(i)
else:
self.msgPrint(fstatus[1]) #Could not open or read file
self.sliceList = sorted(set(self.ds.SliceLocation)) #make an ordered list of slices
self.nImages=len(self.ds.FileName)-1
self.ui.lblnImages.setText(str(self.nImages))
if self.nImages < 1 :
limage = 0
else:
limage = 1
self.ui.vsImage.setMinimum(limage) #set slider to go from 1 to the number of images
self.ui.vsImage.setMaximum(self.nImages)
self.nCurrentImage=limage
self.ui.vsImage.setValue(self.nCurrentImage)
self.displayCurrentImage()
if len(d1)>0:
self.image3D= np.dstack(d1)
self.imswin.show()
def writeDicomFiles (self):
fileName = QtGui.QFileDialog.getSaveFileName(parent=None, caption="Dicom File Name")
if not fileName: #if cancel is pressed return
return None
self.ds.writeDicomFiles(str(fileName)) #write current image list in DICOM format to filename+ imagenumber + .dcm
def writeAnimatedGIF (self):
fileName = QtGui.QFileDialog.getSaveFileName(parent=None, caption="GIF File Name")
if not fileName: #if cancel is pressed return
return None
self.ds.writeAnimatedGIF(fileName) #write current image list to GIF
def changeROISet (self):
self.InitialROIs =self.Phantom.ROIsets[self.ui.hsROISet.value()]
self.ui.lblROISet.setText(self.InitialROIs.ROIName)
self.resetROIs()
def imageSlider (self):
self.nCurrentImage=self.ui.vsImage.value()
self.displayCurrentImage()
def displayCurrentImage (self):
'''Displays current image as set by self.nCurrentImage and associated header parameters'''
i=self.nCurrentImage
self.ui.lblCurrentImage.setText(str(self.nCurrentImage))
self.ui.lblDate.setText(format(self.ds.StudyDate[i]))
self.ui.lblDataType.setText(format(self.ds.DataType[i]))
self.ui.lblFileName.setText(self.ds.FileName[i])
self.ui.lblManufacturer.setText(self.ds.Manufacturer[i])
self.ui.lblSeries.setText(self.ds.SeriesDescription[i])
self.ui.lblInstitution.setText(self.ds.InstitutionName[i])
self.ui.lblField.setText(str(self.ds.MagneticFieldStrength[i]))
self.ui.lblReceiveCoil.setText(str(self.ds.ReceiveCoilName[i]))
self.ui.lblPatient.setText(self.ds.PatientName[i])
self.ui.lblProtocol.setText(str(self.ds.ProtocolName[i]))
self.ui.lblBW.setText(str(self.ds.PixelBandwidth[i]))
self.TEvaries=not(self.checkEqual(self.ds.TE))
if self.TEvaries:
self.T2Analysis()
self.ui.lblTE.setStyleSheet("background-color: yellow") if self.TEvaries else self.ui.lblTE.setStyleSheet("background-color: white")
self.ui.lblTE.setText(str(self.ds.TE[i]))
self.TRvaries = not(self.checkEqual(self.ds.TR))
if self.TRvaries:
self.ui.tabT1.setCurrentIndex(2)
self.ui.lblTR.setStyleSheet("background-color: yellow") if self.TRvaries else self.ui.lblTR.setStyleSheet("background-color: white")
self.ui.lblTR.setText(str(self.ds.TR[i]))
self.ui.lblColumns.setText(str(self.ds.Columns[i]))
self.ui.lblRows.setText(str(self.ds.Rows[i]))
self.TIvaries = not(self.checkEqual(self.ds.TI))
if self.TIvaries:
self.ui.tabT1.setCurrentIndex(0)
self.ui.lblTI.setStyleSheet("background-color: yellow") if self.TIvaries else self.ui.lblTI.setStyleSheet("background-color: white")
self.ui.lblTI.setText(str(self.ds.TI[i]))
self.ui.lblSliceThickness.setText("{:.2f}".format(self.ds.SliceThickness[i]))
self.sliceLocationVaries = not(self.checkEqual(self.ds.SliceLocation))
self.ui.lblSliceLocation.setStyleSheet("background-color: yellow") if self.sliceLocationVaries else self.ui.lblSliceLocation.setStyleSheet("background-color: white")
self.ui.lblSliceLocation.setText("{:.2f}".format(self.ds.SliceLocation[i]))
self.ui.lblPixelSpacingRow.setText("{:.2f}".format(self.ds.PixelSpacingX[i]))
self.ui.lblPixelSpacingCol.setText("{:.2f}".format(self.ds.PixelSpacingY[i]))
self.FAvaries = not(self.checkEqual(self.ds.FA))
if self.FAvaries:
self.ui.tabT1.setCurrentIndex(1)
self.ui.lblFA.setStyleSheet("background-color: yellow") if self.FAvaries else self.ui.lblFA.setStyleSheet("background-color: white")
self.ui.lblFA.setText(str(self.ds.FA[i]))
self.ui.lblPhaseEncodeDirection.setText(str(self.ds.InPlanePhaseEncodingDirection[i]))
self.ui.lblFoVX.setText(str(self.ds.FoVX[i]))
self.ui.lblFoVY.setText(str(self.ds.FoVY[i]))
self.ui.lblbValue.setText(str(self.ds.bValue[i]))
self.bvaries=not(self.checkEqual(self.ds.bValue))
if self.bvaries:
self.diffusionAnalysis()
self.ui.lblbValue.setStyleSheet("background-color: yellow")
else:
self.ui.lblFA.setStyleSheet("background-color: white")
data = self.ds.PA[i]
xscale =self.ds.PixelSpacingX[i] if (self.ds.PixelSpacingX[i] > 0.) else 1
yscale = self.ds.PixelSpacingY[i] if (self.ds.PixelSpacingY[i] > 0.) else 1
xmin = -self.ds.FoVX[i]/2 #set origin to center of image, need to upgrade to set by DICOM tag
ymin = -self.ds.FoVY[i]/2
self.ui.lblUpperLeft.setText("UL=" + "{:.1f}".format(self.ds.ImagePosition[i][0]) + "," + "{:.1f}".format(self.ds.ImagePosition[i][1]) + "," + "{:.1f}".format(self.ds.ImagePosition[i][2]))
self.imv.setImage(data,pos = (xmin,ymin), scale = (xscale,yscale),)
self.ui.txtDicomHeader.setText(self.ds.header[i])
# self.ui.lbldX.setText(str(self.ROItrans[0]))
# self.ui.lbldY.setText(str(self.ROItrans[1]))
# self.ui.lbldZ.setText(str(self.ROItrans[2]))
self.imv.getView().setLabel('bottom',self.DirectionLabel(self.ds.RowDirection[i]),"mm")
self.imv.getView().setLabel('left',self.DirectionLabel(self.ds.ColumnDirection[i]),"mm")
self.ui.lblScaleSlope.setText("{:.3e}".format(self.ds.ScaleSlope[i]))
self.ui.lblScaleIntercept.setText("{:.3e}".format(self.ds.ScaleIntercept[i]))
def toggleShowROIs(self):
self.bShowROIs =not self.bShowROIs
self.showROIs()
def showROIs(self):
"""Displays ROIs if bShowROI is True, erase ROIs if false"""
if self.bShowROIs :
self.roiPen = pg.mkPen(self.currentROIs.ROIColor, width=3)
self.ui.lbldh.setText(str(self.relativeOffseth))
self.ui.lbldv.setText(str(self.relativeOffsetv))
self.ui.lblCurrentROIs.setText(str(self.currentROIs.ROIName))
self.ui.lblnROIs.setText(str(self.currentROIs.nROIs))
self.pgROIs = []
self.bShowSNRROIs = self.ui.chShowBackgroundROIs.isChecked()
for roi in self.currentROIs.ROIs:
r=np.array([roi.Xcenter,roi.Ycenter,roi.Zcenter])
imCoord=self.GlobaltoRel(r,self.nCurrentImage)
pgroi=fCircleROI(self,[imCoord[0]-roi.d1/2, imCoord[1]-roi.d1/2], [roi.d1, roi.d1],str(roi.Index), pen=self.roiPen) #needs work
pgroi.Index=roi.Index
self.pgROIs.append(pgroi)
for roi in self.pgROIs:
self.imv.getView().addItem(roi)
self.imv.getView().addItem(roi.label)
if self.currentROIs.showBackgroundROI:
roi=self.Phantom.SNRROIs.ROIs[0]
r=np.array([roi.Xcenter,roi.Ycenter,roi.Zcenter])
imCoord=self.GlobaltoRel(r,self.nCurrentImage)
bgroi=fCircleROI(self,[imCoord[0]-roi.d1/2, imCoord[1]-roi.d1/2], [roi.d1, roi.d1],"SNR", pen=self.snrPen)
self.imv.getView().addItem(bgroi)
self.bgROI=bgroi
self.bSNRROIs=True
if self.currentROIs.showSNRROI:
roi=self.Phantom.SNRROIs.ROIs[1]
r=np.array([roi.Xcenter,roi.Ycenter,roi.Zcenter])
imCoord=self.GlobaltoRel(r,self.nCurrentImage)
snrroi=fCircleROI(self,[imCoord[0]-roi.d1/2, imCoord[1]-roi.d1/2], [roi.d1, roi.d1],"SNR", pen=self.snrPen)
self.imv.getView().addItem(snrroi)
self.snrROI=snrroi
self.bSNRROIs=True
else: #remove all ROIs from the images
if hasattr(self,"pgROIs"):
for roi in self.pgROIs:
self.imv.getView().removeItem(roi)
self.imv.getView().removeItem(roi.label)
if self.bSNRROIs:
self.imv.getView().removeItem(self.snrROI)
self.bSNRROIs=False
self.pgROIs = []
self.ui.lblnROIs.setText("")
self.ui.lblCurrentROIs.setText("")
def showROIInfo(self):
if self.ui.cbViewROIInfo.isChecked():
if hasattr(self,"ROIInfo")==False:
self.ROIInfo = ROIInfo.ROIInfoWindow()
self.ROIInfo.setWindowTitle(" ROI Info")
self.ROIInfo.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
point = self.rect().topLeft()
self.ROIInfo.move(point) #QtCore.QPoint(self.width(), 0))
self.ROIInfo.update(self.currentROIs,self.currentROI, self)
self.ROIInfo.show()
def editROISet(self):
self.bEditROISet = True
def editSingleROI(self):
self.bEditROISet = False
def allSlices(self):
self.bAllSlices = True
def currentSlice(self):
self.bAllSlices = False
def useROIValues(self):
self.useROIValues = True
def useBestGuess(self):
self.useROIValues = False
def resetROIs(self):
self.currentROIs=copy.deepcopy(self.InitialROIs)
self.theta=0.0
self.ui.lblPhantomAngle.setText("0")
self.ui.hsAngle.setValue(0)
self.relativeOffseth = 0.0 #horizontal and vertical offsets of the ROI positions
self.relativeOffsetv = 0.0
self.redrawROIs()
def redrawROIs(self):
self.bShowROIs = False #erase and redraw initial ROIs
self.showROIs()
self.bShowROIs = True
self.showROIs()
def ROIColor(self):
col = QtGui.QColorDialog.getColor()
self.roiPen = pg.mkPen(col, width=3)
self.redrawROIs()
def openROIFile(self):
if hasattr(self,"ROIprop")==False:
self.ROIprop = ROIProperties.ROIProperties(self.Phantom)
self.ROIprop.setWindowTitle("ROI Properties")
self.ROIprop.openROIFile(self.imageDirectory)
self.bShowROIs=True
self.redrawROIs()
def reflectX(self):
for roi in self.currentROIs.ROIs:
roi.Xcenter=-roi.Xcenter
self.redrawROIs()
def reflectY(self):
for roi in self.currentROIs.ROIs:
roi.Ycenter=-roi.Ycenter
self.redrawROIs()
def reflectZ(self):
for roi in self.currentROIs.ROIs:
roi.Zcenter=-roi.Zcenter
self.redrawROIs()
def translateROIs(self,tvector,snap, roiindex):
self.relativeOffseth += tvector[0]
self.relativeOffsetv += tvector[1]
self.ui.lbldh.setText(str(self.relativeOffseth))
self.ui.lbldv.setText(str(self.relativeOffsetv))
r=self.reltoGlobal(tvector[0],tvector[1],self.nCurrentImage)
if self.bEditROISet == True: #translate ROI set
for roi in self.pgROIs:
roi.translate(tvector, snap=False, finish=False)
roi.label.setPos(roi.pos())
self.currentROIs.translate(r)
else: #translate single ROI with roiindex
roi = self.pgROIs[roiindex-1]
roi.translate(tvector, snap=False, finish=False)
roi.label.setPos(roi.pos())
self.currentROIs.ROIs[roiindex-1].translate(r)
def rotateROIs(self):
if hasattr(self,"currentROIs"):
t=float(self.ui.hsAngle.value())/2
self.ui.lblPhantomAngle.setText("{:.1f}".format(t))
thetanew=float(t * np.pi / 180.)
dtheta=thetanew-self.theta
perpAxis=np.cross(self.ds.RowDirection[self.nCurrentImage], self.ds.ColumnDirection[self.nCurrentImage])
self.theta=thetanew
self.currentROIs.rotate(perpAxis, dtheta)
for i, roi in enumerate(self.pgROIs): #change position of ROIs in pyqtgraph imageview object
r=np.array([self.currentROIs.ROIs[i].Xcenter,self.currentROIs.ROIs[i].Ycenter,self.currentROIs.ROIs[i].Zcenter])
(h,v) = self.GlobaltoRel(r,self.nCurrentImage)
roi.setPos((h-self.currentROIs.ROIs[i].d1/2,v-self.currentROIs.ROIs[i].d1/2))
roi.label.setPos(h-self.currentROIs.ROIs[i].d1/2,v-self.currentROIs.ROIs[i].d1/2)
def deleteROI(self,roi):
if roi.Index >> 0:
del self.currentROIs.ROIs[roi.Index-1]
for i,roi in enumerate(self.currentROIs.ROIs): #rename ROI indexes
roi.Index=i+1
self.currentROIs.nROIs = len(self.currentROIs.ROIs)
self.bShowROIs = False
self.showROIs()
self.bShowROIs = True
self.showROIs()
def addROI(self,pos):
newROI = VPhantom.ROI()
r=self.reltoGlobal(pos.x(),pos.y(),self.nCurrentImage)
newROI.Xcenter=r[0]
newROI.Ycenter=r[1]
newROI.Zcenter=r[2]
newROI.d1=10
newROI.Index=len(self.currentROIs.ROIs) +1
newROI.Name = "def-" + str(newROI.Index)
self.currentROIs.ROIs.append(newROI)
self.bShowROIs = False
self.showROIs()
self.bShowROIs = True
self.showROIs()
def reSizeROIs(self):
if hasattr(self,"currentROIs"):
size=float(self.ui.hsSize.value())/2
self.ui.lblROISize.setText("{:.1f}".format(size))
if self.bEditROISet == True: #change size in ROI set
for roi in self.currentROIs.ROIs: #initial ROIs remain unchanged
roi.d1=size
else:
self.currentROI.d1=size
for roi in self.pgROIs: #erase ROIs
self.imv.getView().removeItem(roi)
self.imv.getView().removeItem(roi.label)
self.pgROIs = []
self.showROIs() #redraw ROIs
def savePhantomFile(self):
fileName = QtGui.QFileDialog.getSaveFileName(parent=None, caption="Save ROI File", directory = self.imageDirectory, selectedFilter = ".dat")
if not fileName: #if cancel is pressed return
return None
f= open(fileName, 'w')
self.Phantom.ROIsets[0]=self.currentROIs
s = self.Phantom.printROIinfo()
f.write(s)
f.close()
def openPhantomFile(self):
self.Phantom=VPhantom.VPhantom()
self.Phantom.readPhantomFile(self.imageDirectory)
self.InitialROIs =self.Phantom.ROIsets[0]
self.ui.lblROISet.setText(self.InitialROIs.ROIName)
self.ui.hsROISet.setMaximum(self.Phantom.nROISets)
self.resetROIs()
def checkEqual(self, lst): #returns True if all elements (except the 0th element) of the list are equal
return lst[2:] == lst[1:-1]
def clearImages (self): #Deletes all images except default image at index 1
self.ds= ImageList.ImageList() #list of data sets, can be dicom, tiff, fdf
del self.seriesFileNames[:]
self.nCurrentImage=0
self.nImages=0
self.ui.txtResults.clear()
#self.image3D.zeros [1,1,1]
self.displayCurrentImage()
self.ui.lblnImages.setText(str(self.nImages))
self.ui.vsImage.setMaximum(0)
self.rdPlot.setLabel('left', "Counts", units='A')
self.rdPlot.setLabel('bottom', "X Axis", units='s')
self.rdPlot.setTitle("Raw Data")
self.rdPlot.clear()
self.resultsPlot.clear()
self.resultsPlot.setLabel('bottom', "X Axis", units='s')
self.resultsPlot.setTitle("Results")
# self.resetROIs()
def deleteCurrentImage(self):
if self.nCurrentImage > 0:
self.ds.deleteImage(self.nCurrentImage)
self.nImages -= 1
self.ui.lblnImages.setText(str(self.nImages))
self.ui.vsImage.setMinimum(1) #set slider to go from 1 to the number of images
self.ui.vsImage.setMaximum(self.nImages)
if self.nImages == 0:
self.nCurrentImage=0
else:
self.nCurrentImage = 1
self.ui.vsImage.setValue(self.nCurrentImage)
self.displayCurrentImage()
def sortOnSliceLoc(self):
self.ds.sortImageList(self.ds.SliceLocation)
self.displayCurrentImage()
self.msgPrint('Images reorderd by slice location\n')
def sortOnTE(self):
self.ds.sortImageList(self.ds.TE)
self.displayCurrentImage()
self.msgPrint('Images reorderd by TE\n')
self.reverseTEOrder = not self.reverseTEOrder #toggle order
def unWrapCurrentImage(self):
'''unwraps a phase image using '''
self.operateOnAll=self.ui.cbOperateOnAllImages.isChecked()
if self.nCurrentImage > 0:
if self.operateOnAll == False:
self.ds.PA[self.nCurrentImage] = unwrap(self.ds.PA[self.nCurrentImage],wrap_around_axis_0=False, wrap_around_axis_1=False,wrap_around_axis_2=False)
if self.operateOnAll == True:
for i in range(1,len(self.ds.PA)):
#self.ds.PA[i] = unwrap(self.ds.PA[i],wrap_around_axis_0=False, wrap_around_axis_1=False,wrap_around_axis_2=False)
self.ds.PA[i] =unwrap_phase(self.ds.PA[i]) #From SKIMAGE should be similar to unwrap
self.displayCurrentImage()
def planeBackgroundSubtract(self):
'''subtracts a plane defined by 3 points set by the previous mouse clicks'''
self.operateOnAll=self.ui.cbOperateOnAllImages.isChecked()
r1=self.clickArray[-3]
r2=self.clickArray[-2]
r3=self.clickArray[-1]
if self.operateOnAll == False:
a=np.cross(r2-r1,r3-r1)
an=np.linalg.norm(a)
a=a/an
plane=np.zeros([self.ds.Rows[self.nCurrentImage],self.ds.Columns[self.nCurrentImage]])
for i in range(int(self.ds.Rows[self.nCurrentImage])):
for j in range(int(self.ds.Columns[self.nCurrentImage])):
plane[i,j]=(-a[0]*(i-r1[0])-a[1]*(j-r1[1]))/a[2]+r1[2]
self.ds.PA[self.nCurrentImage]=self.ds.PA[self.nCurrentImage]-plane
if self.operateOnAll == True:
for ii in range(1,len(self.ds.PA)): #Subtract planar background from all images
r1[2]=self.ds.PA[ii][int(r1[0]),int(r1[1])] #set value of three in plane vectors
r2[2]=self.ds.PA[ii][int(r2[0]),int(r2[1])]
r3[2]=self.ds.PA[ii][int(r3[0]),int(r3[1])]
a=np.cross(r2-r1,r3-r1)
an=np.linalg.norm(a)
a=a/an
plane=np.zeros([self.ds.Rows[ii],self.ds.Columns[ii]])
for i in range(int(self.ds.Rows[ii])):
for j in range(int(self.ds.Columns[ii])):
plane[i,j]=(-a[0]*(i-r1[0])-a[1]*(j-r1[1]))/a[2]+r1[2]
self.ds.PA[ii]=self.ds.PA[ii]-plane
self.displayCurrentImage()
def ParabolaBackgroundSubtract(self):
r1=self.clickArray[-3]
r2=self.clickArray[-2]
r3=self.clickArray[-1]
z1=self.clickArray[-3][2]
z2=self.clickArray[-2][2]
z3=self.clickArray[-1][2]
r1[2]=0
r2[2]=0
r3[2]=0
Sav=(z1+z2)/2
d=np.linalg.norm(np.cross((r2-r1),(r3-r1))/np.linalg.norm(r2-r1))
a=(Sav-z3)/d**2
#print ("a= " + str(a))
#print ("Sav= " + str(Sav))
#print ("d= " + str(d))
#print ( str(z1) + str(z2)+str(z3))
# self.PBGSubtract.setText("r1,r2,r3 = " +str(r1) + str(r2)+ str(r3))
# self.PBGSubtract.setModal(True)
# self.PBGSubtract.show()
parab=np.zeros([self.ds.Rows[self.nCurrentImage],self.ds.Columns[self.nCurrentImage]])
for i in range(int(self.ds.Rows[self.nCurrentImage])):
for j in range(int(self.ds.Columns[self.nCurrentImage])):
r0=np.array([i,j,0])
d=np.linalg.norm(np.cross((r2-r1),(r0-r1))/np.linalg.norm(r2-r1))
parab[i,j]=a*d**2
self.ds.PA[self.nCurrentImage]=self.ds.PA[self.nCurrentImage]+parab
self.displayCurrentImage()
def imageSubtraction(self):
text, ok = QtGui.QInputDialog.getText(self, 'Image Subtraction', 'Image number to be subtracted:')
iscale=1.
i=int(text)
if ok and i > 0 and i < len(self.ds.PA)-1:
self.ds.PA[self.nCurrentImage]=self.ds.PA[self.nCurrentImage]- iscale*self.ds.PA[i]
self.displayCurrentImage()
def mouseClicked(self, evt):
'''Adds points to point array used for analysis and background subtraction, adds or subtracts ROI'''
pos = evt[0] ## using signal proxy turns original arguments into a tuple
mousePoint = self.imv.view.vb.mapSceneToView(pos.scenePos())
if abs(mousePoint.x()) < self.ds.FoVX[self.nCurrentImage]/2 and abs(mousePoint.y()) < self.ds.FoVY[self.nCurrentImage]/2:
Xindex = int((mousePoint.x()+self.ds.FoVX[self.nCurrentImage]/2)/self.ds.PixelSpacingX[self.nCurrentImage]) #if self.ds.PixelSpacingX[self.nCurrentImage] > 0. else Xindex = int(mousePoint.x())
Yindex = int((mousePoint.y()+self.ds.FoVY[self.nCurrentImage]/2)/self.ds.PixelSpacingY[self.nCurrentImage]) #if self.ds.PixelSpacingY[self.nCurrentImage] > 0. else Yindex = int(mousePoint.y())
value= self.ds.PA[self.nCurrentImage][Xindex,Yindex]
self.msgPrint ( "Add point: " + "I= " + str(Xindex) + ", J=" + str(Yindex) + ", z=" + str(value) + "\n")
pnt= np.array([float(Xindex),float(Yindex),float(value)])
self.clickArray.append(pnt)
if self.ui.rbDeleteROI.isChecked():
self.deleteROI(self.currentROI)
if self.ui.rbAddROI.isChecked():
self.addROI(mousePoint)
def viewDicomHeader (self):
if self.ui.rbViewDicomHeader.isChecked():
self.ui.txtDicomHeader.setHidden(False)
dh = str(self.ds.header[self.nCurrentImage])
if dh == '':
dh="DICOM Header"
self.ui.txtDicomHeader.setText(dh)
else:
self.ui.txtDicomHeader.setHidden(True)
#=============================================================================
# def viewMessages (self):
# if self.ui.rbViewMessages.isChecked():
# self.ui.txtResults.setHidden(False)
# else:
# self.ui.txtResults.setHidden(True)
#=============================================================================
def view3DColor(self):
self.view3DColor = QtGui.QColorDialog.getColor()
self.View3d()
def view3DTransparency(self):
t = 15.
t , ok = QtGui.QInputDialog.getInteger( None,'Transparency' , 'Enter value 1 (solid) to 100 transparent', value=15, min=1, max=100, step=1)
if ok:
self.view3DTransparency = t/10.0
self.View3d()
def view3Dinvert(self):
self.view3Dinvert = not self.view3Dinvert
self.View3d()
def View3d(self):
'''creates 3d rendering of current image stack'''
if not hasattr(self,"view3Dwin"):
self.view3Dwin = gl.GLViewWidget()
self.view3Dwin.opts['distance'] = 300
self.view3Dwin.resize(800,800)
self.view3Dwin.setWindowTitle('3D View ' )
self.view3Dwin.show()
try:
self.view3Dwin.removeItem(self.image3DVol)
except:
pass
ax = gl.GLAxisItem()
self.view3Dwin.addItem(ax)
# g = gl.GLGridItem()
# g.scale(10, 10, 10)
# self.view3Dwin.addItem(g)
data=self.image3D.astype(float) /float(self.image3D.max()) #normalize data to 1
if self.view3Dinvert :
data=1-data
d2 = np.empty(data.shape + (4,), dtype=np.ubyte)
d2[..., 0] = data * self.view3DColor.red()
d2[..., 1] = data * self.view3DColor.green()
d2[..., 2] = data * self.view3DColor.blue()
d2[..., 3] = (data)**self.view3DTransparency * 255. #sets transparency
d2[:, 0:3, 0:3] = [255,0,0,20] #draw axes at corner of box
d2[0:3, :, 0:3] = [0,255,0,20]
d2[0:3, 0:3, :] = [0,0,255,20]
self.image3DVol=gl.GLVolumeItem(d2)
self.image3DVol.translate(-128,-128,-128)
self.view3Dwin.addItem(self.image3DVol)
#self.view3Dwin.update(self.geometry())
#self.view3Dwin.repaint(self.geometry())
def mouseMoved(self,evt):
'''mouse move event to move crosshairs and display location and values'''
pos = evt[0] ## using signal proxy turns original arguments into a tuple
if self.imv.view.sceneBoundingRect().contains(pos):
mousePoint = self.imv.view.vb.mapSceneToView(pos)
self.ui.lblH.setText("{:.2f}".format(mousePoint.x()))
self.ui.lblV.setText("{:.2f}".format(mousePoint.y()))
if abs(mousePoint.x()) < self.ds.FoVX[self.nCurrentImage]/2 and abs(mousePoint.y()) < self.ds.FoVY[self.nCurrentImage]/2:
Xindex = int((mousePoint.x()+self.ds.FoVX[self.nCurrentImage]/2)/self.ds.PixelSpacingX[self.nCurrentImage]) #if self.ds.PixelSpacingX[self.nCurrentImage] > 0. else Xindex = int(mousePoint.x())
Yindex = int((mousePoint.y()+self.ds.FoVY[self.nCurrentImage]/2)/self.ds.PixelSpacingY[self.nCurrentImage]) #if self.ds.PixelSpacingY[self.nCurrentImage] > 0. else Yindex = int(mousePoint.y())
value= self.ds.PA[self.nCurrentImage][Xindex,Yindex]
self.ui.lblValue.setText("{:.2f}".format(value))
rc= self.reltoGlobal(mousePoint.x(), mousePoint.y(), self.nCurrentImage)
self.ui.lblX.setText("{:.2f}".format(rc[0]))
self.ui.lblY.setText("{:.2f}".format(rc[1]))
self.ui.lblZ.setText("{:.2f}".format(rc[2]))
self.imv.vLine.setPos(mousePoint.x())
self.imv.hLine.setPos(mousePoint.y())
def reltoGlobal (self, h,v,n): #given relative coordinate h,v of image n returns np vector of global coordinates
#rc= ((h+self.ds.FoVX[n]/2) * self.ds.RowDirection[n]+(v+self.ds.FoVX[n]/2)*self.ds.ColumnDirection[n])+self.ds.ImagePosition[n]
rc= (h* self.ds.RowDirection[n]+v*self.ds.ColumnDirection[n])
return rc
def GlobaltoRel(self,r,n): #Given r vector in global coordinates returns h,v in image plane of image n
h=np.dot(r,self.ds.RowDirection[n])
v=np.dot(r,self.ds.ColumnDirection[n])
# h=np.dot(r-self.ds.ImageCenter[n],self.ds.RowDirection[n])
# v=np.dot(r-self.ds.ImageCenter[n],self.ds.ColumnDirection[n])
return [h,v]
def DirectionLabel (self,Vector): #returns a direction label corresponding to input vector
Label = ""
if abs(Vector[0])> 0.01:
Label = "{:.2f}".format(Vector[0]) + "X "
if abs(Vector[1])> 0.01:
Label += "+ " + "{:.2f}".format(Vector[1]) +"Y "
if abs(Vector[2])> 0.01:
Label += "+ " + "{:.2f}".format(Vector[2]) +"Z"
return Label
def showRawData(self):
'''Plots ROI signal vs relevant parameter; outputs data in self.rdx and self.rdy'''
self.ui.txtResults.clear()
self.msgPrint (self.imageDirectory + "\n")
self.msgPrint ("Data Type = " + self.dataType + "\n")
self.msgPrint ("Raw data: " + time.strftime("%c") + os.linesep)
self.rdPlot.clear()
if self.bAllSlices == True: #analyze all slices together
self.reducedImageSet= range(1,len(self.ds.PA))
self.msgPrint ("Slice locations(mm)=" + str(self.ds.SliceLocation[1:]) + "\n")
else: # only analyze images which are at the current slice location
currentSL = self.ds.SliceLocation[self.nCurrentImage]
self.reducedImageSet= [i for i, val in enumerate(self.ds.SliceLocation)if val == currentSL]
self.msgPrint ("Slice location(mm)=" + "{:6.1f}".format(self.ds.SliceLocation[self.nCurrentImage]) + "\n")
rd = np.zeros((len(self.pgROIs),len(self.reducedImageSet)))
# Set independent variable (parameter that is being varied ie TI, TE, TR, b etc
# T1 data
if self.dataType == "T1":
if self.ui.tabT1.currentIndex() == 0: #T1 Inversion Recovery
self.rdPlot.setLogMode(x=False,y=True)
self.rdPlot.setLabel('bottom', "TI(ms)")
self.rdx = np.array([self.ds.TI[i] for i in self.reducedImageSet])
self.msgPrint ( "TI(ms)=")
for ti in self.rdx:
self.msgPrint ( "{:12.1f}".format(ti))
if self.ui.tabT1.currentIndex() == 1: #T1 VFA
self.rdPlot.setLogMode(x=False,y=False)
self.rdPlot.setLabel('bottom', "FA(deg)")
self.rdx = np.array([self.ds.FA[j] for j in self.reducedImageSet])
self.msgPrint ( "FA(deg)=")
for fa in self.rdx:
self.msgPrint ( "{:12.1f}".format(fa))
if self.ui.tabT1.currentIndex() == 2: #T1 VTR
self.rdPlot.setLogMode(x=False,y=False)
self.rdPlot.setLabel('bottom', "TR(ms)")
self.rdx = np.array([self.ds.TR[j] for j in self.reducedImageSet])
self.msgPrint ( "TR(ms)=")
for tr in self.rdx:
self.msgPrint ( "{:12.1f}".format(tr))
self.msgPrint (os.linesep)
#T2 Data
if self.dataType == "T2":
self.rdPlot.setLogMode(x=False,y=True)
self.rdPlot.setLabel('bottom', "TE(ms)")
self.rdx = np.array([self.ds.TE[i] for i in self.reducedImageSet])
self.msgPrint ( "TE(ms)=")
for te in self.rdx:
self.msgPrint ( "{:12.1f}".format(te))
self.msgPrint (os.linesep)
#Diffusion Data
if self.dataType == "Dif":
if self.ui.tabDif.currentIndex() == 0: #fit signal vs b-value
self.ADCmap = False
self.rdPlot.setLogMode(x=False,y=True)
self.rdPlot.setLabel('bottom', "b(s/mm^2)")
self.rdx = np.array([self.ds.bValue[i] for i in self.reducedImageSet])
self.msgPrint ( "b(s/mm^2)=")
for b in self.rdx:
self.msgPrint ( "{:12.1f}".format(b))
self.msgPrint (os.linesep)
if self.ui.tabDif.currentIndex() == 1: #ADC map
self.ADCmap = True
self.rdPlot.setLogMode(x=False,y=False)
self.rdPlot.setLabel('bottom', "ROI")
self.rdx = np.array([roi.Index for roi in self.currentROIs.ROIs])
#PD Data
if self.dataType == "PD-SNR":
self.rdPlot.setLogMode(x=False,y=False)
self.rdx = np.array([roi.PD for roi in self.currentROIs.ROIs])
self.msgPrint ( "PD(%)=")
for pd in self.rdx: #note that the first image is a blank dummy
self.msgPrint ( "{:12.1f}".format(pd))
self.msgPrint (os.linesep)
#Set and Plot raw signal data
for i, roi in enumerate(self.pgROIs):
self.msgPrint ("ROI-" +"{:02d}".format(i+1) + ' ')
for j, pa in enumerate([self.ds.PA[k] for k in self.reducedImageSet]):
array = roi.getArrayRegion(pa,self.imv.getImageItem())
rd[i ,j]= (array.mean()-self.ds.ScaleIntercept[self.reducedImageSet[j]])/self.ds.ScaleSlope[self.reducedImageSet[j]] #corrects for scaling in Phillips data
self.msgPrint ( "{:12.3f}".format(rd[i,j]) )
c = self.rgb_to_hex(self.setPlotColor(i))
if self.dataType in ["T1" , "T2", "Dif"] and not self.ADCmap:
self.rdPlot.plot(self.rdx, rd[i,:],pen=self.setPlotColor(i),symbolBrush=self.setPlotColor(i), symbolPen='w', name=self.currentROIs.ROIs[i].Name)
self.ui.lblRdLegend.insertHtml('<font size="5" color=' + c + '>' + u"\u25CF" + '</font>' + self.currentROIs.ROIs[i].Name + '<BR>' ) #u"\u25CF" + '<BR>'
self.msgPrint (os.linesep)