def process_pi_signal(path, position, unsynchronized=True): if unsynchronized: path_signal = path + "\\pi" path_signal_before = path_signal + "\\before" path_signal_after = path_signal + "\\after" path_signal_merged = path_signal + "\\merged" path_imp_before = path_signal_before + "\\pi_in-focusxy%sc1.tif" % position path_imp_after = path_signal_after + "\\pixy%sc1.tif" % position path_imp_merged = path_signal_merged + "\\merged.tif" path_imp_merged_sub = path_signal_merged + "\\merged_sub.tif" imp1 = IJ.openImage(path_imp_before) imp1.show() imp2 = IJ.openImage(path_imp_after) imp2.show() zp1 = ZProjector(imp1) zp1.setMethod(ZProjector.AVG_METHOD) zp1.doProjection() zpimp1 = zp1.getProjection() zp2 = ZProjector(imp2) zp2.setMethod(ZProjector.AVG_METHOD) zp2.doProjection() zpimp2 = zp2.getProjection() imp_sub1 = ImageCalculator().run("Subtract create stack", imp1, zpimp1) imp_sub1.show() imp_sub2 = ImageCalculator().run("Subtract create stack", imp2, zpimp2) imp_sub2.show() concatenate_files(imp1, imp2, path_imp_merged) concatenate_files(imp_sub1, imp_sub2, path_imp_merged_sub) else: path_signal = path + "\\pi\\seq0002xy%sc1.tif" % position path_sub = path + "\\pi\\sub.tif" imp = IJ.openImage(path_signal) imp.show() zp = ZProjector(imp) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() imp_sub = ImageCalculator().run("Subtract create stack", imp, zpimp) imp_sub.show() IJ.saveAs(imp_sub, "Tiff", path_sub) imp.changes = False imp.close() zpimp.changes = False zpimp.close() imp_sub.changes = False imp_sub.close()
def maxZprojection(stackimp): '''copied from EMBL CMCI python-ImageJ cookbook.''' zp = ZProjector(stackimp) zp.setMethod(ZProjector.MAX_METHOD) zp.doProjection() zpimp = zp.getProjection() return zpimp
def getMIP(stackImp): """ Create a maximum intensity projection (MIP) from an ImagePlus stack @return ImagePlus maximum projection """ zp = ZProjector(stackImp) zp.setMethod(ZProjector.MAX_METHOD) zp.setStopSlice(stackImp.getNSlices()) zp.doHyperStackProjection(False) return zp.getProjection()
def saveMaxProject(self, destFolder=''): # ch1 if self.imp_ch1: # make max project zp = ZProjector(self.imp_ch1) zp.setMethod(ZProjector.MAX_METHOD) zp.doProjection() zimp = zp.getProjection() # save fs = FileSaver(zimp) bPrintLog('saveMaxProject():' + self.savePathMax_ch1, 3) fs.saveAsTiff(self.savePathMax_ch1) # ch2 if self.imp_ch2: # make max project zp = ZProjector(self.imp_ch2) zp.setMethod(ZProjector.MAX_METHOD) zp.doProjection() zimp = zp.getProjection() # save fs = FileSaver(zimp) bPrintLog('saveMaxProject():' + self.savePathMax_ch2, 3) fs.saveAsTiff(self.savePathMax_ch2) # ch1 if self.imp_ch3: # make max project zp = ZProjector(self.imp_ch3) zp.setMethod(ZProjector.MAX_METHOD) zp.doProjection() zimp = zp.getProjection() # save fs = FileSaver(zimp) bPrintLog('saveMaxProject():' + self.savePathMax_ch3, 3) fs.saveAsTiff(self.savePathMax_ch3)
def projectionImage(imp): """Returns the MIP of the specified ImagePlus (a composite stack)""" from ij.plugin import ZProjector roi_exists = imp.getRoi() is not None imp.deleteRoi() zp = ZProjector(imp) zp.setMethod(ZProjector.MAX_METHOD) zp.setStartSlice(1) zp.setStopSlice(imp.getNSlices()) zp.doHyperStackProjection(True) mip_imp = zp.getProjection() mip_imp.setCalibration(imp.getCalibration()) if roi_exists: mip_imp.restoreRoi() return mip_imp
def project_z(imp, method): zp = ZProjector(imp) if method=="max": zp.setMethod(ZProjector.MAX_METHOD) if method=="sum": zp.setMethod(ZProjector.SUM_METHOD) zp.setStopSlice(imp.getNSlices()) zp.doHyperStackProjection(True) zpimp = zp.getProjection() #IJ.run(imp, "Z Project...", "projection=[Max Intensity] all"); #impout = IJ.getImage() return zpimp
def Zproj(stackimp, method, z_ind, z_range): # Gets a stack and max project it. # imp= stackimp.duplicate() zp = ZProjector(stackimp) if method == "MAX": print "MAX" zp.setMethod(ZProjector.MAX_METHOD) elif method == "SUM": print "SUM" zp.setMethod(ZProjector.MAX_METHOD) print "+/-", int(z_range / 2), "of z-index", z_ind zp.setStartSlice(z_ind - int(z_range / 2)) zp.setStopSlice(z_ind + int(z_range / 2)) zp.doProjection() zpimp = zp.getProjection() return zpimp
def BackgroundFilter(imp, projection_method = "Median"): title = imp.getTitle() #Make a dict containg method_name:const_fieled_value pairs for the projection methods methods_as_strings=['Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'] methods_as_const=[ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD] method_dict=dict(zip(methods_as_strings, methods_as_const)) #The Z-Projection magic happens here through a ZProjector object zp = ZProjector(imp) zp.setMethod(method_dict[projection_method]) zp.doProjection() outstack = imp.createEmptyStack() outstack.addSlice(zp.getProjection().getProcessor()) imp2 = ImagePlus(title+'_'+projection_method, outstack) out = ImageCalculator().run("Subtract create 32-bit stack", imp, imp2) return out
def process_caspase_signal(path_signal, path_imp, path_imp_out): path_imp = path_signal + path_imp imp = IJ.openImage(path_imp) imp.show() zp = ZProjector(imp) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() imp_sub = ImageCalculator().run("Subtract create stack", imp, zpimp) imp_sub.show() IJ.saveAs(imp_sub, "Tiff", path_signal + path_imp_out) imp.changes = False imp.close() imp_sub.changes = False imp_sub.close()
def Zproj(stackimp,method,z_ind,z_range): """ Gets a single channel z-stack as imp and max project it using the provided method. stackimp(ImagePlus): a single channel z-stack as ImagePlus object z_index(int): The central stack number z_range(int): The total number of stacks surrounding the z_index to indclude """ from ij.plugin import ZProjector # imp= stackimp.duplicate() zp = ZProjector(stackimp) if method=="MAX": print "MAX" zp.setMethod(ZProjector.MAX_METHOD) elif method=="SUM": zp.setMethod(ZProjector.MAX_METHOD) zp.setStartSlice(z_ind-int(z_range/2)) zp.setStopSlice(z_ind+int(z_range/2)) zp.doProjection() zpimp = zp.getProjection() return zpimp
def subtractzproject(imp, projectionMethod="Median"): """This function takes an input stack, and subtracts a projection from the whole stack from each individual frame. Thereby, everything that is not moving in a timeseries is filtered away. Args: imp (ImagePlus): An input stack as ImagePlus object. projectionMethod (str, optional): Choose the projection method. Options are 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'. Defaults to "Median". Returns: ImagePlus: The resulting stack. """ #Start by getting the active image window and get the current active channel and other stats cal = imp.getCalibration() title = imp.getTitle() # Define a dictionary containg method_name:const_fieled_value pairs for the projection methods. methods_as_strings = [ 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median' ] methods_as_const = [ ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD ] method_dict = dict(zip(methods_as_strings, methods_as_const)) # Run Z-Projection. zp = ZProjector(imp) zp.setMethod(method_dict[projectionMethod]) zp.doProjection() impMedian = zp.getProjection() # Subtract Z-Projection and return output ImagePlus. impout = ImageCalculator().run("Subtract create 32-bit stack", imp, impMedian) impout.setCalibration(cal) return impout
def saveMaxProject(self, destFolder=''): channelNumber = 1 for imp in self.channelImp: if not destFolder: destFolder = os.path.join(self.enclosingPath, self.enclosingfolder + '_tif', 'max') if not os.path.isdir(destFolder): os.makedirs(destFolder) # make max project zp = ZProjector(imp) zp.setMethod(ZProjector.MAX_METHOD) zp.doProjection() zimp = zp.getProjection() # save saveFile = 'max_' + os.path.splitext(self.filename)[0] + '_ch' + str(channelNumber) + '.tif' savePath = os.path.join(destFolder, saveFile) fs = FileSaver(zimp) bPrintLog('saveMaxProject():' + savePath, 3) fs.saveAsTiff(savePath) channelNumber += 1
def startTracking(filepath, fdir, ffile, filename): outpath = fdir troutpath = fdir + separator + ffile + separator + "tracked" + separator stackoutpath = fdir + separator + ffile + separator + "stacks" + separator pixwidth = 0.647 interval_sec = 600 #pr if "141006" in fdir: interval_sec = 600 elif "141117" in fdir: interval_sec = 300 elif "141215" in fdir: interval_sec = 300 if not os.path.isdir(outpath): os.mkdir(outpath) if not os.path.isdir(troutpath): os.mkdir(troutpath) if not os.path.isdir(stackoutpath): os.mkdir(stackoutpath) print 'filepath: ', filepath #pr print 'fdir: ', fdir #pr print 'ffile: ', ffile #pr IJ.run("Image Sequence...", "open=" + filepath + " file=" + filename + " sort") #pr #IJ.run("Image Sequence...", "open=" + filepath + " file=molm sort"); #pr imp = WindowManager.getCurrentImage() imptitle = imp.getTitle() nframes = imp.getNSlices() IJ.run( imp, "Properties...", "channels=1 slices=1 frames=" + str(nframes) + " unit=inch pixel_width=" + str(pixwidth) + " pixel_height=" + str(pixwidth) + " voxel_depth=1.0000 frame=[" + str(interval_sec) + " sec]") IJ.run(imp, "Duplicate...", "title=" + imptitle + "_dup duplicate") imp_dup = WindowManager.getImage(imptitle + "_dup") IJ.run(imp_dup, "Gaussian Blur...", "sigma=50 stack") ic = ImageCalculator() imp_corr = ic.run("Divide create 32-bit stack", imp, imp_dup) imp_corr.setTitle(imptitle + "_corrected") imp_corr.show() imp.changes = False imp.close() imp_dup.changes = False imp_dup.close() IJ.run(imp_corr, "8-bit", "") IJ.run( imp_corr, "Normalize Local Contrast", "block_radius_x=100 block_radius_y=100 standard_deviations=1 stretch stack" ) IJ.saveAs(imp_corr, "Tiff", stackoutpath + separator + imptitle + "_corrected.tif") IJ.run(imp_corr, "Duplicate...", "title=" + imptitle + "_bg duplicate") imp_bg = WindowManager.getImage(imptitle + "_bg") #Prefs.blackBackground = True; IJ.setAutoThreshold(imp_bg, "MinError dark") IJ.run(imp_bg, "Convert to Mask", "stack") IJ.run(imp_bg, "Analyze Particles...", "size=10000-Infinity show=Masks stack") imp_bg.changes = False imp_bg.close() imp_bgmask = WindowManager.getImage("Mask of " + imptitle + "_bg") ic = ImageCalculator() imp_corr_wobg = ic.run("Subtract create stack", imp_corr, imp_bgmask) imp_corr_wobg.setTitle(imptitle + "_corrected_womask") imp_corr_wobg.show() IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask.tif") #pr # pr: substract average frames zp = ZProjector(imp_corr_wobg) zp.setMethod(ZProjector.AVG_METHOD) zp.doProjection() zpimp = zp.getProjection() zpimp.show() imp_corr_wobg_sub = ImageCalculator().run("Subtract create stack", imp_corr_wobg, zpimp) imp_corr_wobg_sub.show() #imp_corr_wobg.changes = False #imp_corr_wobg.close() # pr: subtract average frames (END) IJ.saveAs( imp_corr_wobg_sub, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask_substracted.tif") #pr IJ.saveAs( zpimp, "Tiff", stackoutpath + separator + imptitle + "_corrected_womask_avg.tif") #commented out: pr #IJ.saveAs(imp_corr_wobg, "Tiff", stackoutpath+separator+imptitle+"_corrected_womask.tif"); IJ.saveAs(imp_bgmask, "Tiff", stackoutpath + separator + imptitle + "_bgmask.tif") print(stackoutpath + separator + imptitle + "_corrected_womask_substracted.tif") print(stackoutpath + separator + imptitle + "_corrected_womask_avg.tif") print(stackoutpath + separator + imptitle + "_bgmask.tif") imp_corr.changes = False imp_corr.close() imp_bgmask.changes = False imp_bgmask.close() imp_corr_wobg.changes = False imp_corr_wobg.close() #imp_corr_wobg_sub.changes = False #imp_corr_wobg_sub.close() zpimp.changes = False zpimp.close() #IJ.log(System.getProperty("os.name")) #IJ.log(fdir) return imp_corr_wobg_sub
xml = '<?xml version="1.0" encoding="utf-8"?><DyeData>' profiles=[] names=[] for idye_,imp in enumerate(imps): idye = idye_+1 # Assumes names are FILENAME+" - "+SERIESNAME names.append(imp.title.split(" - ")[1]) xml+="<Dye%d>"%(idye) # ZProject zp = ZProjector(imp) zp.setMethod(zp.MAX_METHOD) zp.doProjection() imp_mi = zp.getProjection() imp_mip = imp_mi.getProcessor() # autothreshold using the Triangle method and get the thresholds imp_mip.setAutoThreshold(AutoThresholder.Method.Triangle,True) mint = imp_mip.getMinThreshold() maxt = imp_mip.getMaxThreshold() # we don't need the MIP anymore imp_mi.close() # For each channel, get the mean value above threshold and store it profile=[] for ich in range(imp.getNChannels()): p = imp.getStack().getProcessor(ich+1)
def imageprojector(channels, timelist_unsorted, dirs): """ Projects .lif timepoints and saves in a common directory, as well as channel separated directories. """ # Defines in path path = str(Experiment) # BF Importer options = ImporterOptions() try: options.setId(path) except Exception(e): print str(e) options.setOpenAllSeries(True) options.setSplitTimepoints(True) options.setSplitChannels(True) imps = BF.openImagePlus(options) timelist = [x for item in timelist_unsorted for x in repeat(item, channels)] timelist, imps = zip(*sorted(zip(timelist, imps))) counter_C0 = -1 counter_C1 = -1 counter_C2 = -1 # Opens all images, splits channels, z-projects and saves to disk for imp in (imps): # Projection, Sum Intensity project = ZProjector() project.setMethod(ZProjector.SUM_METHOD) project.setImage(imp) project.doProjection() impout = project.getProjection() projection = impout.getTitle() try: # Saves channels to disk, # add more channels here if desired, # remember to define new counters. if "C=0" in projection: counter_C0 += 1 IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"], "Scan" + str(counter_C0).zfill(3) + "C0")) IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C0"], "Scan" + str(counter_C0).zfill(3) + "C0")) elif "C=1" in projection: counter_C1 += 1 IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"], "Scan" + str(counter_C1).zfill(3) + "C1")) IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C1"], "Scan" + str(counter_C1).zfill(3) + "C1")) elif "C=2" in projection: counter_C2 += 1 IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"], "Scan" + str(counter_C2).zfill(3) + "C2")) IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C2"], "Scan" + str(counter_C2).zfill(3) + "C2")) except IOException: print "Directory does not exist" raise IJ.log("Images projected and saved to disk")
def CheckMoment(image): #Perform a maximum projection on the stack stack = image.getStack() NSlices=image.getNSlices() #Take a fixed number of central slices i=float(NSlices-SimulationCharacteristics['CentralZSlices']) i1=math.floor(i/2) i2=math.ceil(i/2) startSlice=int(1+i1) stopSlice=int(NSlices-i2) p=bool(1) proj = ZProjector() proj.setMethod(ZProjector.MAX_METHOD) proj.setImage(image) proj.setStartSlice(startSlice) proj.setStopSlice(stopSlice) proj.doHyperStackProjection(p) imageMax = proj.getProjection() imageMax.show() stack = imageMax.getStack() n_slices= stack.getSize() #Get a Segmentation Mask List for every frame in the stack RoiList=[] RoiRatioList=[] for index in range(1, n_slices+1): ip = stack.getProcessor(index).convertToFloat() boundRoi=SegmentMask(ip) mask=boundRoi.getMask() PixelsMask=mask.getPixels() r=(-1)*float(sum(PixelsMask))/(ip.height*ip.width) RoiList.append(boundRoi) RoiRatioList.append(r) # print(RoiRatioList) #Optimize the Roi List. No 1.0 ratios AllRois1=all(item == 1.0 for item in RoiRatioList) NFrames=len(RoiRatioList) if not AllRois1: for i in range(NFrames): if RoiRatioList[i]==1.0 or RoiList[i]==None: #Find the next value that is not 1.0 NearestNot1=-1 prevIndex=i-1 nextIndex=i+1 Token=True #To run through the list alternating positions while prevIndex>=0 or nextIndex<NFrames: if prevIndex>0 and Token: if RoiRatioList[prevIndex]<0.9999: NearestNot1=prevIndex break else: prevIndex-=1 if nextIndex<NFrames:Token=False continue if nextIndex<NFrames: if RoiRatioList[nextIndex]<0.9999: NearestNot1=nextIndex break else: nextIndex+=1 if prevIndex>0: Token=True continue if NearestNot1!=-1: #Change RoiList and RoiRationList for the NearestNot1 element RoiList[i]=RoiList[NearestNot1] RoiRatioList[i]=RoiRatioList[NearestNot1] else: AllRois1=True print("No avaliable segmentation") if not AllRois1: RoiListMin=ModifyRoiList(RoiRatioList,RoiList) else: RoiListMin=[ None for i in range(len(RoiList))] #Find Optimum Scale for the Wavelet Gamma=endosomeCharacteristics['Gamma_media'] To=endosomeCharacteristics['A_media'] index=1 #Image 1 ipOrig = stack.getProcessor(index).convertToFloat() boundRoi=RoiListMin[0] MaxAmp,Ropt=AmplificationCurveMax(ipOrig,To,Gamma,boundRoi) print("Choosen Scale",Ropt) Moment3Array=[] for index in range(1,n_slices+1): print("time:"+str(index)) ip = stack.getProcessor(index).convertToFloat() boundRoi=RoiListMin[index-1] Skew=GetSigmaWavelet(ip,Ropt,boundRoi) Moment3Array.append(Skew) return Moment3Array
def maxZprojection(stackimp): zp = ZProjector(stackimp) zp.setMethod(ZProjector.MAX_METHOD) zp.doProjection() zpimp = zp.getProjection() return (zpimp)
def processFile(filename, inDir, outDir, dichroics, mergeList): if mergeList is None: merge = False else: merge = True filenameExExt = os.path.splitext(filename)[0] filepath = inDir + filename # parse metadata reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(filepath) numChannels = reader.getSizeC() numSlices = reader.getSizeZ() numFrames = reader.getSizeT() seriesCount = reader.getSeriesCount() globalMetadata = reader.getGlobalMetadata() seriesMetadata = reader.getSeriesMetadata() objLensName = globalMetadata['- Objective Lens name #1'] areaRotation = float(seriesMetadata['area rotation #1']) acquisitionValueRotation = float(seriesMetadata['acquisitionValue rotation #1']) if 'regionInfo rotation #1' in seriesMetadata: regionInfoRotation = float(seriesMetadata['regionInfo rotation #1']) else: regionInfoRotation = float(0) totalRotation = areaRotation + regionInfoRotation physSizeX = omeMeta.getPixelsPhysicalSizeX(0) physSizeY = omeMeta.getPixelsPhysicalSizeY(0) pxSizeX = physSizeX.value(UNITS.MICROM) pxSizeY = physSizeY.value(UNITS.MICROM) # log metadata IJ.log("\nMETADATA") #IJ.log("Filename: " + filepath) IJ.log("Number of series: " + str(seriesCount)) IJ.log("Number of channels: " + str(numChannels)) IJ.log("Number of frames: " + str(numFrames)) IJ.log("Number of slices: " + str(numSlices)) IJ.log("Objective lens: " + objLensName) IJ.log("FOV rotation: " + str(areaRotation)) IJ.log("ROI rotation: " + str(regionInfoRotation)) IJ.log("Total rotation: " + str(totalRotation)) IJ.log("Pixel size:") IJ.log("\t\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol()) IJ.log("\t\tY = " + str(physSizeY.value()) + " " + physSizeY.unit().getSymbol()) if merge: tifDir = outDir + "." + str(datetime.now()).replace(" ", "").replace(":", "") + "/" if not os.path.exists(tifDir): os.makedirs(tifDir) IJ.log("\nCreated temporary folder: " + tifDir + "\n") else: IJ.log("Unable to create temporary folder!\n") else: tifDir = outDir + filenameExExt + "/" if not os.path.exists(tifDir): os.makedirs(tifDir) IJ.log("\nCreated subfolder: " + tifDir + "\n") else: IJ.log("\nSubfolder " + tifDir + " already exists.\n") # correct images tifFilePaths = [] for i in range(numChannels): ip = extractChannel(oirFile=filepath, ch=i) if dichroics[i] == "DM1": IJ.log("Channel " + str(i+1) + " was imaged using DM1, so no correction required.") else: offsets = getOffset(obj=objLensName,dm=dichroicDict[dichroics[i]]) xom = offsets['x'] yom = offsets['y'] if abs(totalRotation) > 0.1: rotOff = rotateOffset(x=xom, y=yom, angle=-totalRotation) xom = rotOff['x'] yom = rotOff['y'] xop = int(round(xom/pxSizeX)) yop = int(round(yom/pxSizeY)) IJ.log("Channel " + str(i+1) + " offsets") IJ.log("\t\tMicrometres") IJ.log("\t\t\t\tx = " + str(xom)) IJ.log("\t\t\t\ty = " + str(yom)) IJ.log("\t\tPixels") IJ.log("\t\t\t\tx = " + str(xop)) IJ.log("\t\t\t\ty = " + str(yop)) IJ.run(ip, "Translate...", "x=" + str(-xop) + " y=" + str(-yop) + " interpolation=None stack") tifFilePath = tifDir + filenameExExt + "_ch_"+str(i+1)+".tif" tifFilePaths.append(tifFilePath) if os.path.exists(tifFilePath): IJ.log("\nOutput file exists: " + tifFilePath) IJ.log("Rerun plugin choosing a different output folder") IJ.log("or delete file and then rerun plugin.") IJ.log("Image processing terminated!\n") return FileSaver(ip).saveAsTiff(tifFilePath) if merge: max_list = [] for i in range(len(mergeList)): if mergeList[i] != None: mergeList[i] = readSingleChannelImg(tifFilePaths[mergeList[i]]) channel = mergeList[i]#https://python.hotexamples.com/examples/ij.plugin/RGBStackMerge/mergeChannels/python-rgbstackmerge-mergechannels-method-examples.html projector = ZProjector(channel) projector.setMethod(ZProjector.MAX_METHOD) projector.doProjection() max_list.append(projector.getProjection()) merged = RGBStackMerge.mergeChannels(mergeList, False) merged_max = RGBStackMerge.mergeChannels(max_list, False) mergedChannelFilepath = outDir + filenameExExt + ".tif" maxMergedChannelFilepath = outDir + filenameExExt + "_max.tif" if os.path.exists(mergedChannelFilepath): IJ.log("\nOutput file exists: " + mergedChannelFilepath) IJ.log("Rerun plugin choosing a different output folder") IJ.log("or delete file and then rerun plugin.") IJ.log("Image processing terminated!\n") FileSaver(merged).saveAsTiff(mergedChannelFilepath) FileSaver(merged_max).saveAsTiff(maxMergedChannelFilepath) for tf in tifFilePaths: os.remove(tf) os.rmdir(tifDir) IJ.log("\nFinished processing file:\n" + filepath + "\n") if merge: IJ.log("Image file with channels aligned:\n" + outDir + filenameExExt + ".tif\n") else: IJ.log("Aligned images (one tiff file for each channel) can be found in:\n" + tifDir + "\n")
def ColMigBud(): def setupDialog(imp): gd = GenericDialog("Collective migration buddy options") gd.addMessage("Collective migration buddy 2.0, you are analyzing: " + imp.getTitle()) calibration = imp.getCalibration() if (calibration.frameInterval > 0): default_interval = calibration.frameInterval default_timeunit = calibration.getTimeUnit() else: default_interval = 8 default_timeunit = "min" gd.addNumericField("Frame interval:", default_interval, 2) # show 2 decimals gd.addCheckbox("Do you want to use a gliding window?", True) gd.addCheckbox( "Project hyperStack? (defaluts to projecting current channel only)", False) gd.addStringField("time unit", default_timeunit, 3) gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1) gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames()) gd.addNumericField("Number of frames to project in to one:", 3, 0) # show 0 decimals gd.addChoice('Method to use for frame projection:', methods_as_strings, methods_as_strings[5]) gd.showDialog() if gd.wasCanceled(): IJ.log("User canceled dialog!") return return gd #Start by getting the active image window and get the current active channel and other stats imp = WindowManager.getCurrentImage() cal = imp.getCalibration() nSlices = 1 #TODO fix this in case you want to do Z-stacks title = imp.getTitle() current_channel = imp.getChannel() #zp = ZProjector(imp) #Make a dict containg method_name:const_fieled_value pairs for the projection methods methods_as_strings = [ 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median' ] methods_as_const = [ ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD ] medthod_dict = dict(zip(methods_as_strings, methods_as_const)) # Run the setupDialog, read out and store the options gd = setupDialog(imp) frame_interval = gd.getNextNumber() time_unit = gd.getNextString() glidingFlag = gd.getNextBoolean() hyperstackFlag = gd.getNextBoolean() #Set the frame interval and unit, and store it in the ImagePlus calibration cal.frameInterval = frame_interval cal.setTimeUnit(time_unit) imp.setCalibration(cal) start_frame = int(gd.getNextNumber()) stop_frame = int(gd.getNextNumber()) #If a subset of the image is to be projected, these lines of code handle that if (start_frame > stop_frame): IJ.showMessage("Start frame > Stop frame, can't go backwards in time!") raise RuntimeException("Start frame > Stop frame!") if ((start_frame != 1) or (stop_frame != imp.getNFrames())): imp = Duplicator().run(imp, 1, nChannels, 1, nSlices, start_frame, stop_frame) no_frames_per_integral = int(gd.getNextNumber()) #the doHyperstackProjection method can't project past the end of the stack if hyperstackFlag: total_no_frames_to_project = imp.getNFrames() - no_frames_per_integral #the doProjection method can project past the end, it just adds black frames at the end #When not projecting hyperstacks, just copy the current active channel from the active image else: total_no_frames_to_project = imp.getNFrames() imp = Duplicator().run(imp, current_channel, current_channel, 1, nSlices, start_frame, stop_frame) #The Z-Projection magic happens here through a ZProjector object zp = ZProjector(imp) projection_method = gd.getNextChoice() chosen_method = medthod_dict[projection_method] zp.setMethod(chosen_method) outstack = imp.createEmptyStack() if glidingFlag: frames_to_advance_per_step = 1 else: frames_to_advance_per_step = no_frames_per_integral for frame in range(1, total_no_frames_to_project, frames_to_advance_per_step): zp.setStartSlice(frame) zp.setStopSlice(frame + no_frames_per_integral) if hyperstackFlag: zp.doHyperStackProjection(False) projected_stack = zp.getProjection().getStack() for channel in range(projected_stack.getSize()): outstack.addSlice(projected_stack.getProcessor(channel + 1)) else: zp.doProjection() outstack.addSlice(zp.getProjection().getProcessor()) #Create an image processor from the newly created Z-projection stack nChannels = imp.getNChannels() nFrames = outstack.getSize() / nChannels imp2 = ImagePlus( title + '_' + projection_method + '_' + str(no_frames_per_integral) + '_frames', outstack) imp2 = HyperStackConverter.toHyperStack(imp2, nChannels, nSlices, nFrames) imp2.show() Startmenu()
def maxZprojection(self, inputimg): zp = ZProjector(inputimg) zp.setMethod(ZProjector.MAX_METHOD) zp.doProjection() Zproj = zp.getProjection() return Zproj
def BackgroundFilter(): def setupDialog(imp): gd = GenericDialog("Toolbox options") gd.addMessage("Imagej toolbox, you are analyzing: " + imp.getTitle()) calibration = imp.getCalibration() if (calibration.frameInterval > 0): default_interval = calibration.frameInterval default_timeunit = calibration.getTimeUnit() else: default_interval = 10 default_timeunit = "sec" gd.addNumericField("Frame interval:", default_interval, 2) # show 2 decimals # gd.addCheckbox("Do you want to use a gliding window?", True) # gd.addCheckbox("Project hyperStack? (defaluts to projecting current channel only)", False) # gd.addStringField("time unit",default_timeunit, 3) # gd.addSlider("Start compacting at frame:", 1, imp.getNFrames(), 1) # gd.addSlider("Stop compacting at frame:", 1, imp.getNFrames(), imp.getNFrames()) # gd.addNumericField("Number of frames to project in to one:", 3, 0) # show 0 decimals gd.addChoice('Method to use for stack background filtering:', methods_as_strings, methods_as_strings[5]) gd.showDialog() if gd.wasCanceled(): IJ.log("User canceled dialog!") return return gd #Start by getting the active image window and get the current active channel and other stats imp = WindowManager.getCurrentImage() cal = imp.getCalibration() nSlices = 1 #TODO fix this in case you want to do Z-stacks title = imp.getTitle() current_channel = imp.getChannel() #zp = ZProjector(imp) #Make a dict containg method_name:const_fieled_value pairs for the projection methods methods_as_strings = [ 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median' ] methods_as_const = [ ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD ] method_dict = dict(zip(methods_as_strings, methods_as_const)) gd = setupDialog(imp) #The Z-Projection magic happens here through a ZProjector object zp = ZProjector(imp) projection_method = gd.getNextChoice() chosen_method = method_dict[projection_method] zp.setMethod(chosen_method) outstack = imp.createEmptyStack() zp.doProjection() outstack.addSlice(zp.getProjection().getProcessor()) imp2 = ImagePlus(title + '_' + projection_method, outstack) # imp2.show() imp3 = ImageCalculator().run("Subtract create 32-bit stack", imp, imp2) imp3.show() Startmenu()
def glidingprojection(imp, startframe=1, stopframe=None, glidingFlag=True, no_frames_per_integral=3, projectionmethod="Median"): """This function subtracts the gliding projection of several frames from the input stack. Thus, everything which moves too fast is filtered away. Args: imp (ImagePlus): Input image as ImagePlus object. startframe (int, optional): Choose a start frame. Defaults to 1. stopframe (int, optional): Choose an end frame. Defaults to None. glidingFlag (bool, optional): Should a gliding frame by frame projection be used? Defaults to True. no_frames_per_integral (int, optional): Number of frames to project each integral. Defaults to 3. projectionmethod (str, optional): Choose the projection method. Options are 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median'. Defaults to "Median". Raises: RuntimeException: Start frame > stop frame. Returns: ImagePlus: The output stack. """ # Store some image properties. cal = imp.getCalibration() width, height, nChannels, nSlices, nFrames = imp.getDimensions() title = imp.getTitle() # Some simple sanity checks for input parameters. if stopframe == None: stopframe = nFrames if (startframe > stopframe): IJ.showMessage("Start frame > Stop frame, can't go backwards in time!") raise RuntimeException("Start frame > Stop frame!") # If a subset of the image is to be projected, these lines of code handle that. if ((startframe != 1) or (stopframe != nFrames)): imp = Duplicator().run(imp, 1, nChannels, 1, nSlices, startframe, stopframe) # Define the number of frames to advance per step based on boolean input parameter glidingFlag. if glidingFlag: frames_to_advance_per_step = 1 else: frames_to_advance_per_step = no_frames_per_integral # Make a dict containg method_name:const_fieled_value pairs for the projection methods methods_as_strings = [ 'Average Intensity', 'Max Intensity', 'Min Intensity', 'Sum Slices', 'Standard Deviation', 'Median' ] methods_as_const = [ ZProjector.AVG_METHOD, ZProjector.MAX_METHOD, ZProjector.MIN_METHOD, ZProjector.SUM_METHOD, ZProjector.SD_METHOD, ZProjector.MEDIAN_METHOD ] method_dict = dict(zip(methods_as_strings, methods_as_const)) # Initialize a ZProjector object and an empty stack to collect projections. zp = ZProjector(imp) zp.setMethod(method_dict[projectionmethod]) outstack = imp.createEmptyStack() # Loop through all the frames in the image, and project that frame with the other frames in the integral. for frame in range(1, nFrames + 1, frames_to_advance_per_step): zp.setStartSlice(frame) zp.setStopSlice(frame + no_frames_per_integral) zp.doProjection() outstack.addSlice(zp.getProjection().getProcessor()) # Create an image processor from the newly created Z-projection stack # nFrames = outstack.getSize()/nChannels impout = ImagePlus( title + '_' + projectionmethod + '_' + str(no_frames_per_integral) + '_frames', outstack) impout = HyperStackConverter.toHyperStack(impout, nChannels, nSlices, nFrames) impout.setCalibration(cal) return impout
# improved with default values or min/max values. emissionWL = [0] try: for x in xrange(1,nbrChannels+1,1): WL = int(imp.getNumericProperty("Information|Image|Channel|EmissionWavelength #" + str(x).zfill(2))) emissionWL.append(WL) except ValueError: raise Exception("Couldn't find the EmissionWavelength info in the metadata") # Make the maximum intensity projection # and show it for user input. project = ZProjector() project.setMethod(ZProjector.MAX_METHOD) project.setImage(imp) project.doProjection() projection = project.getProjection() projection.show() # Wait for the user to draw a line # and check if line ROI. IJ.setTool("line"); myWait = WaitForUserDialog ("waitForUser", "Make a line with the region of interest and press OK") myWait.show() roi = projection.getRoi() # Check if roi is a line # otherwise exit if not (roi.isLine()): raise Exception("Line selection required")
if options is not None: runCamR, runCamL, CamRScale, CamLScale, BackgroundWindowStart, BackgroundWindowEnd, GridSize, TranslateR, TranslateL = options # unpack each parameter print runCamR, runCamL, CamRScale, CamLScale, BackgroundWindowStart, BackgroundWindowEnd, GridSize, TranslateR, TranslateL if runCamR: impR1 = FolderOpener.open(folder, "file=CamR sort") UID = impR1.title filepath = folder.strip(UID + '/') projectR = ZProjector(impR1) projectR.setMethod(ZProjector.AVG_METHOD) projectR.setImage(impR1) projectR.setStartSlice(int(BackgroundWindowStart)) projectR.setStopSlice(int(BackgroundWindowEnd)) projectR.doProjection() projectionR = projectR.getProjection() impR2 = ImageCalculator().run("Subtract create stack", impR1, projectionR) IJ.run(impR2, "Enhance Contrast", "saturated=0.4 process_all") IJ.run(impR2, "Set Scale...", "distance=" + str(CamRScale) + " known=1 unit=cm") IJ.run(impR2, "Grid...", "grid=Lines area=" + str(GridSize) + " color=Cyan") IJ.run(impR2, "Translate...", "x=" + str(TranslateR) + " y=0 interpolation=None stack") savepath = path.join(folder, UID + "_CR.tif") print savepath fs = FileSaver(impR2) if fs.saveAsTiffStack(savepath): print("Files saved succesfully")
#print "index=" + str(index) + "start=" + str(currStart) + " stop=" + str(currStop) if (currStart<1): currStart = 1 if (currStop>nSlices): currStop = nSlices zp = ZProjector(imp) zp.setMethod(ZProjector.MAX_METHOD) zp.setStartSlice(currStart) zp.setStopSlice(currStop) #zp.doHyperStackProjection(True) zp.doProjection() tmpProject = zp.getProjection() zImageProcessor = tmpProject.getProcessor() if (tmpProject==None): print "\tNULL ZProject" else: newStack.addSlice(origStack.getSliceLabel(index), zImageProcessor) currStart = index - userSlices currStop = index + userSlices #how the results as an image imp2 = ImagePlus("Sliding Z Project: " + imp.title + " " + "[" + str(userSlices) + "]", newStack) imp2.setCalibration(imp.getCalibration().copy()) imp2.show()