本文整理汇总了Python中ij.io.FileSaver.saveAsTiffStack方法的典型用法代码示例。如果您正苦于以下问题:Python FileSaver.saveAsTiffStack方法的具体用法?Python FileSaver.saveAsTiffStack怎么用?Python FileSaver.saveAsTiffStack使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ij.io.FileSaver
的用法示例。
在下文中一共展示了FileSaver.saveAsTiffStack方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def run():
printLog("=====ZY_CreatTemp_V2====",0)
#Prompt user to open a image
od = OpenDialog("Choose image file", None)
if od is None:
msgStr = "User Cancled"
printLog(msgStr,1)
else:
sourceFolder = od.getDirectory()
fileName = od.getFileName()
imp = IJ.openImage(sourceFolder+fileName)
imp.show()
n = imp.getNSlices()
printLog("Processing source file: " + fileName,1)
imp2= pickSlice(imp)
if imp2:
destFolder = os.path.join(sourceFolder, 'Temps')
#outName = os.path.join(destFolder,fileName[:-4]+'_temp.tif') #remove the .tif in filename
outName = os.path.join(destFolder,'temp.tif')
# check or make the folder
if not os.path.isdir(destFolder):
os.makedirs(destFolder)
#make temp
dupNSlice(imp2,n-1)
printLog("Saving to: " + outName,1)
fs = FileSaver(imp2)
fs.saveAsTiffStack(outName)
imp2.close()
imp.close()
msgStr = "ZY_CraetTemp_V2.py is Done."
printLog(msgStr,0)
示例2: bSaveStack
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def bSaveStack(imp, fullPath):
fs = FileSaver(imp)
#print 'bSaveStack()', fullPath, 'nslices=', imp.getNSlices()
bPrintLog('bSaveStack():' + fullPath + ' slices=' + str(imp.getNSlices()), 1)
if imp.getNSlices()>1:
fs.saveAsTiffStack(fullPath)
else:
fs.saveAsTiff(fullPath)
示例3: saveStack
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def saveStack(destFolder,file_name,imp):
#rename the result and save it to subfolder
if not os.path.isdir(destFolder):
os.makedirs(destFolder)
fullname=os.path.join(destFolder,file_name)
#print (fullname)
fs = FileSaver(imp)
#print 'bSaveStack()', fullPath, 'nslices=', sr_imp.getNSlices()
msgStr = "Dimension:" + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
printLog("-Save "+file_name+" to "+destFolder,1)
printLog("-"+msgStr,2)
fs.saveAsTiffStack(fullname)
示例4: scaleandfilter
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def scaleandfilter(infile,outfile,scalex,scaley):
print ("infile is: "+infile)
imp = Opener().openImage(infile)
print imp
print "scalex = %f; scaley = %f" % (scalex,scaley)
# Rescale
ip = imp.getProcessor()
ip.setInterpolate(True)
sp = StackProcessor(imp.getStack(),ip);
sp2=sp.resize(int(round(ip.width * scalex)), int(round(ip.height *scaley)));
imp.setStack(imp.getTitle(),sp2);
cal = imp.getCalibration()
cal.pixelWidth /= scalex
cal.pixelHeight /= scaley
IJ.run(imp, "8-bit","")
intif=infile+".tif"
outtif=infile+"-filtered.tif"
print("saving input file as "+intif)
f=FileSaver(imp)
f.saveAsTiffStack(intif)
imp.close()
# anisotropic filtering
anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0"
anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)
if sys.version_info > (2, 4):
#for testing
# subprocess.check_call(["cp",intif,outtif])
subprocess.check_call(["anisofilter"]+anisopts.split(' ')+[intif,outtif])
else:
os.system(" ".join(["anisofilter"]+anisopts.split(' ')+[intif,outtif]))
# Hessian (tubeness)
print("Opening output tif: "+outtif)
imp = Opener().openImage(outtif)
imp.setCalibration(cal)
print("Running tubeness on tif: "+outtif)
IJ.run(imp,"Tubeness", "sigma=1")
IJ.run(imp, "8-bit","")
# Save to PIC
print("Saving as PIC: "+outfile)
# IJ.saveAs("tiff","outtif")
IJ.run(imp,"Biorad ...", "biorad="+outfile)
示例5: run
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def run():
msg = "<html>"
wm = WindowManager
wcount = wm.getWindowCount()
if wcount == 0:
msg += "No windows open, nothing to do.<br/>"
IJ.showMessage(PluginTitle, msg)
return
msg += "Number of open windows: " + str(wcount) + "<br/>"
# let the User choose a directory to store the files
target = DirectoryChooser("Choose target directory").getDirectory()
if target is None:
# User canceled the dialog
msg += "<br/>No directory chosen, aborting.<br/>"
IJ.showMessage(PluginTitle, msg)
return
msg += "Selected '" + target + "'as destination folder.<br/>"
# determine padding width for filenames
pad = len(str(wcount))
for i in range(wcount):
# image ID lists start with 1 instead of 0, so for convenience:
wid = i + 1
imp = wm.getImage(wid)
imgid = wm.getNthImageID(wid)
#print "window id:", wid, ", imageID:", wm.getNthImageID(wid)
# Construct filename
filename = 'tile_' + str(wid).zfill(pad) + '.tif'
filepath = target + '/' + filename
fs = FileSaver(imp)
if imp.getImageStackSize() > 1:
if not fs.saveAsTiffStack(filepath):
IJ.error("<html>Error saving current image, stopping.")
return
else:
if not fs.saveAsTiff(filepath):
IJ.error("<html>Error saving current image, stopping.")
return
msg += "<br/>Successfully saved " + str(wcount) + " files.<br/>"
IJ.showMessage(PluginTitle, msg)
示例6: saveTif
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def saveTif(self, allowOverwrite=1):
#make output folder
if not os.path.isdir(self.dstFolder):
os.makedirs(self.dstFolder)
#ch1
if self.imp_ch1:
#savePath = self.dstFolder + self.enclosingFolderName + '_ch1.tif' #save into new folder
if os.path.isfile(self.savePath_ch1) and not allowOverwrite:
print bPrintLog('File Exists NOT Saving: ' + savePath, 3)
else:
fs = FileSaver(self.imp_ch1)
bPrintLog('Saving: ' + self.savePath_ch1, 3)
if self.imp_ch1.getNSlices()>1:
fs.saveAsTiffStack(self.savePath_ch1)
else:
fs.saveAsTiff(self.savePath_ch1)
#ch2
if self.imp_ch2:
#save into new folder
#savePath = self.dstFolder + self.enclosingFolderName + '_ch2.tif' #save into new folder
if os.path.isfile(self.savePath_ch2) and not allowOverwrite:
bPrintLog('File Exists NOT Saving: ' + self.savePath_ch2, 3)
else:
fs = FileSaver(self.imp_ch2)
bPrintLog('Saving: ' + self.savePath_ch2, 3)
if self.imp_ch2.getNSlices()>1:
fs.saveAsTiffStack(self.savePath_ch2)
else:
fs.saveAsTiff(self.savePath_ch2)
#ch3
if self.imp_ch3:
#save into new folder
#savePath = self.dstFolder + self.enclosingFolderName + '_ch3.tif' #save into new folder
if os.path.isfile(self.savePath_ch3) and not allowOverwrite:
bPrintLog('File Exists NOT Saving: ' + self.savePath_ch3, 3)
else:
fs = FileSaver(self.imp_ch3)
bPrintLog('Saving: ' + self.savePath_ch3, 3)
if self.imp_ch3.getNSlices()>1:
fs.saveAsTiffStack(self.savePath_ch3)
else:
fs.saveAsTiff(self.savePath_ch3)
示例7: run
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def run():
print "=====ZY_Resizetif_V1===="
#expecting one argument: the file path (choose the folder first)
if len(sys.argv) < 2:
print "We need at least one folder as input"
print "Please choose the input folder"
#prompt user to choose a folder"
sourceFolder = DirectoryChooser("Please choose a directory of .tif files").getDirectory()
if not sourceFolder:
return
else:
sourceFolder = sys.argv[1] #assuming it ends in '/'
#get user options
okGo = getOptions()
if okGo == -1:
return 0
destFolder = os.path.join(sourceFolder, 'resized')
print destFolder
# check or make the folder
if not os.path.isdir(destFolder):
os.makedirs(destFolder)
print "Processing souce folder", sourceFolder
print "Saving to destination folder", destFolder
IJ.log(" ====== Startin ZY_resize_V1 ======")
IJ.log(" Processing source folder: " + sourceFolder)
IJ.log(" Saving to destination folder: " + destFolder)
numOpened = 0
numSaved = 0
for filename in os.listdir(sourceFolder):
startWithDot = filename.startswith(".")
isMax = filename.endswith("max.tif")
isTif = filename.endswith(".tif")
if (not startWithDot) and (not isMax) and isTif:
shortname, fileExtension = os.path.splitext(filename)
outPath = destFolder + "/" + filename
outPath1 = destFolder + "/" + shortname + "_ch1" + ".tif"
outPath2 = destFolder + "/" + shortname + "_ch2" + ".tif"
# before processing, check if eventual dest exists
if not replaceExisting:
if numberOfChannels == 2 and os.path.exists(outPath1) and os.path.exists(outPath2):
msgStr = " -->The file==" + filename + "== has been resized, not processing again"
print msgStr
IJ.log(msgStr)
continue #with next iteration
if numberOfChannels == 1 and os.path.exists(outPath):
msgStr = " -->The file==" + filename + "== has been resized, not processing again"
print msgStr
IJ.log(msgStr)
continue #with next iteration
print "================================"
msgStr = str(numOpened+1) + ". opening>> " + sourceFolder + filename
print msgStr
IJ.log(msgStr)
imp = IJ.openImage(sourceFolder+filename)
if imp is None:
msgStr = " -->>Error: could not open image file:" + filename
print msgStr
IJ.log(msgStr)
continue #with next iteration
imp.show()
numOpened +=1
msgStr = " -->Original size is:" + str(imp.width) + "x" + str(imp.height) + "x" + str(imp.getNSlices())
print msgStr
IJ.log(msgStr)
if imp.width < reWidth or imp.height < reHeight:
IJ.run(imp, "Size...", "width=" + str(reWidth) + " height=" + str(reHeight) + " depth=" + str(imp.getNSlices()) + " interpolation=Bilinear")
msgStr = " -> Changing size to:" + str(imp.width) + "x" + str(imp.height)+ "x" + str(imp.getNSlices())
print msgStr
IJ.log(msgStr)
imp = IJ.getImage()
if numberOfChannels == 2:
print "deinterleaving"
IJ.run("Deinterleaving", "how = 2") #make 2 windows
#ch2
imp2=IJ.getImage()
fs = FileSaver(imp2)
print "saving channel 2 file to", outPath2
fs.saveAsTiffStack(outPath2)
numSaved += 1
imp2.changes = 0
imp2.close()
#.........这里部分代码省略.........
示例8: run
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def run():
print "===== bBatchConvertTo8Bitv3 ====="
# Expecting one argument: the file path
if len(sys.argv) < 2:
print " We need at least one folder as input"
print " Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"
# Prompt user for a folder
sourceFolder = DirectoryChooser("Please Choose A Directory Of .tif Files").getDirectory()
if not sourceFolder:
return
else:
sourceFolder = sys.argv[1] #assuming it ends in '/'
#get user options
okGo = getOptions() # creates {numberOfChannels, replaceExisting}
if okGo == -1:
return 0
destFolder = sourceFolder + "channels8_256/"
#make destination directory
if not os.path.isdir(destFolder):
os.makedirs(destFolder)
print " Processing source folder: ", sourceFolder
print " Saving to destination folder: ", destFolder
numOpened = 0
numSaved = 0
for filename in os.listdir(sourceFolder):
startWithDot = filename.startswith(".")
isMax = filename.endswith("max.tif")
isTif = filename.endswith(".tif")
if (not startWithDot) and (not isMax) and (isTif):
shortName, fileExtension = os.path.splitext(filename)
outPath = destFolder + "/" + filename
outPath1 = destFolder + "/" + shortName + "_ch1" + ".tif"
outPath2 = destFolder + "/" + shortName + "_ch2" + ".tif"
#before we open, check if eventual dest exists
if not replaceExisting:
if numberOfChannels == 2 and os.path.exists(outPath1) and os.path.exists(outPath2):
print " 512 Destination file exists, not saving the image.", filename
continue #with next iteration
if numberOfChannels == 1 and os.path.exists(outPath):
print " 512 Destination file exists, not saving the image.", filename
continue #with next iteration
print " ===================================="
print " -> Opening", sourceFolder+filename
imp = IJ.openImage(sourceFolder + filename)
if imp is None:
print " Could not open image from file:", filename
continue #with next iteration
imp.show()
numOpened +=1
#i can get properties as long list of {key=value}
#how do i then set each property in new imp1/imp2? Do IJ.openImagehave ot loop?
#print imp.getProperties()
#in the future IJ.openImagehavewant to have option to scale down to 512X512
#run("Scale...", "x=- y=- z=1.0 width=512 height=512 depth=196 interpolation=Bilinear average process create title=20131007_a144_008_ch1-1.tif");
print " Image is: " + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
#if imp.getBitDepth() == 16:
if imp.width>512 and imp.height>512:
print " Converting to 512X512 with 'Scale'"
#IJ.run("8-bit")
theTitle = "tmpOutput"
IJ.run(imp, "Scale...", "x=- y=- z=1.0 width=512 height=512 depth=" + str(imp.getNSlices()) + " interpolate=Bilinear average process create title=" + theTitle)
imp = IJ.getImage()
#bug: original window is left open
if numberOfChannels == 2:
print " deinterleaving"
IJ.run("Deinterleave", "how=2"); #makes 2 window
#ch2
imp2 = IJ.getImage()
fs = FileSaver(imp2)
print " Saving 8bit File to", outPath2
fs.saveAsTiffStack(outPath2)
numSaved += 1
imp2.changes = 0
imp2.close()
#ch1
imp1 = IJ.getImage()
fs = FileSaver(imp1)
print " Saving 8bit File to", outPath2
fs.saveAsTiffStack(outPath1)
numSaved += 1
imp1.changes = 0
#.........这里部分代码省略.........
示例9: range
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
for i in range(0, channels):
imageProcessor = ShortProcessor(width, height)
imageStack = ImageStack(width, height)
for sphere in spheres:
fnorm = int(round((sphere['f'][i] - fmin[i]) / (fmax[i] - fmin[i]) * 65536.0))
x = sphere['cx']
y = sphere['cy']
d = sphere['r'] * 2
imageProcessor.putPixel(x, y, fnorm)
imageStack.addSlice(imageProcessor)
channelImages.append(ImagePlus("Rendering C" + "%i" % (i + 1), imageStack))
imageO = RGBStackMerge.mergeChannels(channelImages, False)
else:
for i in range(0, channels):
objectImage = ObjectCreator3D(sx, sy, sz)
for sphere in spheres:
fnorm = int(round((sphere['f'][i] - fmin[i]) / (fmax[i] - fmin[i]) * 65536.0))
objectImage.createEllipsoid(
sphere['cx'], sphere['cy'], sphere['cz'],
sphere['r'], sphere['r'], round(sphere['r'] / zscale),
fnorm, False)
channelImages.append(ImagePlus("Rendering C" + "%i" % (i + 1), objectImage.getStack()))
imageO = RGBStackMerge.mergeChannels(channelImages, False)
# Save result
saver = FileSaver(imageO)
saver.saveAsTiffStack(outputFile)
print "Saved " + outputFile
示例10: scaleandfilter
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def scaleandfilter(infile,outfile,scalex,scaley,scalez,anisofilter,runtube):
print ("infile is: "+infile)
imp = Opener().openImage(infile)
print imp
print "scalex = %f; scaley = %f ; scalez = %f" % (scalex,scaley,scalez)
# Rescale
cal = imp.getCalibration()
iml = ImgLib.wrap(imp)
scaledimg = Scale3D(iml, scalex, scaley, scalez)
imp2=ImgLib.wrap(scaledimg)
# find range of pixel values for scaled image
from mpicbg.imglib.algorithm.math import ComputeMinMax
# (for imglib2 will be: net.imglib2.algorithm.stats)
minmax=ComputeMinMax(scaledimg)
minmax.process()
(min,max)=(minmax.getMin().get(),minmax.getMax().get())
# Make a copy of the stack (converting to 8 bit as we go)
stack = ImageStack(imp2.width, imp2.height)
print "min = %e, max =%e" % (min,max)
for i in xrange(1, imp2.getNSlices()+1):
imp2.setSliceWithoutUpdate(i)
ip=imp2.getProcessor()
# set range
ip.setMinAndMax(min,max)
stack.addSlice(str(i), ip.convertToByte(True))
# save copy of calibration info
cal=imp.getCalibration()
# close original image
imp.close()
# make an image plus with the copy
scaled = ImagePlus(imp2.title, stack)
# Deal with calibration info which didn't seem to come along for the ride
cal.pixelWidth/=scalex
cal.pixelHeight/=scaley
cal.pixelDepth/=scalez
scaled.setCalibration(cal)
print "dx = %f; dy=%f; dz=%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)
intif=infile+".tif"
outtif=infile+"-filtered.tif"
if anisofilter.upper() != 'FALSE':
print("saving input file as "+intif)
f=FileSaver(scaled)
f.saveAsTiffStack(intif)
scaled.close()
# anisotropic filtering
anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0"
anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)
if sys.version_info > (2, 4):
#for testing
# subprocess.check_call(["cp",intif,outtif])
subprocess.check_call([anisofilter]+anisopts.split(' ')+[intif,outtif])
else:
os.system(" ".join([anisofilter]+anisopts.split(' ')+[intif,outtif]))
# Open anisofilter output back into Fiji
print("Opening output tif: "+outtif)
scaled = Opener().openImage(outtif)
scaled.setCalibration(cal)
# Hessian (tubeness)
print("Running tubeness")
if(runtube):
tp=TubenessProcessor(1.0,False)
result = tp.generateImage(scaled)
IJ.run(result, "8-bit","")
else:
result=scaled
# Save out file
fileName, fileExtension = os.path.splitext(outfile)
print("Saving as "+fileExtension+": "+outfile)
if fileExtension.lower()=='.nrrd':
nw=Nrrd_Writer()
nw.setNrrdEncoding("gzip")
nw.save(result,outfile)
else:
# Save to PIC
IJ.run(result,"Biorad ...", "biorad=["+outfile+"]")
scaled.close()
result.close()
示例11: splitext
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
#filelist = os.listdir(filedir)
for root, directories, filenames in os.walk(filedir):
print directories
for filename in filenames:
if filename.lower().endswith('.lif'):
print filedir
print "..." + filename
filebase = splitext(filename)[0]
imps = getImps(os.path.join(filedir, filename))
printInfo(imps)
for (counter, item) in enumerate(imps):
#outimp = zproj(item)
outimp = makeComposite(item)
#outimp.show()
#outname = filedir + filebase + "/" + "s" + str(counter) + ".tif"
subname = ijtool.split(item.getTitle(), " - ")[1]
#outname = filedir + filebase + "/" + subname + "_ZP.tif"
outdir = os.path.join(filedir, "processed")
outname = os.path.join(outdir, filebase + "_" + subname + "_" + str(counter) + "_Composite")
print outname
if not os.path.isdir(outdir):
os.mkdir(outdir)
fs = FileSaver(outimp)
fs.saveAsTiffStack(outname+".tif")
fs.saveAsJpeg(outname+".jpg")
#outimp = zproject(filepath)
#outimp.show()
示例12: runOneTif
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
#.........这里部分代码省略.........
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
示例13: getArg
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
# return filedir
return target_folder
filedir = getArg()
filedir = os.path.join(filedir)
filelist = os.listdir(filedir)
for afile in filelist:
if afile.lower().endswith('.lif'):
print filedir
print "..." + afile
filebase = splitext(afile)[0]
imps = getImps(os.path.join(filedir, afile))
printInfo(imps)
for (counter, item) in enumerate(imps):
outimp = zproj(item)
#outname = filedir + filebase + "/" + "s" + str(counter) + ".tif"
subname = ijtool.split(item.getTitle(), " - ")[1]
#outname = filedir + filebase + "/" + subname + "_ZP.tif"
outname = os.path.join(filedir, filebase, subname + "_ZP.tif")
print outname
outdir = os.path.join(filedir, filebase)
print outdir
if not os.path.isdir(outdir):
os.mkdir(outdir)
fs = FileSaver(outimp)
fs.saveAsTiffStack(outname)
#outimp = zproject(filepath)
#outimp.show()
示例14: analyze
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
def analyze(tempFile):
# Get currently selected image
#imp = WindowManager.getCurrentImage()
imp = IJ.openImage(tempFile)
imp.show()
dims = imp.getDimensions();
imp.setDimensions(dims[2], dims[4], dims[3]);
#----------------------------
# Create the model object now
#----------------------------
# Some of the parameters we configure below need to have
# a reference to the model at creation. So we create an
# empty model now.
model = Model()
# Send all messages to ImageJ log window.
model.setLogger(Logger.IJ_LOGGER)
#------------------------
# Prepare settings object
#------------------------
settings = Settings()
settings.setFrom(imp)
print(settings.imageFileName)
# Configure detector - We use the Strings for the keys
settings.detectorFactory = LogDetectorFactory()
settings.detectorSettings = {
'DO_SUBPIXEL_LOCALIZATION' : False,
'RADIUS' : 20.,
'TARGET_CHANNEL' : 1,
'THRESHOLD' : 0.95,
'DO_MEDIAN_FILTERING' : True,
}
# Configure spot filters - Classical filter on quality
#filter1 = FeatureFilter('QUALITY', 0.5, True)
#settings.addSpotFilter(filter1)
# Configure tracker - We want to allow merges and fusions
settings.trackerFactory = SimpleSparseLAPTrackerFactory()
settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() #probably good enough
#settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False
#settings.trackerSettings['ALLOW_TRACK_MERGING'] = False
settings.trackerSettings['LINKING_MAX_DISTANCE'] = 35.0
settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE']= 60.0
settings.trackerSettings['MAX_FRAME_GAP']= 2
# Configure track analyzers - Later on we want to filter out tracks
# based on their displacement, so we need to state that we want
# track displacement to be calculated. By default, out of the GUI,
# not features are calculated.
# The displacement feature is provided by the TrackDurationAnalyzer.
settings.addTrackAnalyzer(TrackDurationAnalyzer())
#-------------------
# Instantiate plugin
#-------------------
trackmate = TrackMate(model, settings)
ok = trackmate.process()
if not ok:
sys.exit(str(trackmate.getErrorMessage()))
#----------------
# Display results
#----------------
selectionModel = SelectionModel(model)
displayer = HyperStackDisplayer(model, selectionModel, imp)
displayer.render()
displayer.refresh()
# Echo results with the logger we set at start:
model.getLogger().log(str(model))
print(str(settings))
filename = os.path.splitext(settings.imageFileName)
pathname = settings.imageFolder + "" + filename[0] + "tracks.xml"
guicontroller = TrackMateGUIController(trackmate)
newFile = File(pathname)
ExportTracksToXML(guicontroller).export(model, settings, newFile)
actionObject = CaptureOverlayAction()
actionObject.execute(trackmate)
imp = WindowManager.getCurrentImage()
fileSaver = FileSaver(imp)
fileSaver.saveAsTiffStack(settings.imageFolder + "" + filename[0] + "overlay.tif")
WindowManager.closeAllWindows()
guicontroller.quit()
selectionModel.clearSelection();
model.clearTracks(1)
示例15: run
# 需要导入模块: from ij.io import FileSaver [as 别名]
# 或者: from ij.io.FileSaver import saveAsTiffStack [as 别名]
#.........这里部分代码省略.........
#try usinf ImageStack
#myImageStack = imp.getImageStack()
#eventuallly just call imp.getProp(str) which Returns the value from the "Info"
#in the future IJ.openImagehavewant to have option to scale down to 512X512
#run("Scale...", "x=- y=- z=1.0 width=512 height=512 depth=196 interpolation=Bilinear average process create title=20131007_a144_008_ch1-1.tif");
msgStr = " Original Image is: " + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
print msgStr
IJ.log(msgStr)
if imp.getBitDepth() == 16:
msgStr = " Converting to 8-bit..."
print msgStr
IJ.log(msgStr)
IJ.run("8-bit")
if numberOfChannels == 2:
msgStr = " deinterleaving"
print msgStr
IJ.run("Deinterleave", "how=2"); #makes 2 window
#
#ch2
imp2 = IJ.getImage()
fs = FileSaver(imp2)
msgStr = " ch2: Saving deinterleaved 8bit File to: " + outPath2
print msgStr
IJ.log(msgStr)
numSlices = imp2.getNSlices()
if (numSlices>1):
fs.saveAsTiffStack(outPath2)
else:
fs.saveAsTiff(outPath2)
#max, ch2
if (numSlices>1):
maxCmdParams = 'start=1' + ' stop=' + str(numSlices) + ' projection=[Max Intensity]'
IJ.run("Z Project...", maxCmdParams)
#impMax2 = IJ.getImage()
print " Saving 8bit Max File to", outMaxPath2
impMax2 = IJ.getImage()
fs = FileSaver(impMax2)
fs.saveAsTiff(outMaxPath2)
impMax2.changes = 0
impMax2.close()
numSaved += 1
imp2.changes = 0
imp2.close()
#
#ch1
imp1 = IJ.getImage()
fs = FileSaver(imp1)
msgStr = " ch1: Saving deinterleaved 8bit File to" + outPath1
print msgStr
numSlices = imp1.getNSlices()
if (numSlices>1):
fs.saveAsTiffStack(outPath1)
else: