def qc_background_regions(intensity_imp, bg_rois): """allow the user to view and correct automatically-determined background regions""" imp = Duplicator().run(intensity_imp); imp.setTitle("Background region QC"); imp.show(); imp.setPosition(1); autoset_zoom(imp); imp.setRoi(bg_rois[0]); IJ.setTool("freehand"); notOK = True; while notOK: listener = UpdateRoiImageListener(bg_rois, is_area=True); imp.addImageListener(listener); dialog = NonBlockingGenericDialog("Background region quality control"); dialog.enableYesNoCancel("Continue", "Use this region for all t"); dialog.setCancelLabel("Cancel analysis"); dialog.addMessage("Please redraw background regions as necessary...") dialog.showDialog(); if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled"); elif not(dialog.wasOKed()): this_roi = imp.getRoi(); bg_rois = [this_roi for _ in listener.getRoiList()]; imp.removeImageListener(listener); else: last_roi = imp.getRoi(); qcd_bg_rois = listener.getRoiList(); if imp.getNFrames() > imp.getNSlices(): qcd_bg_rois[imp.getT() - 1] = last_roi; else: qcd_bg_rois[imp.getZ() - 1] = last_roi; notOK = False; imp.removeImageListener(listener); imp.changes = False; imp.close(); return qcd_bg_rois;
def runOneFile(fullFilePath): global gNumChannels global gAlignBatchVersion if not os.path.isfile(fullFilePath): bPrintLog( '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n', 0) return 0 bPrintLog( time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1) enclosingPath = os.path.dirname(fullFilePath) head, tail = os.path.split(enclosingPath) enclosingPath += '/' #make output folders destFolder = enclosingPath + tail + '_channels/' if not os.path.isdir(destFolder): os.makedirs(destFolder) destMaxFolder = destFolder + 'max/' if not os.path.isdir(destMaxFolder): os.makedirs(destMaxFolder) if gDoAlign: destAlignmentFolder = destFolder + 'alignment/' if not os.path.isdir(destAlignmentFolder): os.makedirs(destAlignmentFolder) if gSave8bit: eightBitFolder = destFolder + 'channels8/' if not os.path.isdir(eightBitFolder): os.makedirs(eightBitFolder) eightBitMaxFolder = eightBitFolder + 'max/' if not os.path.isdir(eightBitMaxFolder): os.makedirs(eightBitMaxFolder) # open image imp = Opener().openImage(fullFilePath) # get parameters of image (width, height, nChannels, nSlices, nFrames) = imp.getDimensions() bitDepth = imp.getBitDepth() infoStr = imp.getProperty("Info") #get all .tif tags if not infoStr: infoStr = '' infoStr += 'bAlignBatch_Version=' + str(gAlignBatchVersion) + '\n' infoStr += 'bAlignBatch_Time=' + time.strftime( "%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n' msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \ + ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth) bPrintLog(msgStr, 1) path, filename = os.path.split(fullFilePath) shortName, fileExtension = os.path.splitext(filename) # # look for num channels in ScanImage infoStr if gGetNumChanFromScanImage: for line in infoStr.split('\n'): #scanimage.SI4.channelsSave = [1;2] scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0 #state.acq.numberOfChannelsSave=2 scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0 if scanimage3: #print 'line:', line equalIdx = find(line, '=') line2 = line[equalIdx + 1:] if gGetNumChanFromScanImage: gNumChannels = int(line2) bPrintLog( 'over-riding gNumChannels with: ' + str(gNumChannels), 2) if scanimage4: #print ' we have a scanimage 4 file ... now i need to exptract the number of channel' #print 'line:', line equalIdx = find(line, '=') line2 = line[equalIdx + 1:] for delim in ';[]': line2 = line2.replace(delim, ' ') if gGetNumChanFromScanImage: gNumChannels = len(line2.split()) bPrintLog( 'over-riding gNumChannels with: ' + str(gNumChannels), 2) # show imp.show() # split channels if necc. and grab the original window names if gNumChannels == 1: origImpWinStr = imp.getTitle() #use this when only one channel origImpWin = WindowManager.getWindow( origImpWinStr) #returns java.awt.Window if gNumChannels == 2: winTitle = imp.getTitle() bPrintLog('Deinterleaving 2 channels...', 1) IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost origCh1WinStr = winTitle + ' #1' origCh2WinStr = winTitle + ' #2' origCh1Imp = WindowManager.getImage(origCh1WinStr) origCh2Imp = WindowManager.getImage(origCh2WinStr) origCh1File = destFolder + shortName + '_ch1.tif' origCh2File = destFolder + shortName + '_ch2.tif' # work on a copy, mostly for alignment with cropping copy = Duplicator().run(imp) #copy.copyAttributes(imp) #don't copy attributes, it copies the name (which we do not want) copy.show() # # crop (on copy) if gDoCrop: bPrintLog('making cropping rectangle (left,top,width,height) ', 1) bPrintLog( str(gCropLeft) + ' ' + str(gCropTop) + ' ' + str(gCropWidth) + ' ' + str(gCropHeight), 2) roi = Roi(gCropLeft, gCropTop, gCropWidth, gCropHeight) #left,top,width,height copy.setRoi(roi) time.sleep( 0.5 ) # otherwise, crop SOMETIMES failes. WHAT THE F**K FIJI DEVELOPERS, REALLY, WHAT THE F**K #bPrintLog('cropping', 1) IJ.run('Crop') infoStr += 'bCropping=' + str(gCropLeft) + ',' + str( gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n' # # remove calibration ( on original) if gRemoveCalibration: cal = imp.getCalibration() calCoeff = cal.getCoefficients() if calCoeff: msgStr = 'Calibration is y=a+bx' + ' a=' + str( calCoeff[0]) + ' b=' + str(calCoeff[1]) bPrintLog(msgStr, 1) #remove calibration bPrintLog('\tRemoving Calibration', 2) imp.setCalibration(None) #without these, 8-bit conversion goes to all 0 !!! what the f**k !!! #bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2) imp.resetStack() imp.resetDisplayRange() #get and print out min/max origMin = StackStatistics(imp).min origMax = StackStatistics(imp).max msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax) bPrintLog(msgStr, 2) # 20150723, 'shift everybody over by linear calibration intercept calCoeff[0] - (magic number) if 1: # [1] was this #msgStr = 'Subtracting original min '+str(origMin) + ' from stack.' #bPrintLog(msgStr, 2) #subArgVal = 'value=%s stack' % (origMin,) #IJ.run('Subtract...', subArgVal) # [2] now this #msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.' #bPrintLog(msgStr, 2) #addArgVal = 'value=%s stack' % (int(calCoeff[0]),) #IJ.run('Add...', addArgVal) # [3] subtract a magic number 2^15-2^7 = 32768 - 128 magicNumber = gLinearShift #2^15 - 128 msgStr = 'Subtracting a magic number (linear shift) ' + str( magicNumber) + ' from stack.' bPrintLog(msgStr, 2) infoStr += 'bLinearShift=' + str(gLinearShift) + '\n' subArgVal = 'value=%s stack' % (gLinearShift, ) IJ.run(imp, 'Subtract...', subArgVal) # 20150701, set any pixel <0 to 0 if 0: ip = imp.getProcessor() # returns a reference pixels = ip.getPixels() # returns a reference msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...' bPrintLog(msgStr, 2) pixels = map(lambda x: 0 if x < 0 else x, pixels) bPrintLog('\t\t... done', 2) #get and print out min/max newMin = StackStatistics(imp).min newMax = StackStatistics(imp).max msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax) bPrintLog(msgStr, 2) #append calibration to info string infoStr += 'bCalibCoeff_a = ' + str(calCoeff[0]) + '\n' infoStr += 'bCalibCoeff_b = ' + str(calCoeff[1]) + '\n' infoStr += 'bNewMin = ' + str(newMin) + '\n' infoStr += 'bNewMax = ' + str(newMax) + '\n' # # set up if gNumChannels == 1: impWinStr = copy.getTitle() #use this when only one channel impWin = WindowManager.getWindow(impWinStr) #returns java.awt.Window if gNumChannels == 2: winTitle = copy.getTitle() bPrintLog('Deinterleaving 2 channels...', 1) IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost ch1WinStr = winTitle + ' #1' ch2WinStr = winTitle + ' #2' ch1Imp = WindowManager.getImage(ch1WinStr) ch2Imp = WindowManager.getImage(ch2WinStr) ch1File = destFolder + shortName + '_ch1.tif' ch2File = destFolder + shortName + '_ch2.tif' # # alignment if gDoAlign and gNumChannels == 1 and copy.getNSlices() > 1: infoStr += 'AlignOnChannel=1' + '\n' #snap to middle slice if gAlignOnMiddleSlice: middleSlice = int( math.floor(copy.getNSlices() / 2)) #int() is necc., python is f*****g picky else: middleSlice = gAlignOnThisSlice copy.setSlice(middleSlice) transformationFile = destAlignmentFolder + shortName + '.txt' bPrintLog('MultiStackReg aligning:' + impWinStr, 1) stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % ( impWin, transformationFile) IJ.run('MultiStackReg', stackRegParams) infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n' #20150723, we just aligned on a cropped copy, apply alignment to original imp origImpTitle = imp.getTitle() stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origImpTitle, transformationFile) IJ.run('MultiStackReg', stackRegParams) if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices( ) > 1 and ch2Imp.getNSlices() > 1: #apply to gAlignThisChannel alignThisWindow = '' applyAlignmentToThisWindow = '' if gAlignThisChannel == 1: infoStr += 'AlignOnChannel=1' + '\n' transformationFile = destAlignmentFolder + shortName + '_ch1.txt' alignThisWindow = ch1WinStr applyAlignmentToThisWindow = ch2WinStr else: infoStr += 'AlignOnChannel=2' + '\n' transformationFile = destAlignmentFolder + shortName + '_ch2.txt' alignThisWindow = ch2WinStr applyAlignmentToThisWindow = ch1WinStr alignThisImp = WindowManager.getImage(alignThisWindow) #snap to middle slice if gAlignOnMiddleSlice: middleSlice = int( math.floor(alignThisImp.getNSlices() / 2)) #int() is necc., python is f*****g picky else: middleSlice = gAlignOnThisSlice alignThisImp.setSlice(middleSlice) infoStr += 'bAlignOnSlice=' + str(middleSlice) + '\n' bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1) stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % ( alignThisWindow, transformationFile) IJ.run('MultiStackReg', stackRegParams) # 20150723, we just aligned on a copy, apply alignment to both channels of original # ch1 bPrintLog('MultiStackReg applying alignment to:' + origCh1WinStr, 1) stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origCh1WinStr, transformationFile) IJ.run('MultiStackReg', stackRegParams) # ch2 bPrintLog('MultiStackReg applying alignment to:' + origCh2WinStr, 1) stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origCh2WinStr, transformationFile) IJ.run('MultiStackReg', stackRegParams) #apply alignment to other window #bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1) #applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow) #stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile) #IJ.run('MultiStackReg', stackRegParams) elif gDoAlign: bPrintLog('Skipping alignment, there may be only one slice?', 3) # # save if gNumChannels == 1: imp.setProperty("Info", infoStr) impFile = destFolder + shortName + '.tif' #bPrintLog('Saving:' + impFile, 1) bSaveStack(imp, impFile) #max project bSaveZProject(imp, destMaxFolder, shortName) if gNumChannels == 2: #ch1 origCh1Imp.setProperty("Info", infoStr) #bPrintLog('Saving:' + ch1File, 1) bSaveStack(origCh1Imp, ch1File) #max project bSaveZProject(origCh1Imp, destMaxFolder, shortName + '_ch1') #ch2 origCh2Imp.setProperty("Info", infoStr) #bPrintLog('Saving:' + ch2File, 1) bSaveStack(origCh2Imp, ch2File) #max project bSaveZProject(origCh2Imp, destMaxFolder, shortName + '_ch2') # # post convert to 8-bit and save if gSave8bit: if bitDepth == 16: if gNumChannels == 1: bPrintLog('Converting to 8-bit:' + impWinStr, 1) IJ.selectWindow(impWinStr) #IJ.run('resetMinAndMax()') IJ.run("8-bit") impFile = eightBitFolder + shortName + '.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(imp, impFile) #max project bSaveZProject(imp, eightBitMaxFolder, shortName) if gNumChannels == 2: # bPrintLog('Converting to 8-bit:' + origCh1WinStr, 1) IJ.selectWindow(origCh1WinStr) IJ.run("8-bit") impFile = eightBitFolder + shortName + '_ch1.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(origCh1Imp, impFile) #max project bSaveZProject(origCh1Imp, eightBitMaxFolder, shortName + '_ch1') # bPrintLog('Converting to 8-bit:' + origCh2WinStr, 1) IJ.selectWindow(origCh2WinStr) #IJ.run('resetMinAndMax()') IJ.run("8-bit") impFile = eightBitFolder + shortName + '_ch2.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(origCh2Imp, impFile) #max project bSaveZProject(origCh2Imp, eightBitMaxFolder, shortName + '_ch2') # # close original window imp.changes = 0 imp.close() #copy copy.changes = 0 copy.close() # # close ch1/ch2 if gNumChannels == 2: #original origCh1Imp.changes = 0 origCh1Imp.close() origCh2Imp.changes = 0 origCh2Imp.close() #copy ch1Imp.changes = 0 ch1Imp.close() ch2Imp.changes = 0 ch2Imp.close() bPrintLog( time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
def runOneFile(fullFilePath): global gFileType global gNumChannels global gAlignBatchVersion if not os.path.isfile(fullFilePath): bPrintLog('\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',0) return 0 bPrintLog(time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1) enclosingPath = os.path.dirname(fullFilePath) head, tail = os.path.split(enclosingPath) enclosingPath += '/' #make output folders destFolder = enclosingPath + tail + '_channels/' if not os.path.isdir(destFolder): os.makedirs(destFolder) destMaxFolder = destFolder + 'max/' if not os.path.isdir(destMaxFolder): os.makedirs(destMaxFolder) if gDoAlign: destAlignmentFolder = destFolder + 'alignment/' if not os.path.isdir(destAlignmentFolder): os.makedirs(destAlignmentFolder) if gSave8bit: eightBitFolder = destFolder + 'channels8/' if not os.path.isdir(eightBitFolder): os.makedirs(eightBitFolder) eightBitMaxFolder = eightBitFolder + 'max/' if not os.path.isdir(eightBitMaxFolder): os.makedirs(eightBitMaxFolder) if gFileType=='tif': # open .tif image imp = Opener().openImage(fullFilePath) else: # open .lsm cmdStr = 'open=%s autoscale color_mode=Default view=Hyperstack stack_order=XYCZT' % (fullFilePath,) IJ.run('Bio-Formats Importer', cmdStr) lsmpath, lsmfilename = os.path.split(fullFilePath) lsWindow = lsmfilename imp = WindowManager.getImage(lsWindow) # get parameters of image (width, height, nChannels, nSlices, nFrames) = imp.getDimensions() bitDepth = imp.getBitDepth() infoStr = imp.getProperty("Info") #get all .tif tags if not infoStr: infoStr = '' infoStr += 'bAlignBatch_Version=' + str(gAlignBatchVersion) + '\n' infoStr += 'bAlignBatch_Time=' + time.strftime("%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n' msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \ + ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth) bPrintLog(msgStr, 1) path, filename = os.path.split(fullFilePath) shortName, fileExtension = os.path.splitext(filename) # # look for num channels in ScanImage infoStr if gGetNumChanFromScanImage: for line in infoStr.split('\n'): #scanimage.SI4.channelsSave = [1;2] scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0 #state.acq.numberOfChannelsSave=2 scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0 if scanimage3: #print 'line:', line equalIdx = find(line, '=') line2 = line[equalIdx+1:] if gGetNumChanFromScanImage: gNumChannels = int(line2) bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2) if scanimage4: #print ' we have a scanimage 4 file ... now i need to exptract the number of channel' #print 'line:', line equalIdx = find(line, '=') line2 = line[equalIdx+1:] for delim in ';[]': line2 = line2.replace(delim, ' ') if gGetNumChanFromScanImage: gNumChannels = len(line2.split()) bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2) # show imp.show() # split channels if necc. and grab the original window names if gNumChannels == 1: origImpWinStr = imp.getTitle() #use this when only one channel origImpWin = WindowManager.getWindow(origImpWinStr) #returns java.awt.Window if gNumChannels == 2: winTitle = imp.getTitle() bPrintLog('Deinterleaving 2 channels...', 1) IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost origCh1WinStr = winTitle + ' #1' origCh2WinStr = winTitle + ' #2' origCh1Imp = WindowManager.getImage(origCh1WinStr) origCh2Imp = WindowManager.getImage(origCh2WinStr) origCh1File = destFolder + shortName + '_ch1.tif' origCh2File = destFolder + shortName + '_ch2.tif' # work on a copy, mostly for alignment with cropping copy = Duplicator().run(imp) #copy.copyAttributes(imp) #don't copy attributes, it copies the name (which we do not want) copy.show() # # crop (on copy) if gDoCrop: bPrintLog('making cropping rectangle (left,top,width,height) ',1) bPrintLog(str(gCropLeft) + ' ' + str(gCropTop) + ' ' +str(gCropWidth) + ' ' +str(gCropHeight), 2) roi = Roi(gCropLeft, gCropTop, gCropWidth, gCropHeight) #left,top,width,height copy.setRoi(roi) time.sleep(0.5) # otherwise, crop SOMETIMES failes. WHAT THE F**K FIJI DEVELOPERS, REALLY, WHAT THE F**K #bPrintLog('cropping', 1) IJ.run('Crop') infoStr += 'bCropping=' + str(gCropLeft) + ',' + str(gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n' # # remove calibration ( on original) if gRemoveCalibration: cal = imp.getCalibration() calCoeff = cal.getCoefficients() if calCoeff: msgStr = 'Calibration is y=a+bx' + ' a=' + str(calCoeff[0]) + ' b=' + str(calCoeff[1]) bPrintLog(msgStr, 1) #remove calibration bPrintLog('\tRemoving Calibration', 2) imp.setCalibration(None) #without these, 8-bit conversion goes to all 0 !!! what the f**k !!! #bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2) imp.resetStack() imp.resetDisplayRange() #get and print out min/max origMin = StackStatistics(imp).min origMax = StackStatistics(imp).max msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax) bPrintLog(msgStr, 2) # 20150723, 'shift everybody over by linear calibration intercept calCoeff[0] - (magic number) if 1: # [1] was this #msgStr = 'Subtracting original min '+str(origMin) + ' from stack.' #bPrintLog(msgStr, 2) #subArgVal = 'value=%s stack' % (origMin,) #IJ.run('Subtract...', subArgVal) # [2] now this #msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.' #bPrintLog(msgStr, 2) #addArgVal = 'value=%s stack' % (int(calCoeff[0]),) #IJ.run('Add...', addArgVal) # [3] subtract a magic number 2^15-2^7 = 32768 - 128 magicNumber = gLinearShift #2^15 - 128 msgStr = 'Subtracting a magic number (linear shift) '+str(magicNumber) + ' from stack.' bPrintLog(msgStr, 2) infoStr += 'bLinearShift=' + str(gLinearShift) + '\n' subArgVal = 'value=%s stack' % (gLinearShift,) IJ.run(imp, 'Subtract...', subArgVal) # 20150701, set any pixel <0 to 0 if 0: ip = imp.getProcessor() # returns a reference pixels = ip.getPixels() # returns a reference msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...' bPrintLog(msgStr, 2) pixels = map(lambda x: 0 if x<0 else x, pixels) bPrintLog('\t\t... done', 2) #get and print out min/max newMin = StackStatistics(imp).min newMax = StackStatistics(imp).max msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax) bPrintLog(msgStr, 2) #append calibration to info string infoStr += 'bCalibCoeff_a = ' + str(calCoeff[0]) + '\n' infoStr += 'bCalibCoeff_b = ' + str(calCoeff[1]) + '\n' infoStr += 'bNewMin = ' + str(newMin) + '\n' infoStr += 'bNewMax = ' + str(newMax) + '\n' # # set up if gNumChannels == 1: impWinStr = copy.getTitle() #use this when only one channel impWin = WindowManager.getWindow(impWinStr) #returns java.awt.Window if gNumChannels == 2: winTitle = copy.getTitle() bPrintLog('Deinterleaving 2 channels...', 1) IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost ch1WinStr = winTitle + ' #1' ch2WinStr = winTitle + ' #2' ch1Imp = WindowManager.getImage(ch1WinStr) ch2Imp = WindowManager.getImage(ch2WinStr) ch1File = destFolder + shortName + '_ch1.tif' ch2File = destFolder + shortName + '_ch2.tif' # # alignment if gDoAlign and gNumChannels == 1 and copy.getNSlices()>1: infoStr += 'AlignOnChannel=1' + '\n' #snap to middle slice if gAlignOnMiddleSlice: middleSlice = int(math.floor(copy.getNSlices() / 2)) #int() is necc., python is f*****g picky else: middleSlice = gAlignOnThisSlice copy.setSlice(middleSlice) transformationFile = destAlignmentFolder + shortName + '.txt' bPrintLog('MultiStackReg aligning:' + impWinStr, 1) stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(impWin,transformationFile) IJ.run('MultiStackReg', stackRegParams) infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n' #20150723, we just aligned on a cropped copy, apply alignment to original imp origImpTitle = imp.getTitle() stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origImpTitle,transformationFile) IJ.run('MultiStackReg', stackRegParams) if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices()>1 and ch2Imp.getNSlices()>1: #apply to gAlignThisChannel alignThisWindow = '' applyAlignmentToThisWindow = '' if gAlignThisChannel == 1: infoStr += 'AlignOnChannel=1' + '\n' transformationFile = destAlignmentFolder + shortName + '_ch1.txt' alignThisWindow = ch1WinStr applyAlignmentToThisWindow = ch2WinStr else: infoStr += 'AlignOnChannel=2' + '\n' transformationFile = destAlignmentFolder + shortName + '_ch2.txt' alignThisWindow = ch2WinStr applyAlignmentToThisWindow = ch1WinStr alignThisImp = WindowManager.getImage(alignThisWindow) #snap to middle slice if gAlignOnMiddleSlice: middleSlice = int(math.floor(alignThisImp.getNSlices() / 2)) #int() is necc., python is f*****g picky else: middleSlice = gAlignOnThisSlice alignThisImp.setSlice(middleSlice) infoStr += 'bAlignOnSlice=' + str(middleSlice) + '\n' bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1) stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(alignThisWindow,transformationFile) IJ.run('MultiStackReg', stackRegParams) # 20150723, we just aligned on a copy, apply alignment to both channels of original # ch1 bPrintLog('MultiStackReg applying alignment to:' + origCh1WinStr, 1) stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origCh1WinStr,transformationFile) IJ.run('MultiStackReg', stackRegParams) # ch2 bPrintLog('MultiStackReg applying alignment to:' + origCh2WinStr, 1) stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origCh2WinStr,transformationFile) IJ.run('MultiStackReg', stackRegParams) #apply alignment to other window #bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1) #applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow) #stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile) #IJ.run('MultiStackReg', stackRegParams) elif gDoAlign: bPrintLog('Skipping alignment, there may be only one slice?',3) # # save if gNumChannels == 1: imp.setProperty("Info", infoStr); impFile = destFolder + shortName + '.tif' #bPrintLog('Saving:' + impFile, 1) bSaveStack(imp, impFile) #max project bSaveZProject(imp, destMaxFolder, shortName) if gNumChannels == 2: #ch1 origCh1Imp.setProperty("Info", infoStr); #bPrintLog('Saving:' + ch1File, 1) bSaveStack(origCh1Imp, ch1File) #max project bSaveZProject(origCh1Imp, destMaxFolder, shortName+'_ch1') #ch2 origCh2Imp.setProperty("Info", infoStr); #bPrintLog('Saving:' + ch2File, 1) bSaveStack(origCh2Imp, ch2File) #max project bSaveZProject(origCh2Imp, destMaxFolder, shortName+'_ch2') # # post convert to 8-bit and save if gSave8bit: if bitDepth == 16: if gNumChannels == 1: bPrintLog('Converting to 8-bit:' + impWinStr, 1) IJ.selectWindow(impWinStr) #IJ.run('resetMinAndMax()') IJ.run("8-bit") impFile = eightBitFolder + shortName + '.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(imp, impFile) #max project bSaveZProject(imp, eightBitMaxFolder, shortName) if gNumChannels == 2: # bPrintLog('Converting to 8-bit:' + origCh1WinStr, 1) IJ.selectWindow(origCh1WinStr) IJ.run("8-bit") impFile = eightBitFolder + shortName + '_ch1.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(origCh1Imp, impFile) #max project bSaveZProject(origCh1Imp, eightBitMaxFolder, shortName+'_ch1') # bPrintLog('Converting to 8-bit:' + origCh2WinStr, 1) IJ.selectWindow(origCh2WinStr) #IJ.run('resetMinAndMax()') IJ.run("8-bit") impFile = eightBitFolder + shortName + '_ch2.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(origCh2Imp, impFile) #max project bSaveZProject(origCh2Imp, eightBitMaxFolder, shortName+'_ch2') # # close original window imp.changes = 0 imp.close() #copy copy.changes = 0 copy.close() # # close ch1/ch2 if gNumChannels == 2: #original origCh1Imp.changes = 0 origCh1Imp.close() origCh2Imp.changes = 0 origCh2Imp.close() #copy ch1Imp.changes = 0 ch1Imp.close() ch2Imp.changes = 0 ch2Imp.close() bPrintLog(time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
def process(dirIn, dirOut, expName, ps, pe, ts, te): jobid = commands.getoutput("echo $PBS_JOBID").split('.')[0] jobid = jobid.replace("[","_").replace("]","") # because the jobids look like 2356385[1] which causes problems print "job id: "+jobid jobdir = os.path.join("/tmp",str(jobid)+"_fiji") print "job dir: "+jobdir for p in range(ps,pe+1): pID = str(p); for t in range(ts,te+1): print "TIMEPOINT STARTING ***************" tID = "t"+str(t); print "time-point: "+tID; if os.path.isdir(jobdir): print "removing "+jobdir shutil.rmtree(jobdir) print "creating "+jobdir os.mkdir(jobdir) if stitching: fileOut = "rescaled_flipped_"; for z in range(zs,ze+1): zID = "z"+str(z); print "z-plane: "+zID; if bandpass: IJ.log("bandpass....") # load all images from same time point and same z-position fileID = expName+pID+"_b0"+tID+zID+"m.*"; IJ.log("opening images: "+os.path.join(dirIn,fileID)) IJ.run("Image Sequence...", "open=["+dirIn+"] starting=1 increment=1 scale=100 file=[] or=["+fileID+"] sort"); #selectWindow("im-2012-0007_Position35.tif_Files"); imp = IJ.getImage(); #imp.show(); imp.setTitle("Stack"); # illumination correction IJ.log("computing FFT..."); # run("Flip Horizontally", "stack"); impFFT = Duplicator().run(imp); for i in range(1, impFFT.getNSlices()+1): print "FFT of slice "+str(i) impFFT.setSlice(i) IJ.run(impFFT, "Bandpass Filter...", "filter_large=10000 filter_small=200 suppress=None tolerance=5 "); #impFFT.show() #stats = imp.getStatistics(Measurements.MEAN) #IJ.log("stats.mean = "+str(stats.mean)); # this is only the mean of one slice...is this a problem? print "dividing image stack by FFT stack..."; ic = ImageCalculator() impCorr = ic.run("Divide create 32-bit stack", imp, impFFT); #impCorr.show() def computeMean(pixels): return sum(pixels) / float(len(pixels)) print "multiplying each image by 128/mean for going back to 8 bit space..." stack = impCorr.getStack() for i in range(1, impCorr.getNSlices()+1): ip = stack.getProcessor(i).convertToFloat() mean = computeMean(ip.getPixels()) print "multiplying slice "+str(i)+" by "+str(float(128/mean)) ip.multiply(float(128/mean)) IJ.log("converting from 32-bit to 8-bit...") IJ.setMinAndMax(impCorr, 0, 255); IJ.run(impCorr,"8-bit",""); #IJ.saveAs(impCorr, "Tiff", "/Users/tischi/Documents/processed.tif"); #ff #impCorr.show() # save images IJ.log("saving bandpass corrected image sequence: "+os.path.join(jobdir,fileOut)) IJ.run(impCorr, "Image Sequence... ", "format=TIFF name=["+fileOut+"] start=1 digits=4 save=["+jobdir+"]"); if check: IJ.run(impCorr, "Image Sequence... ", "format=TIFF name=["+fileOut+"] start=1 digits=4 save=["+dirOut+"]"); #impCorr.close(); imp.close(); impFFT.hide(); # stitching IJ.log("STITCHING START **********") layoutFile = copyStitchingLayoutFile(dirIn,expName,jobdir,ps) ###layoutFile = makeStitchingLayoutFile(jobdir) createPreview = 0 computeOverlap = 0 fusion_method="Linear Blending" handleRGB = "Red, Green and Blue" showImage = 0 #fusion=1 regression=0.30 max/avg=2.50 absolute=3.50" st = Stitch_Image_Collection() st.alpha = 1 IJ.log("layout file: "+str(layoutFile)) impStitched = st.work(layoutFile, createPreview, computeOverlap, fusion_method, handleRGB, showImage) stitchedFile = os.path.join(jobdir,tID+zID+"_stitched.tif"); #impStitched.show() IJ.saveAs(impStitched,"Tiff", stitchedFile); if check: print os.path.join(dirOut,tID+zID+"_stitched.tif") stitchedFile = os.path.join(dirOut,tID+zID+"_stitched.tif"); IJ.saveAs(impStitched,"Tiff", stitchedFile); IJ.log("STITCHING END **********") if combine_z: IJ.log("combine z.....") ######### IJ.log("load stitched images into a stack...") for z in range(zs,ze+1): zID = "z"+str(z); stitchedFile = os.path.join(jobdir,tID+zID+"_stitched.tif"); IJ.log("opening "+stitchedFile) imp = IJ.openImage(stitchedFile) if z==zs: stack = ImageStack(imp.width,imp.height) stack.addSlice(imp.getProcessor()) imp = ImagePlus("stack", stack) #imp.show() ######## ######## IJ.log("cropping...") imp.setRoi(xs, ys, xe, ye); IJ.run(imp, "Crop", ""); #imp.show() ######## # the following normalisation should not be necessary, because they are already all 128/mean normalised #IJ.log("-- normalise intensity of all slices...") #stats = imp.getStatistics(Measurements.MEAN) #IJ.log("stats.mean = "+str(stats.mean)); # this is only the mean of one slice...is this a problem? #stack = imp.getStack() #for i in range(1, impFFT.getNSlices()+1): # ip = stack.getProcessor(i).convertToFloat() # ip.multiply(128/stats.mean) # #stack.setSlice(stack.getSliceLabel(i), ip) #run("Set Slice...", "slice="+1); #run("Set Measurements...", " mean redirect=None decimal=9"); #run("Select None"); #setBatchMode(true); #setMinAndMax(0, 255); run("32-bit"); #for(l=0; l<nSlices+1; l++) { ## run("Select All"); # run("Clear Results"); # run("Measure"); # picsum=getResult("Mean",0); # //if(l==0){picsum1=picsum;} # //int_ratio=picsum1/picsum; # int_ratio=128/picsum; # run("Select None"); # IJ.log("ratio ="+int_ratio); # run("Multiply...", "slice value="+int_ratio); # run("Next Slice [>]"); #} #setBatchMode(false); # stop here and try by hand #... #dfgfd #//stack-reg #//IJ.log("register xy...") #//run("StackReg", "transformation=Translation"); #// project into 1 plane .... #// run("Extended Depth of Field (Easy mode)..."); #//run("Z Project...", "start=["+1+"] stop=["+ze+"] projection=[Standard Deviation]"); doEDF = True if doEDF: IJ.log("EDF: start...") parameters = Parameters() parameters.setQualitySettings(1) parameters.setTopologySettings(0) parameters.show3dView = False parameters.showTopology = False edfh = ExtendedDepthOfFieldHeadless(imp, parameters) imp = edfh.processHeadless() IJ.log("EDF: done.") #imp.show() IJ.log("EDF: converting from 32-bit to 8-bit...") IJ.setMinAndMax(imp, 0, 255); IJ.run(imp,"8-bit",""); edfFile = os.path.join(dirOut,expName+pID+"-"+tID+"_EDOF_noTimeNorm.tif"); IJ.log("EDF save: "+edfFile) IJ.saveAs(imp,"Tiff", edfFile); IJ.log("EDF save: done.") #close(); // projection #close(); // stack print "TIMEPOINT FINISHED ***************" if os.path.isdir(jobdir): print "removing "+jobdir shutil.rmtree(jobdir)