def do_projection(self, channel, proj_type=None): proj = ZProjector() ## create projection class if proj_type is None: if self.do_z[channel] == "MAX": proj.setMethod(ZProjector.MAX_METHOD) elif self.do_z[channel] == "AVG": proj.setMethod(ZProjector.AVG_METHOD) else: print "Dont know how to project this way" print "Just using a single slice for images!!" return None else: if proj_type == "MAX": proj.setMethod(ZProjector.MAX_METHOD) elif proj_type == "AVG": proj.setMethod(ZProjector.AVG_METHOD) else: print "Dont know how to project this way" print "Just using a single slice for images!!" return None proj.setImage(self.stack_imps[channel]) proj.doProjection() projection = proj.getProjection() conv = ImageConverter(projection) conv.convertToGray16() conv.setDoScaling(False) self.projections[channel] = projection self.projections_done[channel] = self.do_z[channel]
def previewDisplaySettings(image, title, zoom, cal): """Apply wanted settings for previews""" ImageConverter.setDoScaling(0) ImageConverter(image).convertToGray16() image.show() IJ.run("glasbey_on_dark") IJ.setMinAndMax(image, 0, 255) image.setTitle(title) image.setCalibration(cal) IJ.run("Set... ", "zoom=" + str(zoom))
def convert(filepath, targetFolder): imp = IJ.openImage(filepath) if imp.getType() == ImagePlus.GRAY32: ic = ImageConverter(imp) ic.setDoScaling(False) ic.convertToGray16() filename = os.path.basename(filepath) writeZip(imp, os.path.join(targetFolder, filename), title=filename) else: syncPrint("Not a 32-bit image: " + filename)
def process(imp): try: IJ.run(imp, "Subtract Background...", "rolling=50"); IJ.run(imp, "Subtract Background...", "rolling=50"); ImageConverter.setDoScaling(True); IJ.run(imp, "32-bit", ""); IJ.run(imp, "Smooth", ""); IJ.setAutoThreshold(imp, "Default dark"); IJ.run(imp, "NaN Background", ""); return imp; except(AttributeError): print("error processing!");
def apply_threshold(imp, method='Otsu', background_threshold='dark', stackopt=False, corrf=1.0): # one threshold value for the whole stack with correction if stackopt: # create argument string for the IJ.setAutoThreshold thcmd = method + ' ' + background_threshold + ' stack' # set threshold and get the lower threshold value IJ.setAutoThreshold(imp, thcmd) ip = imp.getProcessor() # get the threshold value and correct it lowth = ip.getMinThreshold() lowth_corr = int(round(lowth * corrf, 0)) # process stack with corrected threshold value imp = ThresholdTools.apply_threshold_stack_corr(imp, lowth_corr, method=method) # threshold slice-by-slice with correction if not stackopt: # get the stack stack = imp.getStack() # get the stack within the ImagePlus nslices = stack.getSize() # get the number of slices print('Slices: ' + str(nslices)) print('Thresholding slice-by-slice') for index in range(1, nslices + 1): ip = stack.getProcessor(index) # get the histogramm hist = ip.getHistogram() # get the threshold value lowth = ThresholdTools.apply_autothreshold(hist, method=method) lowth_corr = int(round(lowth * corrf, 0)) ip.threshold(lowth_corr) # convert to 8bit without rescaling ImageConverter.setDoScaling(False) ImageConverter(imp).convertToGray8() return imp
def apply_threshold_stack_corr(imp, lowth_corr): # get the stacks stack = imp.getStack() nslices = stack.getSize() for index in range(1, nslices + 1): ip = stack.getProcessor(index) ip.threshold(lowth_corr) # convert to 8bit without rescaling ImageConverter.setDoScaling(False) ImageConverter(imp).convertToGray8() return imp
def edm_watershed(imp): # get the image processor ip = imp.getProcessor() if ip.isBinary is False: # convert to 8bit without rescaling ImageConverter.setDoScaling(False) ImageConverter(imp).convertToGray8() else: edm = EDM() edm.setup("watershed", None) edm.run(ip) return imp
def convertAndSaveFile(fullFilePath, convertTo8Bit=False, allowOverwrite=False): """ """ print(' convertAndSaveFile() fullFilePath:', fullFilePath) folderPath, fileName = os.path.split(fullFilePath) fileNameNoExtension = os.path.splitext(fileName)[0] saveFileNoExtension = os.path.join(folderPath, fileNameNoExtension) # # load file and build a dict of parameters like (channels, pixels, voxels) myFileInfo, imp = bSimpleFileInfo.myLoadFile(fullFilePath, doShow=True) if convertTo8Bit: # from (ImagePlus.GRAY8, ImagePlus.GRAY16, ImagePlus.GRAY32, ImagePlus.COLOR_256 or ImagePlus.COLOR_RGB) myType = imp.getType() if myType in [1,2]: ic = ImageConverter(imp) # converts channelImp in place scaleConversions = True ic.setDoScaling(scaleConversions) # scales inensities to fill 0...255 ic.convertToGray8() # # split channels channelArray = ChannelSplitter.split(imp) # returns an array of imp for channelIdx, channelImp in enumerate(channelArray): # channelImp is an imp, this will NOT have fileinfo (we just created it) #channelImp.show() saveFilePath = saveFileNoExtension + '_ch' + str(channelIdx+1) + '.tif' print(' ch:', channelIdx+1, 'saveFilePath:', saveFilePath) if not allowOverwrite and os.path.isfile(saveFilePath): print(' . not saving, file already exists', saveFilePath) else: IJ.save(channelImp, saveFilePath) return myFileInfo
def loadTif(self, allowOverwrite=1): if self.header['b_sequence'] == 'Linescan': bPrintLog( 'Skipping: bPrairie2tif does not support Linescan, email bob and have him implement this', 3) return 0 width = None height = None #ip_ch1 = [] # a list of images as a list of 'image processor' #ip_ch2 = [] #ip_ch3 = [] bPrintLog('Loading ' + str(self.header['b_numSlices']) + ' Files ...', 3) numFiles = 0 infoStr = '' # sort individual .tif files into ch1 and ch2 for filename in os.listdir(self.srcFolder): if filename.endswith(".tif") and not filename.startswith('.'): # bPrintLog('opening:' + filename, 3) try: imp = IJ.openImage(self.srcFolder + filename) if imp is None: bPrintLog( "ERROR: prairie2stack() could not open image from file:" + self.srcFolder + filename) continue isch1 = '_Ch1_' in filename isch2 = '_Ch2_' in filename isch3 = '_Ch3_' in filename if numFiles == 0: # don;t do this, header is to big to keep with output .tif #infoStr = imp.getProperty("Info") #get all tags, this is usefless infoStr += '\n' + self.infoStr0 # when appending, '\n' (EOL) is important because header does NOT end in EOL width = imp.width height = imp.height #stack = imp.getImageStack() #cp = stack.getProcessor(1) # assume 1 channel if isch1: #ip_ch1.append(cp) if self.imp_ch1 is None: self.imp_ch1 = imp else: self.imp_ch1 = Concatenator.run(self.imp_ch1, imp) elif isch2: #ip_ch2.append(cp) if self.imp_ch2 is None: self.imp_ch2 = imp else: self.imp_ch2 = Concatenator.run(self.imp_ch2, imp) elif isch3: #ip_ch3.append(cp) if self.imp_ch3 is None: self.imp_ch3 = imp else: self.imp_ch3 = Concatenator.run(self.imp_ch3, imp) else: bPrintLog('ERROR: did not find channel name in file:' + filename) numFiles += 1 except: continue #bPrintLog("exception error: prairie2stack() could not open image from file:" + self.srcFolder + filename) bPrintLog('Loaded ' + str(numFiles) + ' files ...', 3) ''' bPrintLog('ch1 has ' + str(len(ip_ch1)) + ' slices', 4) bPrintLog('ch2 has ' + str(len(ip_ch2)) + ' slices', 4) bPrintLog('ch3 has ' + str(len(ip_ch3)) + ' slices', 4) ''' #20170314, need to rewrite this to loop through channels (lots of repeated code here if self.imp_ch1 is not None: self.imp_ch1.setProperty("Info", infoStr) if self.imp_ch2 is not None: self.imp_ch2.setProperty("Info", infoStr) if self.imp_ch3 is not None: self.imp_ch3.setProperty("Info", infoStr) #ch1 #if ip_ch1: if self.imp_ch1: # bPrintLog('ch1 has ' + str(self.imp_ch1.getNSlices()) + ' slices', 4) ''' stack_ch1 = ImageStack(width, height) for fp in ip_ch1: stack_ch1.addSlice(fp) self.imp_ch1 = ImagePlus('xxx', stack_ch1) self.imp_ch1.setProperty("Info", infoStr); ''' # median filter if globalOptions['medianFilter'] > 0: bPrintLog( 'ch1: Running median filter: ' + str(globalOptions['medianFilter']), 4) medianArgs = 'radius=' + str( globalOptions['medianFilter']) + ' stack' IJ.run(self.imp_ch1, "Median...", medianArgs) infoStr += 'bMedianFilter=' + str( globalOptions['medianFilter']) + '\n' self.imp_ch1.setProperty("Info", infoStr) if globalOptions['convertToEightBit']: bPrintLog( 'converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 4) bitDepth = 2 ^ 13 divideBy = bitDepth / 2 ^ 8 # divide the 13 bit image down to 8 bit #run("Divide...", "value=32 stack"); bPrintLog('divideBy:' + str(divideBy), 4) divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(self.imp_ch1, "Divide...", divideArgs) # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); ImageConverter.setDoScaling(False) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 4) IJ.run(self.imp_ch1, "8-bit", '') # print stats including intensity for the stack we just made # Returns the dimensions of this image (width, height, nChannels, nSlices, nFrames) as a 5 element int array. d = self.imp_ch1.getDimensions( ) # width, height, nChannels, nSlices, nFrames stats = self.imp_ch1.getStatistics() # stats.min, stats.max bPrintLog( 'ch1 dimensions w:' + str(d[0]) + ' h:' + str(d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(d[3]) + ' frames:' + str(d[4]), 4) bPrintLog( 'ch1 intensity min:' + str(stats.min) + ' max:' + str(stats.max), 4) # set the voxel size so opening in Fiji will report correct bit depth # run("Properties...", "channels=1 slices=300 frames=1 unit=um pixel_width=.2 pixel_height=.3 voxel_depth=.4"); #ch2 #if ip_ch2: if self.imp_ch2: # bPrintLog('ch2 has ' + str(self.imp_ch2.getNSlices()) + ' slices', 4) ''' stack_ch2 = ImageStack(width, height) for fp in ip_ch2: stack_ch2.addSlice(fp) self.imp_ch2 = ImagePlus('xxx', stack_ch2) self.imp_ch2.setProperty("Info", infoStr); ''' # median filter if globalOptions['medianFilter'] > 0: bPrintLog( 'ch2: Running median filter: ' + str(globalOptions['medianFilter']), 4) medianArgs = 'radius=' + str( globalOptions['medianFilter']) + ' stack' IJ.run(self.imp_ch2, "Median...", medianArgs) infoStr += 'bMedianFilter=' + str( globalOptions['medianFilter']) + '\n' self.imp_ch2.setProperty("Info", infoStr) if globalOptions['convertToEightBit']: bPrintLog( 'converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 4) bitDepth = 2 ^ 13 divideBy = bitDepth / 2 ^ 8 # divide the 13 bit image down to 8 bit #run("Divide...", "value=32 stack"); bPrintLog('divideBy:' + str(divideBy), 4) divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(self.imp_ch2, "Divide...", divideArgs) # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); ImageConverter.setDoScaling(False) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 4) IJ.run(self.imp_ch2, "8-bit", '') # print stats including intensity for the stack we just made d = self.imp_ch2.getDimensions( ) # width, height, nChannels, nSlices, nFrames stats = self.imp_ch2.getStatistics() # stats.min, stats.max bPrintLog( 'ch2 dimensions w:' + str(d[0]) + ' h:' + str(d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(d[3]) + ' frames:' + str(d[4]), 4) bPrintLog( 'ch2 intensity min:' + str(stats.min) + ' max:' + str(stats.max), 4) #ch2 #if ip_ch3: if self.imp_ch3: # bPrintLog('ch1 has ' + str(self.imp_ch3.getNSlices()) + ' slices', 4) ''' stack_ch3 = ImageStack(width, height) for fp in ip_ch3: stack_ch3.addSlice(fp) self.imp_ch3 = ImagePlus('xxx', stack_ch3) self.imp_ch3.setProperty("Info", infoStr); ''' # median filter if globalOptions['medianFilter'] > 0: bPrintLog( 'ch3: Running median filter: ' + str(globalOptions['medianFilter']), 4) medianArgs = 'radius=' + str( globalOptions['medianFilter']) + ' stack' IJ.run(self.imp_ch3, "Median...", medianArgs) infoStr += 'bMedianFilter=' + str( globalOptions['medianFilter']) + '\n' self.imp_ch3.setProperty("Info", infoStr) if globalOptions['convertToEightBit']: bPrintLog( 'converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 4) bitDepth = 2 ^ 13 divideBy = bitDepth / 2 ^ 8 # divide the 13 bit image down to 8 bit #run("Divide...", "value=32 stack"); bPrintLog('divideBy:' + str(divideBy), 4) divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(self.imp_ch3, "Divide...", divideArgs) # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); ImageConverter.setDoScaling(False) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 4) IJ.run(self.imp_ch3, "8-bit", '') # print stats including intensity for the stack we just made d = self.imp_ch3.getDimensions( ) # width, height, nChannels, nSlices, nFrames stats = self.imp_ch3.getStatistics() # stats.min, stats.max bPrintLog( 'ch3 dimensions w:' + str(d[0]) + ' h:' + str(d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(d[3]) + ' frames:' + str(d[4]), 4) bPrintLog( 'ch3 intensity min:' + str(stats.min) + ' max:' + str(stats.max), 4) return 1
def runOneTif(tifPath, dstTifPath): bPrintLog('=== runOneTif processing tif:' + tifPath, 3) bPrintLog('Loading file...', 3) imp = IJ.openImage(tifPath) if imp is None: bPrintLog('ERROR: could not open image from file:' + tifPath, 3) return 0 logStr = 'done loading file: ' + str(imp.width) + ' ' + str(imp.height) + ' ' + str(imp.getNSlices()) bPrintLog(logStr, 3) numSlices = imp.getNSlices() if numSlices>1: pass else: bPrintLog('ERROR: number of slices must be more than one, file: ' + tifPath) return 0 bPrintLog('numSlices: ' + str(numSlices), 3) infoStr = imp.getProperty("Info") #get all tags #print infoStr if infoStr is None: infoStr = '' infoStr += 'bAverageFrames=v0.1\n' imp.setProperty("Info", infoStr) imp.show() impWin = imp.getTitle() # # start body #infer type of file from # get the actual bit depth used (e.g. ScanImage is 11 bit, Prairie is 13 bit) header = bParseHeader(imp) b_sequence = '' if 'b_sequence' in header: b_sequence = str(header['b_sequence']) bPrintLog('b_sequence: ' + b_sequence, 3) madeAverage = 0 # if numSlices is not divisable by gNumToAverage then chop a few slices off bottom/end if b_sequence.startswith('TSeries'): if globalOptions['gNumToAverage'] > 1: numToRemove = numSlices % globalOptions['gNumToAverage'] if numToRemove > 0: bPrintLog('Removing bottom slices: ' + str(numToRemove), 3) # run("Slice Remover", "first=3 last=5 increment=1"); removeArgs = 'first=' + str(numSlices-numToRemove+1) + ' last=' + str(numSlices) + ' increment=1' IJ.run('Slice Remover', removeArgs) numSlices = imp.getNSlices() bPrintLog('numSlices: ' + str(numSlices), 3) #fix this: if stack is really short this will not be taken if (numSlices > globalOptions['gNumToAverage']): bPrintLog('Taking average of ' + str(globalOptions['gNumToAverage']) + ' slices from ' + str(numSlices), 3) stackRegParams = 'projection=[Average Intensity] group=' + str(globalOptions['gNumToAverage']) IJ.run('Grouped Z Project...', stackRegParams) # makes window AVG_ madeAverage = 1 avgWindow = 'AVG_' + impWin avgImp = WindowManager.getImage(avgWindow) avgSlices = avgImp.getNSlices() # Grouped Z PRoject swaps slices for frames? tmpSlices = avgImp.getNSlices() tmpFrames = avgImp.getNFrames() if tmpFrames > 1: newSlices = tmpFrames newFrames = tmpSlices nChannels = 1 bPrintLog('Swaping frames for slices after grouped z',3) bPrintLog('newSlices=' + str(newSlices) + ' newFrames='+str(newFrames), 4) avgImp.setDimensions(nChannels, newSlices, newFrames) infoStr += 'gNumToAverage=' + str(globalOptions['gNumToAverage']) + '\n' # I want to adjust the framePeriod, prairie would be 'b_framePeriod' avgImp.setProperty("Info", infoStr) else: avgImp = imp avgSlices = numSlices else: bPrintLog('Not taking average of sequence: ' + b_sequence,3) avgImp = imp avgSlices = numSlices if globalOptions['medianFilter']>0: bPrintLog('Running median filter: ' + str(globalOptions['medianFilter']), 3) medianArgs = 'radius=' + str(globalOptions['medianFilter']) + ' stack' IJ.run(avgImp, "Median...", medianArgs); infoStr += 'bMedianFilter=' + str(globalOptions['medianFilter']) + '\n' avgImp.setProperty("Info", infoStr) # convert to 8 bit # 1) read bit depth from header (e.g. 2^13) # 2) do math on image and convert to 8-bit # run("Divide...", "value=32 stack"); if globalOptions['gConvertToEightBit']: bPrintLog('converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 3) bitDepth = 2^13 divideBy = bitDepth / 2^8 # divide the 13 bit image down to 8 bit #run("Divide...", "value=32 stack"); bPrintLog('divideBy:' + str(divideBy), 3) divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(avgImp, "Divide...", divideArgs); # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); ImageConverter.setDoScaling(False) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 3) IJ.run(avgImp, "8-bit", ''); bPrintLog('Saving stack with ' + str(avgSlices) + ' slices:' + dstTifPath, 3) fs = FileSaver(avgImp) if avgSlices>1: fs.saveAsTiffStack(dstTifPath) else: fs.saveAsTiff(dstTifPath) if madeAverage: avgImp.changes = 0 avgImp.close() imp.changes = 0 imp.close() # end body # # why was this here #imp.changes = 0 #imp.close() return 1
def loadTif(self, allowOverwrite=1): if self.header['b_sequence'] == 'Linescan': bPrintLog('Skipping: bPrairie2tif does not support Linescan, email bob and have him implement this', 3) return 0 width = None height = None #ip_ch1 = [] # a list of images as a list of 'image processor' #ip_ch2 = [] #ip_ch3 = [] bPrintLog('Loading ' + str(self.header['b_numSlices']) + ' Files ...', 3) numFiles = 0 infoStr = '' # sort individual .tif files into ch1 and ch2 for filename in os.listdir(self.srcFolder): if filename.endswith(".tif") and not filename.startswith('.'): # bPrintLog('opening:' + filename, 3) try: imp = IJ.openImage(self.srcFolder + filename) if imp is None: bPrintLog("ERROR: prairie2stack() could not open image from file:" + self.srcFolder + filename) continue isch1 = '_Ch1_' in filename isch2 = '_Ch2_' in filename isch3 = '_Ch3_' in filename if numFiles == 0: # don;t do this, header is to big to keep with output .tif #infoStr = imp.getProperty("Info") #get all tags, this is usefless infoStr += '\n' + self.infoStr0 # when appending, '\n' (EOL) is important because header does NOT end in EOL width = imp.width height = imp.height #stack = imp.getImageStack() #cp = stack.getProcessor(1) # assume 1 channel if isch1: #ip_ch1.append(cp) if self.imp_ch1 is None: self.imp_ch1 = imp else: self.imp_ch1 = Concatenator.run(self.imp_ch1, imp) elif isch2: #ip_ch2.append(cp) if self.imp_ch2 is None: self.imp_ch2 = imp else: self.imp_ch2 = Concatenator.run(self.imp_ch2, imp) elif isch3: #ip_ch3.append(cp) if self.imp_ch3 is None: self.imp_ch3 = imp else: self.imp_ch3 = Concatenator.run(self.imp_ch3, imp) else: bPrintLog('ERROR: did not find channel name in file:' + filename) numFiles += 1 except: continue #bPrintLog("exception error: prairie2stack() could not open image from file:" + self.srcFolder + filename) bPrintLog('Loaded ' + str(numFiles) + ' files ...', 3) ''' bPrintLog('ch1 has ' + str(len(ip_ch1)) + ' slices', 4) bPrintLog('ch2 has ' + str(len(ip_ch2)) + ' slices', 4) bPrintLog('ch3 has ' + str(len(ip_ch3)) + ' slices', 4) ''' #20170314, need to rewrite this to loop through channels (lots of repeated code here if self.imp_ch1 is not None: self.imp_ch1.setProperty("Info", infoStr); if self.imp_ch2 is not None: self.imp_ch2.setProperty("Info", infoStr); if self.imp_ch3 is not None: self.imp_ch3.setProperty("Info", infoStr); #ch1 #if ip_ch1: if self.imp_ch1: # bPrintLog('ch1 has ' + str(self.imp_ch1.getNSlices()) + ' slices', 4) ''' stack_ch1 = ImageStack(width, height) for fp in ip_ch1: stack_ch1.addSlice(fp) self.imp_ch1 = ImagePlus('xxx', stack_ch1) self.imp_ch1.setProperty("Info", infoStr); ''' # median filter if globalOptions['medianFilter']>0: bPrintLog('ch1: Running median filter: ' + str(globalOptions['medianFilter']), 4) medianArgs = 'radius=' + str(globalOptions['medianFilter']) + ' stack' IJ.run(self.imp_ch1, "Median...", medianArgs); infoStr += 'bMedianFilter=' + str(globalOptions['medianFilter']) + '\n' self.imp_ch1.setProperty("Info", infoStr) if globalOptions['convertToEightBit']: bPrintLog('converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 4) bitDepth = 2^13 divideBy = bitDepth / 2^8 # divide the 13 bit image down to 8 bit #run("Divide...", "value=32 stack"); bPrintLog('divideBy:' + str(divideBy), 4) divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(self.imp_ch1, "Divide...", divideArgs); # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); ImageConverter.setDoScaling(False) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 4) IJ.run(self.imp_ch1, "8-bit", ''); # print stats including intensity for the stack we just made # Returns the dimensions of this image (width, height, nChannels, nSlices, nFrames) as a 5 element int array. d = self.imp_ch1.getDimensions() # width, height, nChannels, nSlices, nFrames stats = self.imp_ch1.getStatistics() # stats.min, stats.max bPrintLog('ch1 dimensions w:' + str(d[0]) + ' h:' + str(d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(d[3]) + ' frames:' + str(d[4]), 4) bPrintLog('ch1 intensity min:' + str(stats.min) + ' max:' + str(stats.max), 4) # set the voxel size so opening in Fiji will report correct bit depth # run("Properties...", "channels=1 slices=300 frames=1 unit=um pixel_width=.2 pixel_height=.3 voxel_depth=.4"); #ch2 #if ip_ch2: if self.imp_ch2: # bPrintLog('ch2 has ' + str(self.imp_ch2.getNSlices()) + ' slices', 4) ''' stack_ch2 = ImageStack(width, height) for fp in ip_ch2: stack_ch2.addSlice(fp) self.imp_ch2 = ImagePlus('xxx', stack_ch2) self.imp_ch2.setProperty("Info", infoStr); ''' # median filter if globalOptions['medianFilter']>0: bPrintLog('ch2: Running median filter: ' + str(globalOptions['medianFilter']), 4) medianArgs = 'radius=' + str(globalOptions['medianFilter']) + ' stack' IJ.run(self.imp_ch2, "Median...", medianArgs); infoStr += 'bMedianFilter=' + str(globalOptions['medianFilter']) + '\n' self.imp_ch2.setProperty("Info", infoStr) if globalOptions['convertToEightBit']: bPrintLog('converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 4) bitDepth = 2^13 divideBy = bitDepth / 2^8 # divide the 13 bit image down to 8 bit #run("Divide...", "value=32 stack"); bPrintLog('divideBy:' + str(divideBy), 4) divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(self.imp_ch2, "Divide...", divideArgs); # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); ImageConverter.setDoScaling(False) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 4) IJ.run(self.imp_ch2, "8-bit", ''); # print stats including intensity for the stack we just made d = self.imp_ch2.getDimensions() # width, height, nChannels, nSlices, nFrames stats = self.imp_ch2.getStatistics() # stats.min, stats.max bPrintLog('ch2 dimensions w:' + str(d[0]) + ' h:' + str(d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(d[3]) + ' frames:' + str(d[4]), 4) bPrintLog('ch2 intensity min:' + str(stats.min) + ' max:' + str(stats.max), 4) #ch2 #if ip_ch3: if self.imp_ch3: # bPrintLog('ch1 has ' + str(self.imp_ch3.getNSlices()) + ' slices', 4) ''' stack_ch3 = ImageStack(width, height) for fp in ip_ch3: stack_ch3.addSlice(fp) self.imp_ch3 = ImagePlus('xxx', stack_ch3) self.imp_ch3.setProperty("Info", infoStr); ''' # median filter if globalOptions['medianFilter']>0: bPrintLog('ch3: Running median filter: ' + str(globalOptions['medianFilter']), 4) medianArgs = 'radius=' + str(globalOptions['medianFilter']) + ' stack' IJ.run(self.imp_ch3, "Median...", medianArgs); infoStr += 'bMedianFilter=' + str(globalOptions['medianFilter']) + '\n' self.imp_ch3.setProperty("Info", infoStr) if globalOptions['convertToEightBit']: bPrintLog('converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 4) bitDepth = 2^13 divideBy = bitDepth / 2^8 # divide the 13 bit image down to 8 bit #run("Divide...", "value=32 stack"); bPrintLog('divideBy:' + str(divideBy), 4) divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(self.imp_ch3, "Divide...", divideArgs); # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); ImageConverter.setDoScaling(False) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 4) IJ.run(self.imp_ch3, "8-bit", ''); # print stats including intensity for the stack we just made d = self.imp_ch3.getDimensions() # width, height, nChannels, nSlices, nFrames stats = self.imp_ch3.getStatistics() # stats.min, stats.max bPrintLog('ch3 dimensions w:' + str(d[0]) + ' h:' + str(d[1]) + ' channels:' + str(d[2]) + ' slices:' + str(d[3]) + ' frames:' + str(d[4]), 4) bPrintLog('ch3 intensity min:' + str(stats.min) + ' max:' + str(stats.max), 4) return 1
tracked[i]= 11 print test.labelValues fp= ShortProcessor(len(tracked), 1,tracked , None) labelerImp= ImagePlus("labeler", fp) src2=clij2.push(labelerImp) conLabeledStack=ImageStack(imp1.width, imp1.height) if frames>1: for nFrame in range(1,frames+1): imp3=extractFrame(imp1, nFrame) src=clij2.push(imp3) dst=clij2.create(src) clij2.replaceIntensities(src, src2, dst) LabeledImp=clij2.pull(dst) conLabeledStack = concatStacks( conLabeledStack, LabeledImp) concatLabeledImp= ImagePlus("Labeled "+imageName, conLabeledStack) ImageConverter.setDoScaling(0) ImageConverter(concatLabeledImp).convertToGray16() IJ.setMinAndMax(concatLabeledImp, 0, 255) concatLabeledImp.setCalibration(imp1.getCalibration()) concatLabeledImp.setDimensions(1, imp1.getNSlices(), imp1.getNFrames()) concatLabeledImp = CompositeImage(concatLabeledImp, CompositeImage.COMPOSITE) concatLabeledImp.show() IJ.run("glasbey_on_dark") labelerImp.close()
def auto_threshold(imp_in, str_thresh, bScale=False): """ auto_threshold_otsu(imp_in, str_thresh="Otsu", bScale=True) Compute an autothreshold for an image. Adapted from http://wiki.cmci.info/documents/120206pyip_cooking/python_imagej_cookbook Parameters ---------- imp_in ImagePlus The image to threshold str_thresh String (Default: Default) The threshold: Otsu, Huang, IsoData, Intermodes, Li, MaxEntropy, Mean, MinError, Minimum, Moments, Percentile, RenyiEntropy, Shanbhag, Triangle, Yen, or Default bScale Boolean (Default: False) Return ------ imp_out ImagePlus The binary image thr_val integer The threshold value """ ti = imp_in.getShortTitle() imp = imp_in.duplicate() hist = imp.getProcessor().getHistogram() if (str_thresh == "Otsu"): lowTH = Auto_Threshold.Otsu(hist) elif (str_thresh == "Huang"): lowTH = Auto_Threshold.Huang(hist) elif (str_thresh == "Intermodes"): lowTH = Auto_Threshold.Intermodes(hist) elif (str_thresh == "IsoData"): lowTH = Auto_Threshold.IsoData(hist) elif (str_thresh == "Li"): lowTH = Auto_Threshold.Li(hist) elif (str_thresh == "MaxEntropy"): lowTH = Auto_Threshold.MaxEntropy(hist) elif (str_thresh == "Mean"): lowTH = Auto_Threshold.Mean(hist) elif (str_thresh == "MinError"): lowTH = Auto_Threshold.MinError(hist) elif (str_thresh == "Minimum"): lowTH = Auto_Threshold.Minimum(hist) elif (str_thresh == "Moments"): lowTH = Auto_Threshold.Moments(hist) elif (str_thresh == "Percentile"): lowTH = Auto_Threshold.Percentile(hist) elif (str_thresh == "RenyiEntropy"): lowTH = Auto_Threshold.RenyiEntropy(hist) elif (str_thresh == "Shanbhag"): lowTH = Auto_Threshold.Shanbhag(hist) elif (str_thresh == "Triangle"): lowTH = Auto_Threshold.Triangle(hist) elif (str_thresh == "Yen"): lowTH = Auto_Threshold.Yen(hist) else: lowTH = Auto_Threshold.Default(hist) imp.getProcessor().threshold(lowTH) imp.setDisplayRange(0, lowTH + 1) ImageConverter.setDoScaling(bScale) IJ.run(imp, "8-bit", "") imp.setDisplayRange(0, 255) imp.setTitle(ti + "-bin-" + str_thresh) return ([imp, lowTH])
def runOneTif(tifPath, dstTifPath): bPrintLog('=== runOneTif processing tif:' + tifPath, 3) bPrintLog('Loading file...', 3) imp = IJ.openImage(tifPath) if imp is None: bPrintLog('ERROR: could not open image from file:' + tifPath, 3) return 0 logStr = 'done loading file: ' + str(imp.width) + ' ' + str( imp.height) + ' ' + str(imp.getNSlices()) bPrintLog(logStr, 3) numSlices = imp.getNSlices() bPrintLog('numSlices: ' + str(numSlices), 3) infoStr = imp.getProperty("Info") #get all tags if infoStr is None: infoStr = '' infoStr += 'bMaxProject=v0.1\n' imp.setProperty("Info", infoStr) imp.show() impWin = imp.getTitle() # BODY # get the bit depth form opened imp impBitDepth = imp.getBitDepth() bPrintLog('image bit depth:' + str(impBitDepth), 3) # get the actual bit depth used (e.g. ScanImage is 11 bit, Prairie is 13 bit) header = bParseHeader(imp) actualBitDepth = impBitDepth if 'b_bitDepth' in header: actualBitDepth = int(header['b_bitDepth']) bPrintLog('actual bit depth:' + str(actualBitDepth), 3) made8bit = 0 if impBitDepth == 8: made8bit = 1 else: made8bit = 1 if 0: divideBy = math.pow(2, actualBitDepth) / math.pow( 2, 8) # divide the 13 bit or 11 bit image down to 8 bit bPrintLog('diving by:' + str(divideBy), 3) bPrintLog( 'converting to 8-bit by dividing image by ' + str(divideBy) + ' and then convert to 8-bit with ImageConverter.setDoScaling(False)', 3) #run("Divide...", "value=32 stack"); divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(imp, "Divide...", divideArgs) # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); # 20170810 was this #ImageConverter.setDoScaling(False) ImageConverter.setDoScaling(True) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 3) IJ.run(imp, "8-bit", '') #does this in place, no new window # save bPrintLog('Saving stack with ' + str(numSlices) + ' slices:' + dstTifPath, 3) fs = FileSaver(imp) if numSlices > 1: fs.saveAsTiffStack(dstTifPath) else: fs.saveAsTiff(dstTifPath) # END BODY # close original imp.changes = 0 imp.close()
def runEDM(imp=None): print('=== runEDM()') # # get info from original imp (make a copy below) myInfoDict = simpleFileInfo.getImpInfo(imp, '') print(json.dumps(myInfoDict, indent=4)) filePath = myInfoDict['filePath'] filePathNoExtension = filePath.split('.')[ 0] # assuming folders in path DO NOT have '.' print(' . filePathNoExtension:', filePathNoExtension) impOriginalWindowTitle = imp.getTitle() # # make a copy of imp print(imp) print(' . === making copy of imp') imp = imp.duplicate() imp.show() # # work on the copy image (mean and mask will be performed on this copy 'in place') impWindowTitle = imp.getTitle() impImage = impWindowTitle.split('.')[0] # used by 3D Distance Map print(' . impWindowTitle:', impWindowTitle) print(' impImage:', impImage) # # mean print(' . === mean 3D filter') IJ.run("Mean 3D...", "x=3 y=3 z=2") # # threshold #IJ.setAutoThreshold("Otsu dark") #IJ.setOption("BlackBackground", true); print(' . === Otsu threshold') IJ.run("Convert to Mask", "method=Otsu background=Dark calculate") # invert IJ.run("Invert LUT") # # fill holes print(' . === fill holes') IJ.run("3D Fill Holes") # does not seem to do anything ??? ''' # 3d mean ch1 ... # convert ch1 to mask selectWindow("20200420_distalHEAD__ch1.tif"); setAutoThreshold("Default dark"); //run("Threshold..."); setAutoThreshold("Otsu dark"); setOption("BlackBackground", false); run("Convert to Mask", "method=Otsu background=Dark calculate"); run("Close"); # # run 3d distance map, outputs two windows (EVF, EDT) # # v1, I thought this was working ??? run("3D Distance Map", "map=Both image=20200420_distalHEAD__ch1 mask=20200420_distalHEAD__ch2_mask threshold=1 inverse"); convert output evf to 8-bit output evf has (maybe don't convert to 8-bit???) -1: where there was no mask in ch1 (after 8-bit is 128) 0: where there was a mask in ch2 (after 8-bit is 0) value: distance between point in ch1 mask and nearest point in ch2 mask # # v2, now this seems to be working (neither mask has inverted LUT) # here, 20200420_distalHEAD__ch1-1 is a mask of channel # run("3D Distance Map", "map=Both image=20200420_distalHEAD__ch2_mask mask=20200420_distalHEAD__ch1-1 threshold=1 inverse"); ''' # # 3d distance map (makes EDT window) print(' . === 3d euclidean distance map (EDM) ... please wait') paramStr = 'map=EDT image=' + impImage + ' mask=Same threshold=1 inverse' # inverse? #IJ.run("3D Distance Map", "map=EDT image=20200420_distalHEAD__ch2 mask=Same threshold=1 inverse") IJ.run("3D Distance Map", paramStr) edmImp = WindowManager.getCurrentImage() print(' . edmImp:', edmImp) # convert 32-bit edm to 8-bit ic = ImageConverter(edmImp) # converts channelImp in place scaleConversions = True ic.setDoScaling(scaleConversions) # scales inensities to fill 0...255 ic.convertToGray8() print(' . edmImp:', edmImp) # # save IJ.selectWindow(impWindowTitle) maskPath = filePathNoExtension + '_mask.tif' print(' . === saving maskPath:', maskPath) IJ.saveAs("Tiff", maskPath) IJ.selectWindow("EDT") edmPath = filePathNoExtension + '_edm.tif' print(' . === saving edmPath:', edmPath) IJ.saveAs("Tiff", edmPath) # # set both (mask and edm) changes=false (we save them) imp.changes = False edmImp.changes = False # # output, merge channels into composite # contrast adjust edmp print(' . === contrast adjust edm') edmPath, edmFile = os.path.split(edmPath) IJ.selectWindow(edmFile) IJ.run("Enhance Contrast", "saturated=0.35") # not sure how to calculate auto, 0.35 will be different !!! IJ.run("Apply LUT", "stack") # merge into composite print(' . === merging into composite') #impOriginalWindowTitle was assigned right at start maskWindowTitle = imp.getTitle( ) # (mean, threshold) was done in place on copy edmWindowTitle = edmImp.getTitle() # run("Merge Channels...", "c1=20200420_distalHEAD__ch2.tif c2=20200420_distalHEAD__ch2_mask.tif c3=20200420_distalHEAD__ch2_edm.tif create keep ignore"); paramStr = 'c1=' + impOriginalWindowTitle + ' c2=' + maskWindowTitle + ' c3=' + edmWindowTitle + ' create keep ignore' IJ.run("Merge Channels...", paramStr)
def myConvert(path='', imp=None): if path == '' and imp is None: # NOT USED # ask user for file. I do not know how to handle when users hits cancel??? Script will just fail notUsedBy_oxs = 'Open a two-channel deconvoluted .oir file' path = OpenDialog(notUsedBy_oxs).getPath() if len(path) > 0: print(' user selected path:', path) fileName = os.path.basename(path) # load print(' . loading:', path) imps = BF.openImagePlus(path) for imp in imps: imp.show() # convert to 8-bit ImageConverter.setDoScaling(True) IJ.run('8-bit') # split channels IJ.run("Split Channels") # save channel 1 windowName = 'C1-' + fileName print(' . ch1 windowName:', windowName) IJ.selectWindow(windowName) windowName_notSure = WindowManager.getImage(windowName) saveFilePath = os.path.splitext( path )[0] + '_ch1.tif' # this is getting garbled when we have spaces (' ') in path !!!!!!!!! # remove spaces #saveFilePath = saveFilePath.replace(' ', '_') print(' saving', saveFilePath) IJ.save(windowName_notSure, saveFilePath) #IJ.run("Save", 'save=' + saveFilePath) # #IJ.close() # close channel 1 ... this does not work windowName_notSure.close() # save channel 2 windowName = 'C2-' + fileName print(' . ch2 windowName:', windowName) IJ.selectWindow(windowName) windowName_notSure = WindowManager.getImage(windowName) saveFilePath = os.path.splitext(path)[0] + '_ch2.tif' # remove spaces #saveFilePath = saveFilePath.replace(' ', '_') print(' saving', saveFilePath) IJ.save(windowName_notSure, saveFilePath) #IJ.run("Save", 'save=' + saveFilePath) #IJ.close() # close channel 2 ... this does not work windowName_notSure.close() # save channel 3 windowName = 'C3-' + fileName print(' . ch3 windowName:', windowName) IJ.selectWindow(windowName) windowName_notSure = WindowManager.getImage(windowName) if windowName_notSure is not None: saveFilePath = os.path.splitext(path)[0] + '_ch3.tif' # remove spaces #saveFilePath = saveFilePath.replace(' ', '_') print(' saving', saveFilePath) IJ.save(windowName_notSure, saveFilePath) #IJ.run("Save", 'save=' + saveFilePath) #IJ.close() # close channel 2 ... this does not work windowName_notSure.close() else: print('no channel 3') # close all the windows ... this does not work ''' print(' closing windows') closeAll() ''' ''' imps = BF.openImagePlus(path) for imp in imps: imp.changes= False imp.close() ''' print(' done')
from ij.process import ImageConverter IJ.run("Close All") img_dir = "/Users/jrminter/Documents/git/tips/ImageJ/tif" path_tif = img_dir + "/qm-05131-cd1435I-2-102.tif" path_jpg = img_dir + "/sem_lines_200_jpg.jpg" print(path_tif) imp_ori = IJ.openImage(path_tif) imp_ori.show() imp_ori.setRoi(373,164,600,300) IJ.run("Crop") IJ.run(imp_ori, "Enhance Contrast", "saturated=0.35") imp_ori.show() ImageConverter.setDoScaling(True) IJ.run(imp_ori, "8-bit", "") imp_ori.setTitle("SEM lines") imp_ori.show() IJ.saveAs(imp_ori, "Jpeg", path_jpg) for i in range(201): imp_jpg = IJ.openImage(path_jpg) IJ.saveAs(imp_jpg, "Jpeg", path_jpg) IJ.run(imp_jpg, "32-bit", "") IJ.run(imp_ori, "32-bit", "") imp_ori.setTitle("TIF") imp_ori.show() imp_jpg.setTitle("200 x JPG") imp_jpg.show()
def Overlayer(org_size, dirs): """ Overlays ROIs with appropriate color, saves to .tif and animates aligned images to .gif """ # Get colors. Colors, Colors_old = colorlist() # Get ROImanager. rm = RoiManager().getInstance() rois = rm.getCount() # Overlays ROI on aligned images, converts to 8-bit (for gif). for root, directories, filenames in os.walk(dirs["Composites_Aligned"]): for filename in filenames: imp = IJ.openImage(os.path.join(root, filename)) converter = ImageConverter(imp) converter.setDoScaling(True) converter.convertToGray8() # Lookup table and local contrast enhancement for vizualisation. IJ.run(imp, "Rainbow RGB", "") IJ.run(imp, "Enhance Local Contrast (CLAHE)", "blocksize=127 histogram=256 maximum=3 mask=*None*") for roi in range(rois): roi_obj = rm.getRoi(roi) roi_obj.setStrokeWidth(2) if roi < 19: roi_obj.setStrokeColor(Color(*Colors[roi][0:3])) else: roi_obj.setStrokeColor(eval(Colors_old[roi])) rm.moveRoisToOverlay(imp) IJ.saveAs(imp, "Tiff", os.path.join(dirs["Overlays"], filename)) # Opens overlaid images, saves as tiff stack. overlay_stack = IJ.run("Image Sequence...", "open="+dirs["Overlays"]+ " number=3040 starting=0 increment=1 scale=300 file=.tif sort") # Takes care of spaces in titles. tiftitle = Title.replace(" ", "_") tiftitle = tiftitle.replace(".", "_") # Gets dimensions for scalebar. imp = WindowManager.getImage("Overlays") dimensions = imp.getDimensions() size = dimensions[0] + dimensions[1] microns = org_size / size # Sets scale and writes scale-bar, flattens overlays. IJ.run(imp, "Set Scale...", "distance=1 known=" +str(microns)+" pixel=1 unit=micron") IJ.run(imp, "Scale Bar...", "width=10 height=4 font=14 color=Yellow background=None location=[Lower Right] bold overlay") IJ.run(imp, "Flatten", "stack") IJ.saveAs(imp, "Tiff", os.path.join(dirs["Gifs"], tiftitle)) # Animates tiff stack from directoy. for root, directories, filenames in os.walk(dirs["Gifs"]): for filename in filenames: if tiftitle in filename and filename.endswith(".tif"): # set=xx parameter controls gif speed. # for additional parameters run with macro recorder. try: print "Animating gif..." imp = WindowManager.getImage(tiftitle + ".tif") gif = IJ.run("Animated Gif ... ", "set=200 number=0 filename=" + os.path.join(dirs["Gifs"], tiftitle + ".gif")) except Exception, e: print str(e) print "gif animated."