def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.homeDir = os.getcwd() #self.ui.registration.clicked.connect(self.registrationFunc) self.ui.segmentation.clicked.connect(self.micosFunc) #This is MICOS self.ui.segmentation2.clicked.connect(self.autoregsegFunc) # This is AutoRegSeg self.ui.segmentation3.clicked.connect(self.segmentationFunc3) # This is stereo to seg method self.ui.volumeButton.clicked.connect(self.volumeDisplayFunc) self.ui.headerInfo.clicked.connect(self.headerInfoFunc) #self.ui.calculate_features.clicked.connect(self.calculateGLCMFeaturesFunc) #Function to run feature calculations self.ui.scribble.stateChanged.connect(self.scribbleEditFunc) # This is drawing function self.ui.imageSlider.valueChanged.connect(self.imageSliderFunc) self.ui.loadPatientData.clicked.connect(self.loadDataFunc) self.ui.load3DSeg.clicked.connect(self.load3DSegFunc) self.ui.saveROI.clicked.connect(self.saveROIFunc) self.ui.overlaySeg.clicked.connect(self.overlaySegFunc) self.scrolFlag2 = self.ui.figure2.canvas.mpl_connect('scroll_event', self.scrollT2WImage) self.clickFlag2 = self.ui.figure2.canvas.mpl_connect('button_press_event', self.onclickWidget2) self.clickFlag3 = self.ui.figure3.canvas.mpl_connect('button_press_event', self.onclickWidget3) self.clickFlag4 = self.ui.figure4.canvas.mpl_connect('button_press_event', self.onclickWidget4) self.ui.figure2.canvas.mpl_connect('key_press_event',self.keyPressEventFunc) self.ui.grayLow.valueChanged.connect(self.grayLowFunc) self.ui.grayHigh.valueChanged.connect(self.grayHighFunc) self.ui.autogray.clicked.connect(self.autograyFunc) self.ui.figure2.canvas.fig.tight_layout() self.ui.figure3.canvas.fig.tight_layout() self.ui.figure4.canvas.fig.tight_layout() #initialize Variables self.thVal = None self.scribbling = False self.micos_flag = 0 self.roiload_flag = 0 self.main_dir = os.getcwd()
class Main(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.homeDir = os.getcwd() #self.ui.registration.clicked.connect(self.registrationFunc) self.ui.segmentation.clicked.connect(self.micosFunc) #This is MICOS self.ui.segmentation2.clicked.connect(self.autoregsegFunc) # This is AutoRegSeg self.ui.segmentation3.clicked.connect(self.segmentationFunc3) # This is stereo to seg method self.ui.volumeButton.clicked.connect(self.volumeDisplayFunc) self.ui.headerInfo.clicked.connect(self.headerInfoFunc) #self.ui.calculate_features.clicked.connect(self.calculateGLCMFeaturesFunc) #Function to run feature calculations self.ui.scribble.stateChanged.connect(self.scribbleEditFunc) # This is drawing function self.ui.imageSlider.valueChanged.connect(self.imageSliderFunc) self.ui.loadPatientData.clicked.connect(self.loadDataFunc) self.ui.load3DSeg.clicked.connect(self.load3DSegFunc) self.ui.saveROI.clicked.connect(self.saveROIFunc) self.ui.overlaySeg.clicked.connect(self.overlaySegFunc) self.scrolFlag2 = self.ui.figure2.canvas.mpl_connect('scroll_event', self.scrollT2WImage) self.clickFlag2 = self.ui.figure2.canvas.mpl_connect('button_press_event', self.onclickWidget2) self.clickFlag3 = self.ui.figure3.canvas.mpl_connect('button_press_event', self.onclickWidget3) self.clickFlag4 = self.ui.figure4.canvas.mpl_connect('button_press_event', self.onclickWidget4) self.ui.figure2.canvas.mpl_connect('key_press_event',self.keyPressEventFunc) self.ui.grayLow.valueChanged.connect(self.grayLowFunc) self.ui.grayHigh.valueChanged.connect(self.grayHighFunc) self.ui.autogray.clicked.connect(self.autograyFunc) self.ui.figure2.canvas.fig.tight_layout() self.ui.figure3.canvas.fig.tight_layout() self.ui.figure4.canvas.fig.tight_layout() #initialize Variables self.thVal = None self.scribbling = False self.micos_flag = 0 self.roiload_flag = 0 self.main_dir = os.getcwd() def headerInfoFunc(self): fileIS = nib.load(str(self.getFileNAME)) print fileIS.get_header() def autograyFunc(self,event): if self.ui.autogray.checkState()==2: self.autoGrayFlag = 1 else: self.autoGrayFlag = 0 def grayLowFunc(self,event): #self.graylowlevel = event #self.autoGrayFlag = 0 self.imshowFunc() def grayHighFunc(self,event): #self.grayhighlevel = event #self.autoGrayFlag = 0 self.imshowFunc() def keyPressEventFunc(self, event): # This function defines controls for coronal window (up/down a slice) # As well as fast key functions for power users. key = event.key if key == 'up': #scroll up a slice if self.z2 + 1 <= self.maxSlice: self.z2 = self.z2 + 1 self.ui.lineEdit.setText(str(self.z2)) self.img2 = self.img_data2[:,:,self.z2] self.z = self.z2 self.imshowFunc() if key == 'down': #scroll down a slice if self.z2 - 1 >= 0: self.z2 = self.z2 - 1 self.ui.lineEdit.setText(str(self.z2)) self.img2 = self.img_data2[:,:,self.z2] self.z = self.z2 self.imshowFunc() if key == '9': #tap '9' to change brush size to 9.0 self.ui.brushSize.setValue((9.0)) if key == '8': #tap '8' to change brush size to 8.0 self.ui.brushSize.setValue((8.0)) if key == '7': #tap '7' to change brush size to 7.0 self.ui.brushSize.setValue((7.0)) if key == '6': #tap '6' to change brush size to 6.0 self.ui.brushSize.setValue((6.0)) if key == '5': #tap '5' to change brush size to 5.0 self.ui.brushSize.setValue((5.0)) if key == '4': #tap '4' to change brush size to 4.0 self.ui.brushSize.setValue((4.0)) if key == '3': #tap '3' to change brush size to 3.0 self.ui.brushSize.setValue((3.0)) if key == '2': #tap '2' to change brush size to 2.0 self.ui.brushSize.setValue((2.0)) if key == '1': #tap '1' to change brush size to 1.0 self.ui.brushSize.setValue((1.0)) if key == 'u': #tap 'u' to undo last segmentation edit self.redoHoldSeg = self.segImg.copy() self.segImg = self.holdLastSeg.copy() self.imshowFunc() if key == 'r': # tap 'r' to redo an undo self.segImg = self.redoHoldSeg.copy() self.imshowFunc() if key == 'v': #click 'v' to recalculate and see volume self.volumeDisplayFunc() if key == 's': # toggle with 's' the overlay tool if self.ui.overlaySeg.checkState()==2: self.ui.overlaySeg.setCheckState(0) else: self.ui.overlaySeg.setCheckState(2) self.imshowFunc() if key == 'd': #toggle with 'd' the drawing tool if self.ui.scribble.checkState()==2: self.ui.scribble.setCheckState(0) else: self.ui.scribble.setCheckState(2) if key == 'w': #toggle with 'w' the watershed edge detection if self.ui.freehand.checkState()==2: self.ui.freehand.setCheckState(0) else: self.ui.freehand.setCheckState(2) if key == 'g': #toggle with 'g' the auto gray leveling if self.ui.autogray.checkState()==2: self.ui.autogray.setCheckState(0) self.autoGrayFlag = 0 else: self.ui.autogray.setCheckState(2) self.autoGrayFlag = 1 if key == 'q': #with q keep only two largest objects (or if only two objects keep only largest) self.holdLastSeg = self.segImg.copy() #save previous state in case need to undo #first determine if region is 0's or 1's row = int(event.ydata) col = int(event.xdata) regVal = self.segImg[row,col,self.z] mgac = self.segImg[:,:,self.z].copy() labelSlice,numFeatures = label(mgac) minVal = 0 for i in range(0,numFeatures): sumLabel = np.sum(labelSlice==(i+1)) if sumLabel > minVal: maxlabel = i + 1 minVal = sumLabel minVal = 0 for i in range(0,numFeatures): sumLabel = np.sum(labelSlice==(i+1)) if sumLabel > minVal and i+1 != maxlabel: max2label = i + 1 minVal = sumLabel labelPointsVal = labelSlice[row,col] outputFilledImage = self.segImg[:,:,self.z].copy() * 0 outputFilledImage[labelSlice==maxlabel] = 1 if numFeatures > 2: outputFilledImage[labelSlice==max2label] = 1 self.segImg[:,:,self.z] = outputFilledImage > 0 #this will be final after flood fill. self.segImg[0,0,self.z] = 0 #need at least one zero value for overlay (matplotlib overlay bug???) self.imshowFunc() (row,col,dep) = self.img_data2.shape self.overlayImgAX = np.zeros((row,col)) if key == 'e': #with 'e' fill in any empty enclosed regions. self.holdLastSeg = self.segImg.copy() self.segImg[:,:,self.z] = imfill(self.segImg[:,:,self.z]) self.imshowFunc() def calculateGLCMFeaturesFunc(self): # This needs to be changed, utilize features from CalculateFeatures command # The ants versions just returns values (not images) os.chdir(self.main_dir) if self.ui.glcmCB.checkState()==2: # Run GLCM textures print "TextureCooccurrenceFeatures 3 " + str(self.getFileNAME) + " 16" subprocess.Popen("TextureCooccurrenceFeatures 3 " + "'"+str(self.getFileNAME)+"'" + " 16", shell = True) if self.ui.glcmCB.checkState()==2: # Run GLCM textures print "TextureRunLengthFeatures 3 " + str(self.getFileNAME) + " 16" subprocess.Popen("TextureRunLengthFeatures 3 " + "'"+str(self.getFileNAME)+"'" + " 16", shell = True) return def micosFunc(self): # Call MICOS as sub-process command line call os.chdir(self.main_dir) print "python ../../src/MICOS.py --mri_scan " + str(self.getFileNAME) subprocess.Popen("python ../../src/MICOS.py --mri_scan " + '"' + str(self.getFileNAME) + '"', shell = True) start_time = time.clock() self.micos_flag = 1 self.micos_name = str(self.getFileNAME[:-7])+'_FASTseg_MICOS.nii.gz' self.roiload_flag = 0 # Trying something to get fastseg back into GUI (need While True to run this) # Currently just wait for MICOS to finish, then click loadROI button return def scrollT2WImage(self, event): if (event.step > 0 and self.z2 != 0): self.z2 = self.z2 - 1 self.ui.lineEdit.setText(str(self.z2)) elif (event.step < 0 and self.z2 < self.sliceNum2): self.z2 = self.z2 + 1 self.ui.lineEdit.setText(str(self.z2)) self.img2 = self.img_data2[:,:,self.z2] self.z = self.z2 self.imshowFunc() def loadDataFunc(self): #Function for loading image file self.ui.autogray.setCheckState(2) self.autoGrayFlag = 1 getFileNAME = QFileDialog.getOpenFileName() if str(getFileNAME)[-4:] == '.avw': #if avw file, do conversion, and then work with nifti file MR = loadAVW(str(getFileNAME)) avw2nifti(str(getFileNAME[:-4]) + 'avw', MR, seg=None) getFileNAME = str(getFileNAME[:-4]) + 'avw.nii.gz' #print getFileNAME self.getFileNAME = getFileNAME self.ui.displayFileName.setText(str(os.path.basename(str(self.getFileNAME)))) self.z =0 self.z1 = 0 self.z2 = 0 self.rotD = -90 imgObj2= nib.load(str(getFileNAME)) imgObj1 = imgObj2 self.affine2 = imgObj2.get_affine() self.PSx = imgObj1.get_header()['pixdim'][1] self.PSy = imgObj1.get_header()['pixdim'][2] self.PSz = imgObj1.get_header()['pixdim'][3] (x,y,z) = orx.aff2axcodes(self.affine2) self.Orx = x self.Ory = y self.Orz = z ornt = orx.axcodes2ornt((x,y,z)) refOrnt = orx.axcodes2ornt(('R','S','A')) #was 'R', 'A', 'S' newOrnt = orx.ornt_transform(ornt,refOrnt) self.ornt = ornt self.refOrnt = refOrnt self.img_data2 = imgObj2.get_data() self.img_data2 = orx.apply_orientation(self.img_data2,newOrnt) self.img_data2 = np.fliplr(np.rot90(self.img_data2,1)) self.img_data1 = self.img_data2 self.imageFile2 = str(getFileNAME) #changed self.ui.T2Image.currentText() to getFileNAME self.imageFile1 = self.imageFile2 indx2 = self.imageFile2.rfind('/') indx1 = indx2 self.filePath1 = self.imageFile1[0:indx1+1] self.fileName1 = self.imageFile1[indx1+1:] self.filePath2 = self.imageFile2[0:indx2+1] self.fileName2 = self.imageFile2[indx2+1:] # sizeT1C = self.img_data1.shape try: (x1,y1,z1) = self.img_data1.shape (x2,y2,z2) = self.img_data2.shape except: (x1,y1,z1,d1) = self.img_data1.shape (x2,y2,z2,d1) = self.img_data2.shape self.img_data1 = self.img_data1[:,:,:,0] self.img_data2 = self.img_data2[:,:,:,0] self.sliceNum1 = z1 self.sliceNum2 = z2 self.shape = self.img_data2.shape self.img1 = self.img_data1[:,:,self.z] self.img2 = self.img_data2[:,:,self.z] self.segImg = self.img_data2 * 0 self.imshowFunc() (x,y,z) = self.shape self.ui.figure3.canvas.ax.clear() # self.ui.figure3.canvas.ax.imshow(((self.img_data2[:,round(x/2),:])),cmap=plt.cm.gray) self.ui.figure3.canvas.ax.imshow(((self.img_data2[:,round(x/2),:])),cmap=plt.cm.gray) #self.ui.figure3.canvas.ax.set_aspect('auto') self.ui.figure3.canvas.ax.get_xaxis().set_visible(False) self.ui.figure3.canvas.ax.get_yaxis().set_visible(False) #self.ui.figure3.canvas.ax.set_title('Sagittal View', color = 'white') #this is where had sagittal view self.ui.figure3.canvas.draw() self.ui.figure4.canvas.ax.clear() self.ui.figure4.canvas.ax.imshow(np.rot90((self.img_data2[round(y/2),:,:]),1),cmap=plt.cm.gray) #self.ui.figure4.canvas.ax.set_aspect('auto') self.ui.figure4.canvas.ax.get_xaxis().set_visible(False) self.ui.figure4.canvas.ax.get_yaxis().set_visible(False) #self.ui.figure4.canvas.ax.set_title('Axial View', color = 'white') self.ui.figure4.canvas.draw() # self.imhistFunc() self.ui.imageSlider.setMinimum(0) self.ui.imageSlider.setMaximum(z2-1) self.ui.imageSlider.setSingleStep(1) self.maxSlice = z2 - 1 (row,col,dep) = self.img_data2.shape self.overlayImgAX = np.zeros((row,col)) return def imageSliderFunc(self): self.ui.lineEdit.setText(str(self.ui.imageSlider.value())) self.z = self.ui.imageSlider.value() self.img1 =self.img_data1[:,:,self.z] self.img2 =self.img_data2[:,:,self.z] self.imshowFunc() def biasFieldCorrFunc(self): biasFieldCorrection(self.filePath1,self.filePath2,self.imageFile1,self.imageFile2,self.fileName1,self.fileName2) self.ui.T1Contrast.addItem(self.filePath1 + self.fileName1[:len(self.fileName1)-4] + '_corrected.nii') index = self.ui.T1Contrast.findText(self.filePath1 + self.fileName1[:len(self.fileName1)-4] + '_corrected.nii') self.ui.T1Contrast.setCurrentIndex(index) self.ui.T2Image.addItem(self.filePath2 + self.fileName2[:len(self.fileName2)-4] + '_corrected.nii') index = self.ui.T2Image.findText(self.filePath2 + self.fileName2[:len(self.fileName2)-4] + '_corrected.nii') self.ui.T2Image.setCurrentIndex(index) self.loadDataFunc() def volumeDisplayFunc(self): self.ROIvolume = np.round(np.sum(self.segImg)*self.PSx*self.PSy*self.PSz / 1000) self.ui.displayVolume.setText(str(self.ROIvolume)) self.ROImean = np.round(np.mean(self.img_data2[self.segImg>0])) self.ui.displayMean.setText(str(self.ROImean)) def resetUpdateSeg(self): self.segImg = deepcopy(self.original3DSeg) self.overlayImgCOR = np.zeros((self.shape[2],self.shape[1])) self.overlayImgSAG = np.zeros((self.shape[2],self.shape[0])) self.overlayImgAX = np.zeros((self.shape[0],self.shape[1])) def registrationFunc(self): #Placeholder for adding registration functionality rFlag = self.ui.rigidCB.isChecked() aFlag = self.ui.affineCB.isChecked() nrFlag = self.ui.nonrigidCB.isChecked() atFlag = self.ui.atlasCB.isChecked() atSFlag = self.ui.atlasCBS.isChecked() if (rFlag == 1 and aFlag == 0 and nrFlag == 0 and atFlag == 0): fixedImg = self.filePath2 + self.fileName2 movingImg = self.filePath1 + self.fileName1 rigidRegFunc(self.filePath2,self.fileName1,fixedImg,movingImg) self.ui.T1Contrast.addItem(self.filePath2 + 'rigid_reg_' + self.fileName1) index = self.ui.T1Contrast.findText(self.filePath2 + 'rigid_reg_' + self.fileName1) self.ui.T1Contrast.setCurrentIndex(index) self.loadDataFunc() elif (rFlag == 0 and aFlag == 1 and nrFlag == 0 and atFlag == 0): fixedImg = self.filePath2 + self.fileName2 movingImg = self.filePath1 + self.fileName1 affineRegFunc(self.filePath2,self.fileName1,fixedImg,movingImg) self.ui.T1Contrast.addItem(self.filePath2 + 'affine_reg_' + self.fileName1) index = self.ui.T1Contrast.findText(self.filePath2 + 'affine_reg_' + self.fileName1) self.ui.T1Contrast.setCurrentIndex(index) self.loadDataFunc() elif (rFlag == 0 and aFlag == 0 and nrFlag == 1 and atFlag == 0): fixedImg = self.filePath2 + self.fileName2 movingImg = self.filePath1 + self.fileName1 nonrigidRegFunc(self.filePath2,self.fileName1,fixedImg,movingImg) self.ui.T1Contrast.addItem(self.filePath2 + 'nonrigid_reg_' + self.fileName1) index = self.ui.T1Contrast.findText(self.filePath2 + 'nonrigid_reg_' + self.fileName1) self.ui.T1Contrast.setCurrentIndex(index) self.loadDataFunc() elif (rFlag == 0 and aFlag == 0 and nrFlag == 0 and atFlag == 1): fixedImg = self.filePath2 + self.fileName2 movingImg = self.filePath1 + self.fileName1 atlasRegFunc(self.homeDir, self.filePath2,self.fileName2,fixedImg,movingImg) self.ui.T1Contrast.addItem(self.filePath2 + 'registeredAtlas_' + self.fileName2) index = self.ui.T1Contrast.findText(self.filePath2 + 'registeredAtlas_' + self.fileName2) self.ui.T1Contrast.setCurrentIndex(index) self.loadDataFunc() elif (rFlag == 0 and aFlag == 0 and nrFlag == 0 and atSFlag == 1): fixedImg = self.filePath2 + self.fileName2 movingImg = self.filePath1 + self.fileName1 atlasRegFunc2(self.homeDir, self.filePath2,self.fileName2,fixedImg,movingImg) self.ui.T1Contrast.addItem(self.filePath2 + 'registeredAtlas_' + self.fileName2) index = self.ui.T1Contrast.findText(self.filePath2 + 'registeredAtlas_' + self.fileName2) self.ui.T1Contrast.setCurrentIndex(index) self.loadDataFunc() elif (rFlag == 0 and aFlag == 1 and nrFlag == 1 and atFlag == 0): fixedImg = self.filePath2 + self.fileName2 movingImg = self.filePath1 + self.fileName1 affine_nonrigidRegFunc(self.filePath2,self.fileName1,fixedImg,movingImg) self.ui.T1Contrast.addItem(self.filePath2 + 'affine_nonrigid_reg_' + self.fileName1) index = self.ui.T1Contrast.findText(self.filePath2 + 'affine_nonrigid_reg_' + self.fileName1) self.ui.T1Contrast.setCurrentIndex(index) self.loadDataFunc() elif (rFlag == 1 and aFlag == 0 and nrFlag == 1 and atFlag == 0): fixedImg = self.filePath2 + self.fileName2 movingImg = self.filePath1 + self.fileName1 rigid_nonrigidRegFunc(self.filePath2,self.fileName1,fixedImg,movingImg) self.ui.T1Contrast.addItem(self.filePath2 + 'rigid_nonrigid_reg_' + self.fileName1) index = self.ui.T1Contrast.findText(self.filePath2 + 'rigid_nonrigid_reg_' + self.fileName1) self.ui.T1Contrast.setCurrentIndex(index) self.loadDataFunc() else: fixedImg = self.filePath2 + self.fileName2 movingImg = self.filePath1 + self.fileName1 affineRegFunc(self.filePath2,self.fileName1,fixedImg,movingImg) self.ui.T1Contrast.addItem(self.filePath2 + 'affine_nonrigid_reg_' + self.fileName1) index = self.ui.T1Contrast.findText(self.filePath2 + 'affine_nonrigid_reg_' + self.fileName1) self.ui.T1Contrast.setCurrentIndex(index) self.loadDataFunc() def segmentationFunc(self): asdf = 1 def autoregsegFunc(self): # Auto reg seg segmentation method #os.chdir(self.main_dir) # First ask user for files to send to auto reg seg method baselineScan = QFileDialog.getOpenFileName(caption = "Select the Baseline Scan") baselineSeg = QFileDialog.getOpenFileName(caption = "Select the Baseline Segmentation") followupImage = QFileDialog.getOpenFileName(caption = "Select the Followup Scan") # Now run autoregseg as sub-process os.chdir(self.main_dir) subprocess.Popen("python ../../src/AutoRegSegTKV.py" + " --prior_scan " + str(baselineScan) + " --prior_seg " + str(baselineSeg) + " --followup_scan " + str(followupImage) + " --followup_seg_name " + str(followupImage[:-7] + "_AutoRegSeg.nii.gz"), shell = True) def segmentationFunc3(self): # Using for MICOS_justpoly #Placeholder for stereo to seg segmentation method (not sure really needed in the gui) #os.chdir(self.main_dir) #subprocess.Popen("python ../../src/stereo2seg.py", shell = True) # Call MICOS as sub-process command line call os.chdir(self.main_dir) print "python ../../src/MICOS_justpoly.py --mri_scan " + str(self.getFileNAME) subprocess.Popen("python ../../src/MICOS_justpoly.py --mri_scan " + '"' + str(self.getFileNAME) + '"', shell = True) def load3DSegFunc(self): if self.micos_flag == 1: getFileNAME = self.micos_name self.micos_flag = 0 self.roiload_flag = 0 else: getFileNAME = QFileDialog.getOpenFileName() self.roiload_flag = 1 segImgObj = nib.load(str(getFileNAME)) segImgData = segImgObj.get_data() ornt = orx.axcodes2ornt((self.Orx,self.Ory,self.Orz)) refOrnt = orx.axcodes2ornt(('R','S','A')) newOrnt = orx.ornt_transform(ornt,refOrnt) segImgData = orx.apply_orientation(segImgData,newOrnt) segImgData = np.fliplr(np.rot90(segImgData,1)) self.segImg = deepcopy(segImgData) self.ui.overlaySeg.setChecked(True) self.imshowFunc() #self.affine2 = segImgObj.get_affine() #self.displayROI() def overlaySegFunc(self): self.imshowFunc() def imshowFunc(self): overlayFlag = self.ui.overlaySeg.isChecked() self.ui.figure2.canvas.ax.clear() self.ui.figure2.canvas.ax.imshow(self.img2,cmap=plt.cm.gray) #print self.autoGrayFlag if self.autoGrayFlag == 1: graylowlevel,grayhighlevel = self.ui.figure2.canvas.ax.imshow(self.img2,cmap=plt.cm.gray).get_clim() self.ui.grayLow.setValue((graylowlevel)) self.ui.grayHigh.setValue((grayhighlevel)) self.ui.figure2.canvas.ax.imshow(self.img2,cmap=plt.cm.gray).set_clim(self.ui.grayLow.value(),self.ui.grayHigh.value()) #self.ui.figure2.canvas.ax.set_aspect('equal') self.ui.figure2.canvas.ax.get_xaxis().set_visible(False) self.ui.figure2.canvas.ax.get_yaxis().set_visible(False) #self.ui.figure2.canvas.ax.set_title(str(os.path.basename(str(self.getFileNAME))), color = 'white') if overlayFlag == True: self.colormap1 = mpl.colors.LinearSegmentedColormap.from_list('mycmap',[(0,0,0,0),(1,0,0,0.45)]) self.ui.figure2.canvas.ax.hold(True) self.ui.figure2.canvas.ax.imshow(self.segImg[:,:,self.z],cmap = self.colormap1) self.ui.figure2.canvas.draw() def onclickWidget2(self, event): colormap1 = mpl.colors.LinearSegmentedColormap.from_list('mycmap',[(0,0,0,0),(1,0,0,0.45)]) #self.ui.figure2.canvas.ax.set_title(str(int(event.xdata))+','+str(int(event.ydata))+','+str(int(self.img2[np.round(event.ydata),np.round(event.xdata)])), color='green') self.coordXPoint = event.xdata self.coordYPoint = event.ydata self.ui.figure3.canvas.ax.clear() self.ui.figure3.canvas.ax.imshow(np.rot90((self.img_data2[:,round(event.xdata),:]),0),cmap=plt.cm.gray) #self.ui.figure3.canvas.ax.set_aspect('auto') #had these in before self.ui.figure3.canvas.ax.get_xaxis().set_visible(False) self.ui.figure3.canvas.ax.get_yaxis().set_visible(False) #self.ui.figure3.canvas.ax.set_title('', color = 'red') self.ui.figure3.canvas.draw() self.ui.figure4.canvas.ax.clear() self.ui.figure4.canvas.ax.imshow(np.rot90((self.img_data2[round(event.ydata),:,:]),1),cmap=plt.cm.gray) #self.ui.figure4.canvas.ax.set_aspect('auto') #had these in before self.ui.figure4.canvas.ax.get_xaxis().set_visible(False) self.ui.figure4.canvas.ax.get_yaxis().set_visible(False) #self.ui.figure4.canvas.ax.set_title('', color = 'blue') self.ui.figure4.canvas.draw() if self.ui.overlaySeg.isChecked() == True: self.ui.figure2.canvas.ax.hold(True) sizeV = int(self.ui.brushSize.value()) sizeZ = 1#int(sizeV/2) row = int(event.ydata) col = int(event.xdata) dep = self.shape[2]-self.z self.overlayImgAX = self.segImg[:,:,self.z] self.overlayImgSAG = np.rot90((self.segImg[:,round(event.xdata),:]),0) self.overlayImgCOR = np.rot90((self.segImg[round(event.ydata),:,:]),1) self.ui.figure3.canvas.ax.hold(True) self.ui.figure3.canvas.ax.imshow(self.overlayImgSAG,cmap = colormap1) #self.ui.figure3.canvas.ax.set_aspect('auto') #had these in before self.ui.figure3.canvas.draw() self.ui.figure4.canvas.ax.hold(True) self.ui.figure4.canvas.ax.imshow(self.overlayImgCOR,cmap = colormap1) #self.ui.figure4.canvas.ax.set_aspect('auto') #had these in before self.ui.figure4.canvas.draw() #self.img1[np.round(event.xdata),np.round(event.ydata)] self.ui.figure2.canvas.draw() def onclickWidget3(self, event): self.ui.figure3.canvas.ax.set_title(str(int(event.xdata))+','+str(int(self.shape[2]-event.ydata+1)), color='green') self.ui.figure3.canvas.draw() if self.ui.volBrushCB.isChecked(): self.ui.figure3.canvas.ax.hold(True) sizeV = int(self.ui.brushSize.value()) sizeZ = 1#int(sizeV/2) row = int(event.ydata) col = int(event.xdata) dep = self.shape[2]-self.z+1 self.overlayImgSAG[row-sizeZ:row+sizeZ,col-sizeV:col+sizeV] = 1 self.ui.figure3.canvas.ax.imshow(self.overlayImgSAG,cmap = self.colormap) #self.ui.figure3.canvas.ax.set_aspect('auto') self.ui.figure3.canvas.draw() self.overlayImgAX[col-sizeV:col+sizeV,self.coordXPoint-sizeV:self.coordXPoint+sizeV] = 1 self.overlayImgCOR[dep-sizeZ:dep+sizeZ,self.coordYPoint-sizeV:self.coordYPoint+sizeV,] = 1 self.ui.figure2.canvas.ax.hold(True) self.ui.figure2.canvas.ax.imshow(self.overlayImgAX,cmap = self.colormap) #self.ui.figure2.canvas.ax.set_aspect('auto') self.ui.figure2.canvas.draw() self.ui.figure4.canvas.ax.hold(True) self.ui.figure4.canvas.ax.imshow(self.overlayImgCOR,cmap = self.colormap) #self.ui.figure4.canvas.ax.set_aspect('auto') self.ui.figure4.canvas.draw() def onclickWidget4(self, event): self.ui.figure4.canvas.ax.set_title(str(int(event.xdata))+','+str(int(self.shape[2]-event.ydata+1)), color='green') self.ui.figure4.canvas.draw() if self.ui.volBrushCB.isChecked(): self.ui.figure3.canvas.ax.hold(True) sizeV = int(self.ui.brushSize.value()) sizeZ = 1#int(sizeV/2) row = int(event.ydata) col = int(event.xdata) dep = self.shape[2]-self.z+1 self.overlayImgCOR[row-sizeZ:row+sizeZ,col-sizeV:col+sizeV] = 1 self.ui.figure4.canvas.ax.imshow(self.overlayImgCOR,cmap = self.colormap) #self.ui.figure4.canvas.ax.set_aspect('auto') self.ui.figure4.canvas.draw() self.overlayImgAX[self.coordYPoint-sizeV:self.coordYPoint+sizeV,col-sizeV:col+sizeV] = 1 self.overlayImgSAG[dep-sizeZ:dep+sizeZ,self.coordXPoint-sizeV:self.coordXPoint+sizeV] = 1 self.ui.figure2.canvas.ax.hold(True) self.ui.figure2.canvas.ax.imshow(self.overlayImgAX,cmap = self.colormap) #self.ui.figure2.canvas.ax.set_aspect('auto') self.ui.figure2.canvas.draw() self.ui.figure3.canvas.ax.hold(True) self.ui.figure3.canvas.ax.imshow(self.overlayImgSAG,cmap = self.colormap) #self.ui.figure3.canvas.ax.set_aspect('auto') self.ui.figure3.canvas.draw() def imhistFunc(self): self.ui.plotHist.canvas.ax.set_title('Histogram',color = 'w', fontsize = '10') self.ui.plotHist.canvas.ax.hist(self.img1.flatten(), 256, range=(0.0,100), fc='gray', ec='r') self.ui.plotHist.canvas.draw() def saveROIFunc(self): #save out segmentation aff = self.affine2 outImage = deepcopy(self.segImg)#np.rot90(np.fliplr(self.segImg),-1) [x_si,y_si,z_si] = np.shape(outImage) #This method works (for fastsegs)... but need more robust #for i in range(0,z_si): # outImage[:,:,i] = np.rot90(self.segImg[:,:,z_si-1-i],-1) #try new method (more robust to header and affine mix-ups) ornt = orx.axcodes2ornt((self.Orx,self.Ory,self.Orz)) refOrnt = orx.axcodes2ornt(('R','S','A')) newOrnt = orx.ornt_transform(refOrnt,ornt) #reversed these outImage= orx.apply_orientation(np.rot90(np.fliplr(outImage),-1),newOrnt) #outImage = orx.apply_orientation(outImage,newOrnt) #outImage = np.rot90(np.fliplr(outImage),-1) new_image = nib.Nifti1Image(outImage,aff) os.chdir(os.path.dirname(str(self.getFileNAME))) self.roiSaveName=QFileDialog.getSaveFileName() #nib.save(new_image,fileNAME[:-7]+'_FASTseg_TK_edit.nii.gz') nib.save(new_image,str(self.roiSaveName)) def scribbleEditFunc(self): if (self.ui.scribble.isChecked()): (row,col,dep) = self.img_data2.shape self.overlayImgAX = np.zeros((row,col)) self.overlayImgSAG = np.zeros((dep,row)) self.overlayImgCOR = np.zeros((dep,col)) self.colormap = mpl.colors.LinearSegmentedColormap.from_list('mycmap',[(0,0,0,0),(0,1,0,0.45)]) self.myPenWidth = 3.0 self.myPenColor = QtCore.Qt.blue self.ui.figure2.canvas.mpl_disconnect(self.clickFlag2) self.__ID1 = self.ui.figure2.canvas.mpl_connect( 'motion_notify_event', self.__scribble_motion_notify_callback) self.__ID2 = self.ui.figure2.canvas.mpl_connect( 'button_press_event', self.__scribble_button_press_callback) self.__ID3 = self.ui.figure2.canvas.mpl_connect( 'button_release_event', self.__scribble_button_release_callback) self.__ID5 = self.ui.figure3.canvas.mpl_connect( 'motion_notify_event', self.__scribble_motion_notify_callback) self.__ID6 = self.ui.figure3.canvas.mpl_connect( 'button_press_event', self.__scribble_button_press_callback) self.__ID7 = self.ui.figure4.canvas.mpl_connect( 'motion_notify_event', self.__scribble_motion_notify_callback) self.__ID8 = self.ui.figure4.canvas.mpl_connect( 'button_press_event', self.__scribble_button_press_callback) else: self.scrolFlag2 = self.ui.figure2.canvas.mpl_connect('scroll_event', self.scrollT2WImage) self.clickFlag2 = self.ui.figure2.canvas.mpl_connect('button_press_event', self.onclickWidget2) self.ui.figure2.canvas.mpl_disconnect(self.__ID1) self.ui.figure2.canvas.mpl_disconnect(self.__ID2) self.ui.figure2.canvas.mpl_disconnect(self.__ID3) self.ui.figure3.canvas.mpl_disconnect(self.__ID5) self.ui.figure3.canvas.mpl_disconnect(self.__ID6) self.ui.figure4.canvas.mpl_disconnect(self.__ID7) self.ui.figure4.canvas.mpl_disconnect(self.__ID8) def __scribble_button_press_callback(self, event): if event.inaxes: self.ax = event.inaxes figure = str(event.canvas)[1:8] x, y = event.xdata, event.ydata if figure == 'figure2': #print 'here' #print str(event.button) if event.button == 1 and event.key != 'f':#QtCore.Qt.LeftButton: self.ui.figure2.canvas.ax.hold(True) sizeV = int(self.ui.brushSize.value()) self.brushSize = sizeV sizeZ = 1#int(sizeV/2) row = int(event.ydata) col = int(event.xdata) dep = self.shape[2]-self.z #this just added self.line = plt.Line2D([x, x], [y, y], color='b',linewidth = self.brushSize*3) self.ax.add_line(self.line) self.ui.figure2.canvas.draw() self.xs = x self.ys = y self.lastx = x self.lasty = y def __scribble_motion_notify_callback(self, event): if event.inaxes: if event.button == 1 and event.key != 'f': row, col = int(event.ydata), int(event.xdata) # this just added self.line.set_data([self.lastx, col], #before just col, col [self.lasty,row]) self.ax.draw_artist(self.line) self.ui.figure2.canvas.blit(self.ax.bbox) #self.ax.bbox #this is old way #self.line = plt.Line2D([self.lastx, col], #before just col, col # [self.lasty,row], # color='b',linewidth = self.brushSize * 3) #self.ax.add_line(self.line) #self.ui.figure2.canvas.draw() #determine number of steps needed numsteps = np.max([np.absolute(int(self.lastx)-col),np.absolute(int(self.lasty)-row)]) self.xs = np.append(self.xs, np.round(np.linspace(int(self.lastx),col,numsteps))) self.ys = np.append(self.ys, np.round(np.linspace(int(self.lasty),row,numsteps))) self.lastx = col self.lasty = row def __scribble_button_release_callback(self, event): #print 'release -1' if event.inaxes: ax = event.inaxes figure = str(event.canvas)[1:8] x, y = event.xdata, event.ydata #print 'release 0' if figure == 'figure2': #print 'release 1' #print event.button #print self.scribbling if event.button == 1 and event.key != 'f': # and self.scribbling: #print 'release 2' self.ui.figure2.canvas.ax.hold(True) sizeV = int(self.brushSize)#int(self.ui.brushSize.value()) sizeZ = 1#int(sizeV/2) row = int(event.ydata) col = int(event.xdata) dep = self.shape[2]-self.z self.xs = np.append(self.xs,col) self.ys = np.append(self.ys,row) #self.xs = np.array(self.xs) #self.ys = np.array(self.ys) #self.xs = self.ax.line.get_xdata() #self.ys = self.ax.line.get_ydata() for iii in range(0,np.shape(self.xs)[0]): self.overlayImgAX[(self.ys[iii])-sizeV:(self.ys[iii])+sizeV,(self.xs[iii])-sizeV:(self.xs[iii])+sizeV] = 1 #self.overlayImgAX[row-sizeV:row+sizeV,col-sizeV:col+sizeV] = 1 self.ui.figure2.canvas.ax.imshow(self.overlayImgAX,cmap = self.colormap) self.ui.figure2.canvas.draw() self.scribbling = False # Recomputes border based on watershed and sobel edge detection technique mgac = self.segImg[:,:,self.z] - self.overlayImgAX if event.key == 'a': mgac = self.segImg[:,:,self.z] + self.overlayImgAX if self.ui.freehand.isChecked()==True: seeds = self.overlayImgAX * 0 seeds[:] = 1 seeds[mgac==1] = 2 seeds[self.overlayImgAX>0] = 0 sobelFilt = sobel(np.array(self.img2.copy(),dtype='int16')) mgac = watershed(sobelFilt,seeds)>1 #below is AC #for ijk123 in xrange(50): # mgac.step() self.holdLastSeg = self.segImg.copy() self.segImg[:,:,self.z] = mgac > 0 self.imshowFunc() (row,col,dep) = self.img_data2.shape self.overlayImgAX = np.zeros((row,col)) if event.button == 1 and event.key == 'f': #this will be flood fill function self.holdLastSeg = self.segImg.copy() #save previous state in case need to undo #first determine if region is 0's or 1's row = int(event.ydata) col = int(event.xdata) regVal = self.segImg[row,col,self.z] #print regVal #if zeroes need to flip image if regVal == 0: mgac = self.segImg[:,:,self.z].copy() * 0 mgac[self.segImg[:,:,self.z]==0] = 1 else: mgac = self.segImg[:,:,self.z].copy() labelSlice,numFeatures = label(mgac) labelPointsVal = labelSlice[row,col] outputFilledImage = self.segImg[:,:,self.z].copy() #if zeroes need to add label image back in if regVal == 0: outputFilledImage[labelSlice==labelPointsVal] = 1 else: outputFilledImage[labelSlice==labelPointsVal] = 0 self.segImg[:,:,self.z] = outputFilledImage > 0 #this will be final after flood fill. self.segImg[0,0,self.z] = 0 #need at least one zero value for overlay (matplotlib bug???) self.imshowFunc() (row,col,dep) = self.img_data2.shape self.overlayImgAX = np.zeros((row,col)) def __motion_notify_callback(self, event): if event.inaxes: ax = event.inaxes figure = str(event.canvas)[1:8] x, y = event.xdata, event.ydata if figure == 'figure2': if (event.button == None or event.button == 1) and self.line != None: # Move line around self.line.set_data([self.previous_point[0], x], [self.previous_point[1], y]) self.ui.figure2.canvas.draw() elif figure == 'figure3': if (event.button == None or event.button == 1) and self.line3 != None: # Move line around self.line3.set_data([self.previous_point3[0], x], [self.previous_point3[1], y]) self.ui.figure3.canvas.draw() elif figure == 'figure4': if (event.button == None or event.button == 1) and self.line4 != None: # Move line around self.line4.set_data([self.previous_point4[0], x], [self.previous_point4[1], y]) self.ui.figure4.canvas.draw() def __button_press_callback(self, event): if event.inaxes: x, y = event.xdata, event.ydata ax = event.inaxes figure = str(event.canvas)[1:8] if figure == 'figure2': if event.button == 1 and event.dblclick == False: # If you press the left button, single click if self.line == None: # if there is no line, create a line self.line = plt.Line2D([x, x], [y, y], marker='o', color=self.roicolor) self.start_point = [x,y] self.previous_point = self.start_point self.allxpoints=[x] self.allypoints=[y] ax.add_line(self.line) #self.ui.figure1.canvas.draw() self.ui.figure2.canvas.draw() # add a segment else: # if there is a line, create a segment self.line = plt.Line2D([self.previous_point[0], x], [self.previous_point[1], y], marker = 'o',color=self.roicolor) self.previous_point = [x,y] self.allxpoints.append(x) self.allypoints.append(y) event.inaxes.add_line(self.line) #self.ui.figure1.canvas.draw() elif ((event.button == 1 and event.dblclick==True) or (event.button == 3 and event.dblclick==False)) and self.line != None: # close the loop and disconnect #self.ui.figure1.canvas.mpl_disconnect(self.__ID1) #joerg #self.ui.figure1.canvas.mpl_disconnect(self.__ID2) #joerg self.ui.figure2.canvas.mpl_disconnect(self.__ID1) #joerg self.ui.figure2.canvas.mpl_disconnect(self.__ID2) #joerg self.line.set_data([self.previous_point[0], self.start_point[0]], [self.previous_point[1], self.start_point[1]]) ax.add_line(self.line) self.ui.figure2.canvas.draw() #self.ui.figure1.canvas.draw() self.line = None elif figure == 'figure3': if event.button == 1 and event.dblclick == False: # If you press the left button, single click if self.line3 == None: # if there is no line, create a line self.line3 = plt.Line2D([x, x], [y, y], marker='o', color=self.roicolor3) self.start_point3 = [x,y] self.previous_point3 = self.start_point3 self.allxpoints3=[x] self.allypoints3=[y] ax.add_line(self.line3) self.ui.figure3.canvas.draw() # add a segment else: # if there is a line, create a segment self.line3 = plt.Line2D([self.previous_point3[0], x], [self.previous_point3[1], y], marker = 'o',color=self.roicolor3) self.previous_point3 = [x,y] self.allxpoints3.append(x) self.allypoints3.append(y) event.inaxes.add_line(self.line3) self.ui.figure3.canvas.draw() elif ((event.button == 1 and event.dblclick==True) or (event.button == 3 and event.dblclick==False)) and self.line3 != None: # close the loop and disconnect self.ui.figure3.canvas.mpl_disconnect(self.__ID5) #joerg self.ui.figure3.canvas.mpl_disconnect(self.__ID6) #joerg self.line3.set_data([self.previous_point3[0], self.start_point3[0]], [self.previous_point3[1], self.start_point3[1]]) ax.add_line(self.line3) self.ui.figure3.canvas.draw() self.line3 = None # self.allypoints3 = self.shape[2] - self.allypoints3 elif figure == 'figure4': if event.button == 1 and event.dblclick == False: # If you press the left button, single click if self.line4 == None: # if there is no line, create a line self.line4 = plt.Line2D([x, x], [y, y], marker='o', color=self.roicolor4) self.start_point4 = [x,y] self.previous_point4 = self.start_point4 self.allxpoints4=[x] self.allypoints4=[y] ax.add_line(self.line4) self.ui.figure4.canvas.draw() # add a segment else: # if there is a line, create a segment self.line4 = plt.Line2D([self.previous_point4[0], x], [self.previous_point4[1], y], marker = 'o',color=self.roicolor4) self.previous_point4 = [x,y] self.allxpoints4.append(x) self.allypoints4.append(y) event.inaxes.add_line(self.line4) self.ui.figure4.canvas.draw() elif ((event.button == 1 and event.dblclick==True) or (event.button == 3 and event.dblclick==False)) and self.line4 != None: # close the loop and disconnect self.ui.figure4.canvas.mpl_disconnect(self.__ID5) #joerg self.ui.figure4.canvas.mpl_disconnect(self.__ID6) #joerg self.line4.set_data([self.previous_point4[0], self.start_point4[0]], [self.previous_point4[1], self.start_point4[1]]) ax.add_line(self.line4) self.ui.figure4.canvas.draw() self.line4 = None # self.allypoints4 = self.shape[2] - self.allypoints4 # if sys.flags.interactive: # pass # else: # #figure has to be closed so that code can continue # plt.close(self.fig) def drawLineTo(self, endPoint): painter = QtGui.QPainter(self.image) painter.setPen(QtGui.QPen(self.myPenColor, self.myPenWidth, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)) painter.drawLine(self.lastPoint, endPoint) self.modified = True # rad = self.myPenWidth / 2 + 2 # self.update(QtCore.QRect(self.lastPoint, endPoint).normalized().adjusted(-rad, -rad, +rad, +rad)) self.update() self.lastPoint = QtCore.QPoint(endPoint)