def zproj(imp): zpimp = ZP() zpimp.setImage(imp) zpimp.setMethod(zpimp.MAX_METHOD) zpimp.setStartSlice(1) zpimp.setStopSlice(imp.getNSlices()) zpimp.doHyperStackProjection(True) zpedimp = zpimp.getProjection() return zpedimp
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 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 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 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
options = getOptions() 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
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 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
for index in range(1, nSlices+1): ip = origStack.getProcessor(index) #IJ.log(str(index) + " " + ip.toString()) # output info on current slice #IJ.run(imp, "Z Project...", "start=" + str(currStart) + " stop=" + str(currStop) + " projection=[Max Intensity]") #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