def assembleChannelImagesInStacks(imageTitle, arrayOfImages, valeurSelectionDisplayMode, valeurSelectionTypeFichier): maxNumberOfChannels = len(arrayOfImages) maxNumberOfZDepth = 1; maxNumberOfTimeStamps = 1; print("assembleChannelImagesInStacks - arrayOfImages: "+str(arrayOfImages)) for channelNumber in range(len(arrayOfImages)): if valeurSelectionTypeFichier == "1 fichier par canal (NOM_FICHIER_chXX.tif)": numberOfZDepth = len(arrayOfImages[channelNumber]) if numberOfZDepth > maxNumberOfZDepth: maxNumberOfZDepth = numberOfZDepth if valeurSelectionTypeFichier == "1 fichier par canal + temps (NOM_FICHIER_tXX_chXX.tif)": numberOfZDepth = len(arrayOfImages[channelNumber]) if numberOfZDepth > maxNumberOfZDepth: maxNumberOfZDepth = numberOfZDepth for zNumber in range(len(arrayOfImages[channelNumber])): numberOfTime = len(arrayOfImages[channelNumber][zNumber]) if numberOfTime > maxNumberOfTimeStamps: maxNumberOfTimeStamps = numberOfTime if valeurSelectionTypeFichier == "1 fichier par canal et par profondeur (NOM_FICHIER_zXX_chXX.tif)": numberOfZDepth = len(arrayOfImages[channelNumber]) if numberOfZDepth > maxNumberOfZDepth: maxNumberOfZDepth = numberOfZDepth if valeurSelectionTypeFichier == "1 fichier par canal et par profondeur + temps (NOM_FICHIER_tXX_zXX_chXX.tif)": numberOfZDepth = len(arrayOfImages[channelNumber]) print(arrayOfImages[channelNumber]) if numberOfZDepth > maxNumberOfZDepth: maxNumberOfZDepth = numberOfZDepth for zNumber in range(len(arrayOfImages[channelNumber])): print(arrayOfImages[channelNumber][zNumber]) numberOfTime = len(arrayOfImages[channelNumber][zNumber]) if numberOfTime > maxNumberOfTimeStamps: maxNumberOfTimeStamps = numberOfTime hyperStack = ImageStack() #imageTitle = "HyperStack" print("C: "+str(maxNumberOfChannels)+", Z: "+str(maxNumberOfZDepth)+", T: "+str(maxNumberOfTimeStamps)) for timeNumber in range(maxNumberOfTimeStamps): for zDepthNumber in range(maxNumberOfZDepth): for channelNumber in range(maxNumberOfChannels): #print("Position: "+str(channelNumber)+", "+str(zDepthNumber)+", "+str(timeNumber)) currentImagePlus = arrayOfImages[channelNumber][zDepthNumber][timeNumber] #print("ImagePlus: "+str(currentImagePlus)) currentImagePlus.setC(channelNumber) currentImagePlus.setZ(zDepthNumber) currentImagePlus.setT(timeNumber) currentImageProcessor = currentImagePlus.getProcessor() hyperStack.addSlice(currentImageProcessor) hyperStackImagePlus = ImagePlus(imageTitle, hyperStack) #hyperStackImagePlus.show() if maxNumberOfChannels*maxNumberOfZDepth*maxNumberOfTimeStamps > 1: converter = HyperStackConverter() hyperStackImagePlus = converter.toHyperStack(hyperStackImagePlus, maxNumberOfChannels, maxNumberOfZDepth, maxNumberOfTimeStamps, valeurSelectionDisplayMode) if valeurSelectionTypeFichier == "1 fichier par canal + temps (NOM_FICHIER_tXX_chXX.tif)": hyperStackImagePlus = converter.toHyperStack(hyperStackImagePlus, maxNumberOfChannels, maxNumberOfTimeStamps, maxNumberOfZDepth, "xyctz", valeurSelectionDisplayMode); return hyperStackImagePlus
def stackprocessor(path, nChannels=4, nSlices=1, nFrames=1): imp = ImagePlus(path) imp = HyperStackConverter().toHyperStack(imp, nChannels, # channels nSlices, # slices nFrames) # frames imp = ZProjector.run(imp, "max") return imp
def slices_to_frames(hstack): ''' Reorder Hyperstack in case of slices - frames confusion ''' hc = HyperStackConverter() x, y, c, z, t = hstack.getDimensions() new_hstack = hstack # to avoid 'reference before assignment' error # more slices than frames indicate mis-placed dimensions if z > t: IJ.log('Shuffling\n' + hstack.getShortTitle() + '\n slices to frames..') new_hstack = hc.toHyperStack(hstack, c, t, z) # shuffle indices IJ.log('New dimensions: ' + str(c) + ', ' + str(t) + ', ' + str(z)) else: IJ.log(hstack.getShortTitle() + '\n needs no shuffling') return new_hstack
def hyperSC(num, istr): imp2 = impl[num] imp2 = HyperStackConverter.toHyperStack(imp2, 2, 1, 50, "xytcz", "Color") if (num - 2) < 10: numstr = "000" + str(num - 2) elif (num - 2) < 100: numstr = "00" + str(num - 2) elif (num - 2) > 99: numstr = "0" + str(num - 2) IJ.saveAs( imp2, "Tiff", "" + directory_save + title + "_R" + istr + "_Z" + numstr + ".tif")
def run_script(): SamIm = open_fli(SampleFile.getAbsolutePath()) RefIm = open_fli(ReferenceFile.getAbsolutePath()) reftau = RefIm.getStringProperty("PARAMETERS: ACQUISITION SETTINGS - RefLifetime") freq = SamIm.getStringProperty("PARAMETERS: ACQUISITION SETTINGS - Frequency") phases = SamIm.getStringProperty("FLIMIMAGE: LAYOUT - phases") phases = int(phases) timestamps = SamIm.getStringProperty("FLIMIMAGE: LAYOUT - timestamps") timestamps = int(timestamps) #put phases in z. SamIm = HyperStackConverter.toHyperStack(SamIm,1,phases,timestamps,"xyczt","grayscale") RefIm.show() SamIm.show() #go frame by frame for frame in range(1,timestamps+1): WindowManager.toFront(WindowManager.getWindow(SamIm.getTitle())) time.sleep(0.25) IJ.run("Make Substack...", "slices=1-12 frames="+str(frame)) substack = IJ.getImage() IJ.run("fdFLIM", "image1=["+substack.getTitle()+"] boolphimod=false image2=["+RefIm.getTitle()+"] tau_ref="+reftau+" freq="+freq); substack.close() if frame == 1: substack = IJ.getImage() substack.setTitle("Lifetime_Result") else: IJ.run("Concatenate...", " title=Lifetime_Result open image1=Lifetime_Result image2=Lifetimes image3=[-- None --]"); SamIm.close() RefIm.close() #Stack to Hyperstack result1 = IJ.getImage() result = HyperStackConverter.toHyperStack(result1,3,1,timestamps,"xyctz","grayscale") result1.close() #Otsu Threshold to NaN set_to_nan(result) #set range and LUT set_range_LUT(result,1,1,4,"Royal") set_range_LUT(result,2,1,4,"Royal") set_range_LUT(result,3,-1E11,1E11,"Grays") result.show()
def open_sequential_gcimages_from_folder(source, image_dimensions_czt): """use IJ "import image sequence" to open all sequential images written by the Grid/collection stitcher in a folder as virtual stack. Bio-Formats seems to have a limit in XY size. Arguments: source {string} -- directory to the imagefiles image_dimensions_czt {list} -- number of images in dimensions c,z,t Returns: nothing """ c_end = image_dimensions_czt[0] t_end = image_dimensions_czt[2] imp = FolderOpener.open(str(source), "virtual") total_images_in_stack = imp.getNSlices() z_total = total_images_in_stack / ( c_end * t_end ) # needs to be inferred rather than taken from raw image metadata as the G/C-stitcher might have added z-planes imp2 = HyperStackConverter.toHyperStack( imp, c_end, z_total, t_end, "default", "Color") # xyczt (default), stays virtual imp2.show()
image.show() if auto_thresh: con = ImageConverter(image) con.convertToGray8() IJ.run( image, "Auto Local Threshold", "method=Bernsen radius=15 parameter_1=0 parameter_2=0 white stack") #image = CompositeImage(image_two) #image = IJ.getImage() z_slices = image.getDimensions()[3] / 2 print( "order=xyczt(default) channels=2 slices=" + str(z_slices) + " frames=1 display=Color", image.getDimensions()) image_two = HyperStackConverter.toHyperStack(image, 2, z_slices, 1) image = CompositeImage(image_two) image.show() rt = run_comdet(image) rt.save(directory + "/" + filename + "_results.csv") image = IJ.getImage() if auto_cell: mask = generate_mask(image_green, auto_cell_thresh) fs = FileSaver(mask) filepath = directory + "/" + filename + "_mask.tiff" fs.saveAsTiff(filepath) rest = ResultsTable.open(directory + "/" + filename + "_results.csv")
def main(): # setup Prefs.blackBackground = True params = Parameters() params.load_last_params() # select folders if params.last_input_path is not None: DirectoryChooser.setDefaultDirectory(params.last_input_path) dc = DirectoryChooser("Choose root folder containing data for analysis") input_folder = dc.getDirectory() params.last_input_path = input_folder if input_folder is None: raise KeyboardInterrupt("Run canceled") if params.last_output_path is not None: DirectoryChooser.setDefaultDirectory( os.path.dirname(params.last_output_path)) dc = DirectoryChooser("choose location to save output") output_folder = dc.getDirectory() timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S') output_folder = os.path.join(output_folder, (timestamp + ' output')) params.last_output_path = output_folder os.mkdir(output_folder) analysis_mode = choose_analysis_mode(params) params.last_analysis_mode = analysis_mode params.persist_parameters() # load image(s): files_lst = [ f for f in os.listdir(input_folder) if os.path.splitext(f)[1] == '.tif' ] out_statses = [] for f in files_lst: print("Working on image {}...".format(os.path.splitext(f)[0])) imp = IJ.openImage(os.path.join(input_folder, f)) metadata = import_iq3_metadata( os.path.join(input_folder, os.path.splitext(f)[0] + '.txt')) imp = HyperStackConverter.toHyperStack(imp, 3, imp.getNSlices() // 3, 1, "Color") imp = ZProjector.run(imp, "max") imp.setC(3) IJ.run(imp, "Blue", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.setC(2) IJ.run(imp, "Red", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.setC(1) IJ.run(imp, "Green", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.show() imp.setDisplayMode(IJ.COMPOSITE) cal = imp.getCalibration() cal.setUnit(metadata["y_unit"]) cal.pixelWidth = metadata["x_physical_size"] cal.pixelHeight = metadata["y_physical_size"] imp.setCalibration(cal) if analysis_mode == "GFP intensity": out_stats = gfp_analysis(imp, f, output_folder) elif analysis_mode == "Manual": out_stats = manual_analysis(imp, f, output_folder) out_statses.extend(out_stats) print("Current total number of cells identified: {}".format( len(out_statses))) # get # nuclei per "cell" params.save_parameters_to_json( os.path.join(output_folder, "parameters used.json")) WaitForUserDialog( "Done", "Done, having analysed {} cells in total!".format( len(out_statses))).show() return
i+=1 arrayOfChannels.append(timeImagePluses) #print("arrayOfChannels: "+str(arrayOfChannels)) #print("Finished separating by channels") shuffledHyperStackImageStack = ImageStack() for timeStamp in range(totalTime): for zDepth in range(zDepthByChannel): for channelNumber in range(numberOfChannels): timeImagePlus = arrayOfChannels[channelNumber][timeStamp] print("timeImagePlus: "+str(timeImagePlus)) #timeImagePlus.show() timeImageStack = timeImagePlus.getStack() timeImageStackSize = timeImageStack.getSize() timeImageSliceProcessor = timeImageStack.getProcessor(zDepth+1) shuffledHyperStackImageStack.addSlice(timeImageSliceProcessor) """ shuffledHyperStackImagePlus = ImagePlus(imageTitle, shuffledHyperStackImageStack) #shuffledHyperStackImagePlus.show() shuffledHyperStackImagePlus = HyperStackConverter.toHyperStack(shuffledHyperStackImagePlus, nFirst, nMiddle, nLast, "Color") return shuffledHyperStackImagePlus IJ.log('\\Clear') #efface le contenu de la console hyperStackImagePlus = IJ.openImage() hyperStackImagePlus.show() #shuffledHyperStackImagePlus = shuffleImagestoCZT(hyperStackImagePlus, "CTZ") HyperStackConverter.shuffle(hyperStackImagePlus, 1) hyperStackImagePlus.show()
def register_hyperstack(imp, shifts, target_folder, virtual): """ Applies the shifts to all channels in the hyperstack.""" # Compute bounds of the new volume, # which accounts for all translations: minx, miny, minz, maxx, maxy, maxz = compute_min_max(shifts) # Make shifts relative to new canvas dimensions # so that the min values become 0,0,0 for shift in shifts: shift.x -= minx shift.y -= miny shift.z -= minz #print "shifts relative to new dimensions:" #for s in shifts: # print s.x, s.y, s.z # new canvas dimensions:r width = imp.width + maxx - minx height = maxy - miny + imp.height slices = maxz - minz + imp.getNSlices() print "New dimensions:", width, height, slices # Prepare empty slice to pad in Z when necessary empty = imp.getProcessor().createProcessor(width, height) # if it's RGB, fill the empty slice with blackness if isinstance(empty, ColorProcessor): empty.setValue(0) empty.fill() # Write all slices to files: stack = imp.getStack() if virtual is False: registeredstack = ImageStack(width, height, imp.getProcessor().getColorModel()) names = [] for frame in range(1, imp.getNFrames()+1): shift = shifts[frame-1] #print "frame",frame,"correcting drift",-shift.x-minx,-shift.y-miny,-shift.z-minz IJ.log(" frame "+str(frame)+" correcting drift "+str(-shift.x-minx)+","+str(-shift.y-miny)+","+str(-shift.z-minz)) fr = "t" + zero_pad(frame, len(str(imp.getNFrames()))) # Pad with empty slices before reaching the first slice for s in range(shift.z): ss = "_z" + zero_pad(s + 1, len(str(slices))) # slices start at 1 for ch in range(1, imp.getNChannels()+1): name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif" names.append(name) if virtual is True: currentslice = ImagePlus("", empty) currentslice.setCalibration(imp.getCalibration().copy()) currentslice.setProperty("Info", imp.getProperty("Info")) FileSaver(currentslice).saveAsTiff(target_folder + "/" + name) else: empty = imp.getProcessor().createProcessor(width, height) registeredstack.addSlice(str(name), empty) # Add all proper slices stack = imp.getStack() for s in range(1, imp.getNSlices()+1): ss = "_z" + zero_pad(s + shift.z, len(str(slices))) for ch in range(1, imp.getNChannels()+1): ip = stack.getProcessor(imp.getStackIndex(ch, s, frame)) ip2 = ip.createProcessor(width, height) # potentially larger ip2.insert(ip, shift.x, shift.y) name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif" names.append(name) if virtual is True: currentslice = ImagePlus("", ip2) currentslice.setCalibration(imp.getCalibration().copy()) currentslice.setProperty("Info", imp.getProperty("Info")); FileSaver(currentslice).saveAsTiff(target_folder + "/" + name) else: registeredstack.addSlice(str(name), ip2) # Pad the end for s in range(shift.z + imp.getNSlices(), slices): ss = "_z" + zero_pad(s + 1, len(str(slices))) for ch in range(1, imp.getNChannels()+1): name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif" names.append(name) if virtual is True: currentslice = ImagePlus("", empty) currentslice.setCalibration(imp.getCalibration().copy()) currentslice.setProperty("Info", imp.getProperty("Info")) FileSaver(currentslice).saveAsTiff(target_folder + "/" + name) else: registeredstack.addSlice(str(name), empty) if virtual is True: # Create virtual hyper stack registeredstack = VirtualStack(width, height, None, target_folder) for name in names: registeredstack.addSlice(name) registeredstack_imp = ImagePlus("registered time points", registeredstack) registeredstack_imp.setCalibration(imp.getCalibration().copy()) registeredstack_imp.setProperty("Info", imp.getProperty("Info")) registeredstack_imp = HyperStackConverter.toHyperStack(registeredstack_imp, imp.getNChannels(), len(names) / (imp.getNChannels() * imp.getNFrames()), imp.getNFrames(), "xyczt", "Composite"); return registeredstack_imp
# Result visualisation if (not stillValid): impSphereProjection = clijx.pull(sphereMaxProjection); IJ.run(impSphereProjection, "Enhance Contrast", "saturated=0.3"); impCircles = clijx.pull(circles); impCircles.setDisplayRange(0, 1); IJ.run(impSphereProjection, "8-bit", ""); IJ.run(impCircles, "8-bit", ""); stack = ImageStack(impSphereProjection.getWidth(), impSphereProjection.getHeight()); stack.addSlice(impSphereProjection.getProcessor()); stack.addSlice(impCircles.getProcessor()); tempImp = ImagePlus("Cylinder Maximum Projection + spots", stack); tempImp = HyperStackConverter.toHyperStack(tempImp, 2, 1, 1); if (tempImp.getNChannels() == 2): tempImp.setC(1); IJ.run(tempImp, "Magenta", ""); tempImp.setC(2); tempImp.setDisplayRange(0, 1); RGBStackConverter.convertToRGB(tempImp); if (resultCylinderMaxProjection is None): resultCylinderMaxProjection = tempImp; else: resultCylinderMaxProjection.setProcessor(tempImp.getProcessor()); resultCylinderMaxProjection.show(); resultCylinderMaxProjection.updateAndDraw();
def register_hyperstack_subpixel(imp, channel, shifts, target_folder, virtual): """ Takes the imp, determines the x,y,z drift for each pair of time points, using the preferred given channel, and outputs as a hyperstack. The shifted image is computed using TransformJ allowing for sub-pixel shifts using interpolation. This is quite a bit slower than just shifting the image by full pixels as done in above function register_hyperstack(). However it significantly improves the result by removing pixel jitter. """ # Compute bounds of the new volume, # which accounts for all translations: minx, miny, minz, maxx, maxy, maxz = compute_min_max(shifts) # Make shifts relative to new canvas dimensions # so that the min values become 0,0,0 for shift in shifts: shift.x -= minx shift.y -= miny shift.z -= minz # new canvas dimensions: width = int(imp.width + maxx - minx) height = int(maxy - miny + imp.height) slices = int(maxz - minz + imp.getNSlices()) print "New dimensions:", width, height, slices # prepare stack for final results stack = imp.getStack() if virtual is True: names = [] else: registeredstack = ImageStack(width, height, imp.getProcessor().getColorModel()) # prepare empty slice for padding empty = imp.getProcessor().createProcessor(width, height) IJ.showProgress(0) # get raw data as stack stack = imp.getStack() # loop across frames for frame in range(1, imp.getNFrames()+1): IJ.showProgress(frame / float(imp.getNFrames()+1)) fr = "t" + zero_pad(frame, len(str(imp.getNFrames()))) # for saving files in a virtual stack # get and report current shift shift = shifts[frame-1] print "frame",frame,"correcting drift",-shift.x-minx,-shift.y-miny,-shift.z-minz IJ.log(" frame "+str(frame)+" correcting drift "+str(round(-shift.x-minx,2))+","+str(round(-shift.y-miny,2))+","+str(round(-shift.z-minz,2))) # loop across channels for ch in range(1, imp.getNChannels()+1): tmpstack = ImageStack(width, height, imp.getProcessor().getColorModel()) # get all slices of this channel and frame for s in range(1, imp.getNSlices()+1): ip = stack.getProcessor(imp.getStackIndex(ch, s, frame)) ip2 = ip.createProcessor(width, height) # potentially larger ip2.insert(ip, 0, 0) tmpstack.addSlice("", ip2) # Pad the end (in z) of this channel and frame for s in range(imp.getNSlices(), slices): tmpstack.addSlice("", empty) # subpixel translation imp_tmpstack = ImagePlus("", tmpstack) imp_translated = translate_single_stack_using_imglib2(imp_tmpstack, shift.x, shift.y, shift.z) # add translated stack to final time-series translated_stack = imp_translated.getStack() for s in range(1, translated_stack.getSize()+1): ss = "_z" + zero_pad(s, len(str(slices))) ip = translated_stack.getProcessor(s).duplicate() # duplicate is important as otherwise it will only be a reference that can change its content if virtual is True: name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif" names.append(name) currentslice = ImagePlus("", ip) currentslice.setCalibration(imp.getCalibration().copy()) currentslice.setProperty("Info", imp.getProperty("Info")); FileSaver(currentslice).saveAsTiff(target_folder + "/" + name) else: registeredstack.addSlice("", ip) IJ.showProgress(1) if virtual is True: # Create virtual hyper stack registeredstack = VirtualStack(width, height, None, target_folder) for name in names: registeredstack.addSlice(name) registeredstack_imp = ImagePlus("registered time points", registeredstack) registeredstack_imp.setCalibration(imp.getCalibration().copy()) registeredstack_imp.setProperty("Info", imp.getProperty("Info")) registeredstack_imp = HyperStackConverter.toHyperStack(registeredstack_imp, imp.getNChannels(), slices, imp.getNFrames(), "xyzct", "Composite"); return registeredstack_imp
def load_image_sequence_from_path_to_hyperstack(path, nc, nz, nt): imp = FolderOpener().openFolder(path) imp2 = HyperStackConverter.toHyperStack(imp, nc, nz, nt, "default", "Color"); return imp2
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()
#Plug Your analysis here# imp = IJ.getImage(); IJ.runMacroFile(str(macroFilePath)) imp.close() done.append(imageName) counter += 1 # Save resultant image using Bio-Formats # #path = paths + imp.getTitle() + operation + ".ome.tiff"; #print(path) #options = "save=" + path + " export compression=Uncompressed" #IJ.run(imp, "Bio-Formats Exporter", options); #imp.changes = False # # Upload image to OMERO #str2d = java.lang.reflect.Array.newInstance(java.lang.String,[1]) #str2d [0] = path #success = uploadImage(str2d, gateway) image = IJ.getImage(); print(image.getDimensions(), z_slices, counter) final_image = HyperStackConverter.toHyperStack(image,1,z_slices,counter) final_image.setOpenAsHyperStack(True) final_image.show() IJ.run(final_image, "Stack to Hyperstack...", "order=xyczt(default) channels=1 slices="+str(z_slices)+" frames="+str(counter)+" display=Color") print(final_image.isHyperStack(), final_image.getDimensions(), final_image.isDisplayedHyperStack()) #image.close() print("Done") openImagePlus(HOST,USERNAME,PASSWORD,defaultgroup,str(100000000)) #success = uploadImage(str2d, gateway) gateway.disconnect()
def load_image_sequence_from_path_to_hyperstack(path, nc, nz, nt): imp = FolderOpener().openFolder(path) imp2 = HyperStackConverter.toHyperStack(imp, nc, nz, nt, "default", "Color"); return imp2
IJ.runMacroFile(str(macroFilePath)) #print("ran macro") imp.close() #print("closed image") done.append(imageName) counter += 1 # Save resultant image using Bio-Formats # #path = paths + imp.getTitle() + operation + ".ome.tiff"; #print(path) #options = "save=" + path + " export compression=Uncompressed" #IJ.run(imp, "Bio-Formats Exporter", options); #imp.changes = False # # Upload image to OMERO #str2d = java.lang.reflect.Array.newInstance(java.lang.String,[1]) #str2d [0] = path #success = uploadImage(str2d, gateway) image = IJ.getImage(); print(image.getDimensions(), z_slices, counter) final_image = HyperStackConverter.toHyperStack(image,1,z_slices,counter) final_image.setOpenAsHyperStack(True) final_image.show() IJ.run(final_image, "Stack to Hyperstack...", "order=xyczt(default) channels=1 slices="+str(z_slices)+" frames="+str(counter)+" display=Color") print(final_image.isHyperStack(), final_image.getDimensions(), final_image.isDisplayedHyperStack()) #image.close() print("Done") openImagePlus(HOST,USERNAME,PASSWORD,defaultgroup,str(100000000)) #success = uploadImage(str2d, gateway) gateway.disconnect()
def shuffleImagestoCZT(hyperStackImagePlus, case): #hyperStackImagePlus.show() #Inverser T (totalTime) et Z (zDepthByChannel) mainProcessor = hyperStackImagePlus.getProcessor() numberOfChannels = hyperStackImagePlus.getNChannels() #Nombre de canaux totalTime = hyperStackImagePlus.getNFrames() zDepthByChannel = hyperStackImagePlus.getNSlices() imageTitle = hyperStackImagePlus.getTitle() print("numberOfChannels: "+str(numberOfChannels)) print("zDepthByChannel: "+str(zDepthByChannel)) print("totalTime: "+str(totalTime)) imageWidth = hyperStackImagePlus.getWidth(); #Largeur de l'image imageHeight = hyperStackImagePlus.getHeight(); #Hauteur de l'image bitDepth = hyperStackImagePlus.getBitDepth() #Type de l'image en bits - Returns the bit depth, 8, 16, 24 (RGB) or 32, or 0 if the bit depth is unknown. RGB images actually use 32 bits per pixel. stackedImages = hyperStackImagePlus.getStack() #totalNumberOfImages = mainImageStackImp.getStackSize() #Profondeur Z * Nombre de canaux * temps totalNumberOfImages = stackedImages.getSize() #Profondeur Z * Nombre de canaux * temps print("totalNumberOfImages: "+str(totalNumberOfImages)) #print("Separating by channels...") C = 0 T = 1 Z = 2 if case == "CTZ": first=C middle=T last=Z nFirst=numberOfChannels nMiddle=totalTime nLast=zDepthByChannel elif case == "ZCT": first=Z middle=C last=T nFirst=zDepthByChannel nMiddle=numberOfChannels nLast=totalTime elif case == "ZTC": first=Z middle=T last=C nFirst=zDepthByChannel nMiddle=totalTime nLast=numberOfChannels elif case == "TCZ": first=T middle=C last=Z nFirst=totalTime nMiddle=numberOfChannels nLast=zDepthByChannel elif case == "TZC": first=T middle=Z last=C nFirst=totalTime nMiddle=zDepthByChannel nLast=numberOfChannels else: first=C middle=Z last=T nFirst=numberOfChannels nMiddle=zDepthByChannel nLast=totalTime shuffledHyperStackImageStack = ImageStack() originalImageArray = stackedImages.getImageArray() pythonOriginalImageArray = [] pythonShuffledImageArray = [] for imageArray in originalImageArray: pythonOriginalImageArray.append(imageArray) pythonShuffledImageArray.append(imageArray) originalImageLabels = stackedImages.getSliceLabels() pythonOriginalLabelsArray = [] pythonShuffledLabelsArray = [] for imageLabel in originalImageLabels: pythonOriginalLabelsArray.append(imageLabel) pythonShuffledLabelsArray.append(imageLabel) indexes = [0, 0, 0] for timeNumber in range(0, totalTime): for zNumber in range(0, zDepthByChannel): for channelNumber in range(0, numberOfChannels): destinationSliceIndex = channelNumber + zNumber*numberOfChannels + timeNumber*numberOfChannels*zDepthByChannel #sourceSliceIndex = indexes[first] + indexes[middle]*nFirst + indexes[last]*nFirst*nMiddle sourceSliceIndex = channelNumber + timeNumber*nFirst + zNumber*nFirst*nMiddle print("destinationSliceIndex: "+str(destinationSliceIndex)+", sourceSliceIndex: "+str(channelNumber)+"+"+str(timeNumber)+"*"+str(nFirst)+"+"+str(zNumber)+"*"+str(nFirst)+"*"+str(nMiddle)+" = "+str(sourceSliceIndex)) pythonOriginalImageArray[destinationSliceIndex] = pythonShuffledImageArray[sourceSliceIndex] pythonOriginalLabelsArray[destinationSliceIndex] = pythonShuffledLabelsArray[sourceSliceIndex] indexes[0]+=1 indexes[1]+=1 indexes[2]+=1 #print("selectedSliceNumber: "+str(sliceNumber)) #sliceProcessor = stackedImages.getProcessor(sliceNumber) #shuffledHyperStackImageStack.addSlice(sliceProcessor) number = 0 for sliceImageArray in pythonOriginalImageArray: if sliceImageArray == None: break sliceImage = IJ.createImage(str(pythonShuffledLabelsArray[number]), "16-bit Black", imageWidth, imageHeight, 1) sliceProcessor = sliceImage.getProcessor() sliceProcessor.setPixels(sliceImageArray) #print("sliceImageArray: "+str(sliceImageArray)) shuffledHyperStackImageStack.addSlice(sliceProcessor) number+=1 #for zNumber in range(0, zDepthByChannel): #for timeNumber in range(1, totalNumberOfImages+1, totalTime): #for channelNumber in range(timeNumber, totalNumberOfImages, numberOfChannels): #sliceNumber = timeNumber+zNumber #print("selectedSliceNumber: "+str(sliceNumber)) #sliceProcessor = stackedImages.getProcessor(sliceNumber) #shuffledHyperStackImageStack.addSlice(sliceProcessor) """ arrayOfChannels = [] for channelNumber in range(0,numberOfChannels): channelStack = ImageStack(imageWidth, imageHeight) timeStacks = [] for timeNumber in range(0, totalTime): timeStack = ImageStack(imageWidth, imageHeight) timeStacks.append(timeStack) for imageNumber in range(channelNumber, totalNumberOfImages, numberOfChannels): sliceTitle = stackedImages.getSliceLabel(imageNumber+1) sliceProcessor = stackedImages.getProcessor(imageNumber+1) channelStack.addSlice(sliceTitle, sliceProcessor) #channelImagePlus = ImagePlus("Test view content channel "+str(channelNumber), channelStack) #channelImagePlus.show() #OK jusque ici zDepthNumberCount = 0 timeSliceCount = 0 for sliceNumber in range(1, channelStack.getSize()+1): #print(str(zDepthNumberCount), str(timeSliceCount)) sliceProcessor = channelStack.getProcessor(sliceNumber) selectedTimeStack = timeStacks[zDepthNumberCount] selectedTimeStack.addSlice(sliceProcessor) zDepthNumberCount+=1 if zDepthNumberCount == totalTime: #zDepthByChannel zDepthNumberCount = 0 timeSliceCount+=1 if timeSliceCount == zDepthByChannel: #totalTime break timeImagePluses = [] i=0 #print("timeStacks: "+str(timeStacks)) for timeStack in timeStacks: title = String("Channel "+str(channelNumber+1)+" - Time "+str(i)) #print("title: "+str(title)) timeImagePlus = ImagePlus(title, timeStack) #timeImagePlus.show() timeImagePluses.append(timeImagePlus) i+=1 arrayOfChannels.append(timeImagePluses) #print("arrayOfChannels: "+str(arrayOfChannels)) #print("Finished separating by channels") shuffledHyperStackImageStack = ImageStack() for timeStamp in range(totalTime): for zDepth in range(zDepthByChannel): for channelNumber in range(numberOfChannels): timeImagePlus = arrayOfChannels[channelNumber][timeStamp] print("timeImagePlus: "+str(timeImagePlus)) #timeImagePlus.show() timeImageStack = timeImagePlus.getStack() timeImageStackSize = timeImageStack.getSize() timeImageSliceProcessor = timeImageStack.getProcessor(zDepth+1) shuffledHyperStackImageStack.addSlice(timeImageSliceProcessor) """ shuffledHyperStackImagePlus = ImagePlus(imageTitle, shuffledHyperStackImageStack) #shuffledHyperStackImagePlus.show() shuffledHyperStackImagePlus = HyperStackConverter.toHyperStack(shuffledHyperStackImagePlus, nFirst, nMiddle, nLast, "Color") return shuffledHyperStackImagePlus
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
def reduceZ(): imp = IJ.getImage() #get the standardtack title_1 = imp.getTitle() title = title_1.split(' - ')[1] print(title) dimentions = imp.getDimensions() numZ, numChannels, numframes = dimentions[3], dimentions[2], dimentions[4] print(numChannels) IJ.run(imp, "Set Measurements...", "kurtosis redirect=None decimal=3") kurtTotal = [] for time in range(numframes): print(time) time = time + 1 imp.setPosition(1, 1, time) kurt = [] for z in range(numZ): z = z + 1 imp.setPosition(1, z, time) imp.setRoi(70, 40, 437, 459) IJ.setAutoThreshold(imp, "MaxEntropy dark") IJ.run(imp, "Measure", "") IJ.resetThreshold(imp) rt = ResultsTable() t = rt.getResultsTable() kurt.append(t.getValueAsDouble(23, z - 1)) # 23 = kurtosis kurtTotal.append(kurt.index(max(kurt)) + 1) IJ.run(imp, "Clear Results", "") print(kurtTotal) IJ.run(imp, "Select All", "") imp2 = IJ.createImage("GFP", "16-bit black", dimentions[0], dimentions[1], numframes) imp2 = HyperStackConverter.toHyperStack(imp2, 1, 1, numframes, "Color") print(' ------------') print(numframes) channel = 1 i = 0 for time in range(numframes): time = time + 1 imp.setPosition(channel, kurtTotal[i], time) imp.copy() imp2.setPosition(channel, 1, time) imp2.paste() print(time) i = i + 1 IJ.run(imp2, "Delete Slice", "delete=slice") imp2.show() imp4 = IJ.createImage("RFP", "16-bit black", dimentions[0], dimentions[1], numframes) imp4 = HyperStackConverter.toHyperStack(imp4, 1, 1, numframes, "Color") print(' ------------') channel = 2 i = 0 for time in range(numframes): time = time + 1 imp.setPosition(channel, kurtTotal[i], time) imp.copy() print(imp.title) imp4.setPosition(channel, 1, time) imp4.paste() i = i + 1 IJ.run(imp4, "Delete Slice", "delete=slice") imp4.show() IJ.selectWindow(title_1) IJ.run("Close") imp5 = ImagePlus() IJ.run(imp5, "Merge Channels...", "c1=RFP c2=GFP create") imp5 = IJ.getImage() IJ.run( imp5, "Bio-Formats Exporter", "save=/home/rickettsia/Desktop/data/Clamydial_Image_Analysis/EMS_BMEC_20X_01192020/Zreduced/" + title + ".ome.tif export compression=LZW") IJ.selectWindow('Merged') IJ.run("Close")
from fiji.plugin.trackmate.action import TrackBranchAnalysis from fiji.plugin.trackmate.graph import GraphUtils from ij.plugin import HyperStackConverter from ij.measure import ResultsTable from ij import IJ import fiji.plugin.trackmate.visualization.hyperstack.HyperStackDisplayer as HyperStackDisplayer import fiji.plugin.trackmate.features.FeatureFilter as FeatureFilter import fiji.plugin.trackmate.features.track.TrackDurationAnalyzer as TrackDurationAnalyzer import sys from java.io import File from fiji.plugin.trackmate.io import TmXmlWriter imp = IJ.getImage() impconv = HyperStackConverter() imp = impconv.toHyperStack(imp, 1, 1, imp.getStackSize()) imp.show() #---------------------------- # Create the model object now #---------------------------- model = Model() # Send all messages to ImageJ log window. model.setLogger(Logger.IJ_LOGGER) #------------------------ # Prepare settings object
def register_hyperstack(imp, channel, shifts, target_folder, virtual): """ Takes the imp, determines the x,y,z drift for each pair of time points, using the preferred given channel, and outputs as a hyperstack.""" # Compute bounds of the new volume, # which accounts for all translations: minx, miny, minz, maxx, maxy, maxz = compute_min_max(shifts) # Make shifts relative to new canvas dimensions # so that the min values become 0,0,0 for shift in shifts: shift.x -= minx shift.y -= miny shift.z -= minz #print "shifts relative to new dimensions:" #for s in shifts: # print s.x, s.y, s.z # new canvas dimensions:r width = imp.width + maxx - minx height = maxy - miny + imp.height slices = maxz - minz + imp.getNSlices() print "New dimensions:", width, height, slices # Prepare empty slice to pad in Z when necessary empty = imp.getProcessor().createProcessor(width, height) # if it's RGB, fill the empty slice with blackness if isinstance(empty, ColorProcessor): empty.setValue(0) empty.fill() # Write all slices to files: stack = imp.getStack() if virtual is False: registeredstack = ImageStack(width, height, imp.getProcessor().getColorModel()) names = [] for frame in range(1, imp.getNFrames()+1): shift = shifts[frame-1] print "frame",frame,"correcting drift",-shift.x-minx,-shift.y-miny,-shift.z-minz IJ.log(" frame "+str(frame)+" correcting drift "+str(-shift.x-minx)+","+str(-shift.y-miny)+","+str(-shift.z-minz)) fr = "t" + zero_pad(frame, len(str(imp.getNFrames()))) # Pad with empty slices before reaching the first slice for s in range(shift.z): ss = "_z" + zero_pad(s + 1, len(str(slices))) # slices start at 1 for ch in range(1, imp.getNChannels()+1): name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif" names.append(name) if virtual is True: currentslice = ImagePlus("", empty) currentslice.setCalibration(imp.getCalibration().copy()) currentslice.setProperty("Info", imp.getProperty("Info")) FileSaver(currentslice).saveAsTiff(target_folder + "/" + name) else: empty = imp.getProcessor().createProcessor(width, height) registeredstack.addSlice(str(name), empty) # Add all proper slices stack = imp.getStack() for s in range(1, imp.getNSlices()+1): ss = "_z" + zero_pad(s + shift.z, len(str(slices))) for ch in range(1, imp.getNChannels()+1): ip = stack.getProcessor(imp.getStackIndex(ch, s, frame)) ip2 = ip.createProcessor(width, height) # potentially larger ip2.insert(ip, shift.x, shift.y) name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif" names.append(name) if virtual is True: currentslice = ImagePlus("", ip2) currentslice.setCalibration(imp.getCalibration().copy()) currentslice.setProperty("Info", imp.getProperty("Info")); FileSaver(currentslice).saveAsTiff(target_folder + "/" + name) else: registeredstack.addSlice(str(name), ip2) # Pad the end for s in range(shift.z + imp.getNSlices(), slices): ss = "_z" + zero_pad(s + 1, len(str(slices))) for ch in range(1, imp.getNChannels()+1): name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif" names.append(name) if virtual is True: currentslice = ImagePlus("", empty) currentslice.setCalibration(imp.getCalibration().copy()) currentslice.setProperty("Info", imp.getProperty("Info")) FileSaver(currentslice).saveAsTiff(target_folder + "/" + name) else: registeredstack.addSlice(str(name), empty) if virtual is True: # Create virtual hyper stack registeredstack = VirtualStack(width, height, None, target_folder) for name in names: registeredstack.addSlice(name) registeredstack_imp = ImagePlus("registered time points", registeredstack) registeredstack_imp.setCalibration(imp.getCalibration().copy()) registeredstack_imp.setProperty("Info", imp.getProperty("Info")) registeredstack_imp = HyperStackConverter.toHyperStack(registeredstack_imp, imp.getNChannels(), len(names) / (imp.getNChannels() * imp.getNFrames()), imp.getNFrames(), "xyczt", "Composite"); return registeredstack_imp
def decon(seriesNumber, imgP, psfP): nChannels = imgP.getNChannels() if nChannels>1: imgPc = ChannelSplitter.split(imgP) else: imgPc = [imgP] if psfP.getNChannels()>1: psfPc = ChannelSplitter.split(psfP) if len(psfPc)<nChannels: log("PSF image has fewer channels! Skipping image's trailing channels {} to {}".format(psfP.getNChannels()+1,nChannels)) imgPc = imgPc[:psfP.getNChannels()] else: psfPc = [psfP]*nChannels nChannels = len(imgPc) if combinedChannels: deconChannels = None for channelNumber in range(nChannels): log("Processing image {} series {} channel {}..".format(inputFile.getAbsolutePath(),seriesNumber,channelNumber)) imgP = imgPc[channelNumber] psfP = psfPc[channelNumber] img = ImageJFunctions.wrap(imgP) psf = ImageJFunctions.wrap(psfP) # convert to float (TODO: make sure deconvolution op works on other types) imgF=ops.convert().float32(img) psfF=ops.convert().float32(psf) # make psf same size as image psfSize=FinalDimensions([img.dimension(0), img.dimension(1), img.dimension(2)]); # add border in z direction #borderSize=[0,0,psfSize.dimension(2)/2]; borderSize=[0,0,0]; deconvolved = ops.deconvolve().richardsonLucy(imgF, psfF, numIterations); # Create the ImagePlus, copy scale and dimensions deconvolvedImp = ImageJFunctions.wrapFloat(deconvolved,inputFile.getName()+'-series{}-channel{}-deconvolvedWith-{}-{}iterations.tiff'.format(seriesNumber,channelNumber,psfFile.getName(),numIterations)) deconvolvedImp.copyScale(imgP) width, height, nChannelz, nSlices, nFrames = imgP.getDimensions() deconvolvedImp.setDimensions(nChannelz, nSlices, nFrames) if combinedChannels: if deconChannels is None: deconChannels = ImageStack(width,height) for z in range(nSlices): deconChannels.addSlice(deconvolvedImp.getStack().getProcessor(z)) else: IJ.saveAsTiff(deconvolvedImp,os.path.join(outputDirectory.getAbsolutePath(),deconvolvedImp.getTitle())) if combinedChannels: final = ImageStack(width,height) for z in range(nSlices): for c in range(nChannels): i = c*nSlices+z final.addSlice(deconChannels.getProcessor(i+1)) hyperstack = ImagePlus(inputFile.getName()+'-series{}-deconvolvedWith-{}-{}iterations.tiff'.format(seriesNumber,psfFile.getName(),numIterations),final) hyperstack = HyperStackConverter.toHyperStack(hyperstack,nChannels,nSlices,1) hyperstack.copyScale(imgP) IJ.saveAsTiff(hyperstack,os.path.join(outputDirectory.getAbsolutePath(),hyperstack.getTitle()))
# apply a filter to the image using ClearCL / OpenCL parameters = { "src":input, "dst":output , "shift":shift }; clij.execute(filesPath + "psychodelicColorExchange.cl", "psychodelicColorExchange", parameters); for c in range(0, 3): clij.op().copySlice(output, slice, c); for d in range(0, 5): clij.op().copySlice(slice, stack, shift * 3 * 5 + d * 3 + c); # convert the result back to ImagePlus and show it result = clij.pull(stack); result = HyperStackConverter.toHyperStack(result, 3, result.getNSlices() / 3, 1); IJ.run(result, "Gaussian Blur 3D...", "x=0 y=0 z=1"); result.show(); IJ.run(result, "Make Composite", "display=Composite"); # clean up input.close(); output.close(); slice.close(); stack.close(); clij.close();
print("Loading data...") if len(imfilenames) > 2: fo = FolderOpener() imp = fo.open(p) imp.show() print("N_z = {}".format(imp.getNSlices())) print("N_c = {}".format(imp.getNChannels())) print("N_t = {}".format(imp.getNFrames())) else: ch1_imp = IJ.openImage(os.path.join(p, imfilenames[0])) ch2_imp = IJ.openImage(os.path.join(p, imfilenames[1])) imp = Concatenator().concatenate(ch1_imp, ch2_imp, False) imp2 = HyperStackConverter.toHyperStack(imp, 2, int(imp.getNSlices() / 2), 1, "xyzct", "Composite") imp2.show() imp.close() print("Saving data...") out_dir = os.path.dirname(os.path.dirname(p)) save_path = os.path.join(out_dir, fname + ".tif") FileSaver(imp2).saveAsTiffStack(save_path) print("Copying metadata...") shutil.copyfile(os.path.join(p, fname + ".txt"), os.path.join(out_dir, metadata_file)) imp2.close() except Exception as e: print(e) print("Problem with {}".format(p))
Canceled = False if not Canceled: for f in file_path: # Hyperstackの作成 imp = IJ.openImage(f) nFrame = imp.getNSlices( ) / n_Channel # 元画像のAttributionがなぜかFrame が Z sliceとなっている # File 保存のための文字列作成 save_file = imp.getTitle().replace(".tif", "-stack.tif") save_path = os.path.join(save_dir, save_file) # Hyper Stackに変換 h_imp = HyperStackConverter.toHyperStack(imp, n_Channel, 1, nFrame, "Composite") del imp # Hyper Stack の Channelカラー変更 for i, color in enumerate(user_color): h_imp.setC(i + 1) h_imp.setLut(LUT.createLutFromColor(Colors[color])) # ファイルを保存 IJ.saveAsTiff(h_imp, save_path) # IJ.log(save_path) del h_imp
def main(): check_dependencies() # setup Prefs.blackBackground = True params = Parameters() params.load_last_params() # select folders if params.last_input_path is not None: DirectoryChooser.setDefaultDirectory(params.last_input_path) dc = DirectoryChooser("Choose root folder containing data for analysis") input_folder = dc.getDirectory() params.last_input_path = input_folder if input_folder is None: print("Run canceled") return if params.last_output_path is not None: DirectoryChooser.setDefaultDirectory( os.path.dirname(params.last_output_path)) dc = DirectoryChooser("choose location to save output") output_folder = dc.getDirectory() if output_folder is None: print("Run canceled") return timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S') output_folder = os.path.join(output_folder, (timestamp + ' output')) params.last_output_path = output_folder os.mkdir(output_folder) analysis_mode, threshold_method, minimum_cell_area_um2 = choose_analysis_mode( params) if analysis_mode is None: print("Run canceled") return params.last_analysis_mode = analysis_mode do_manual_qc = "+ manual correction" in analysis_mode params.last_threshold_method = threshold_method params.last_minimum_cell_area_um2 = minimum_cell_area_um2 params.persist_parameters() # load image(s): files_lst = [ f for f in os.listdir(input_folder) if os.path.splitext(f)[1] == '.tif' ] out_statses = [] for f in files_lst: print("Working on image {}...".format(os.path.splitext(f)[0])) imp = IJ.openImage(os.path.join(input_folder, f)) metadata = import_iq3_metadata( os.path.join(input_folder, os.path.splitext(f)[0] + '.txt')) n_channels = int(metadata['n_channels']) gfp_channel_number = [ ("488" in ch) for ch in metadata['channel_list'] ].index(True) + 1 if any( [("488" in ch) for ch in metadata['channel_list']]) else None dapi_channel_number = [ ("405" in ch) for ch in metadata['channel_list'] ].index(True) + 1 if any( [("405" in ch) for ch in metadata['channel_list']]) else None red_channel_number = [ ("561" in ch) for ch in metadata['channel_list'] ].index(True) + 1 if any( [("561" in ch) for ch in metadata['channel_list']]) else None imp = HyperStackConverter.toHyperStack(imp, n_channels, imp.getNSlices() // n_channels, 1, "Color") imp = ZProjector.run(imp, "max") if dapi_channel_number is not None: imp.setC(dapi_channel_number) IJ.run(imp, "Blue", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") else: raise NotImplementedError( "Nuclear staining channel doesn't seem to exist!") if red_channel_number is not None: imp.setC(red_channel_number) IJ.run(imp, "Red", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") if gfp_channel_number is not None: imp.setC(gfp_channel_number) IJ.run(imp, "Green", "") IJ.run(imp, "Enhance Contrast", "saturated=0.35") imp.setC(gfp_channel_number) imp.show() imp.setDisplayMode(IJ.COMPOSITE) cal = imp.getCalibration() cal.setUnit(metadata["y_unit"]) cal.pixelWidth = metadata["x_physical_size"] cal.pixelHeight = metadata["y_physical_size"] imp.setCalibration(cal) min_size_pix = minimum_cell_area_um2 / (cal.pixelHeight * cal.pixelWidth) if "GFP intensity" in analysis_mode: out_stats = gfp_analysis(imp, f, output_folder, gfp_channel_number=gfp_channel_number, dapi_channel_number=dapi_channel_number, threshold_method=threshold_method, do_manual_qc=do_manual_qc, min_size_pix=min_size_pix) elif analysis_mode == "Manual": important_channel = gfp_channel_number if gfp_channel_number is not None else dapi_channel_number out_stats = manual_analysis( imp, f, output_folder, gfp_channel_number=gfp_channel_number, dapi_channel_number=dapi_channel_number, important_channel=important_channel) elif "E-cadherin watershed" in analysis_mode: out_stats = ecad_analysis(imp, f, output_folder, gfp_channel_number=gfp_channel_number, red_channel_number=red_channel_number, dapi_channel_number=dapi_channel_number, do_manual_qc=do_manual_qc) imp.close() out_statses.extend(out_stats) print("Current total number of cells identified: {}".format( len(out_statses))) # get # nuclei per "cell" params.save_parameters_to_json( os.path.join(output_folder, "parameters used.json")) WaitForUserDialog( "Done", "Done, having analysed {} cells in total!".format( len(out_statses))).show() return
def register_hyperstack_subpixel(imp, channel, shifts, target_folder, virtual): """ Takes the imp, determines the x,y,z drift for each pair of time points, using the preferred given channel, and outputs as a hyperstack. The shifted image is computed using TransformJ allowing for sub-pixel shifts using interpolation. This is quite a bit slower than just shifting the image by full pixels as done in above function register_hyperstack(). However it significantly improves the result by removing pixel jitter. """ # Compute bounds of the new volume, # which accounts for all translations: minx, miny, minz, maxx, maxy, maxz = compute_min_max(shifts) # Make shifts relative to new canvas dimensions # so that the min values become 0,0,0 for shift in shifts: shift.x -= minx shift.y -= miny shift.z -= minz # new canvas dimensions: width = int(imp.width + maxx - minx) height = int(maxy - miny + imp.height) slices = int(maxz - minz + imp.getNSlices()) #print "New dimensions:", width, height, slices # prepare stack for final results stack = imp.getStack() if virtual is True: names = [] else: registeredstack = ImageStack(width, height, imp.getProcessor().getColorModel()) # prepare empty slice for padding empty = imp.getProcessor().createProcessor(width, height) IJ.showProgress(0) # get raw data as stack stack = imp.getStack() # loop across frames for frame in range(1, imp.getNFrames()+1): IJ.showProgress(frame / float(imp.getNFrames()+1)) fr = "t" + zero_pad(frame, len(str(imp.getNFrames()))) # for saving files in a virtual stack # get and report current shift shift = shifts[frame-1] #print "frame",frame,"correcting drift",-shift.x-minx,-shift.y-miny,-shift.z-minz IJ.log(" frame "+str(frame)+" correcting drift "+str(round(-shift.x-minx,2))+","+str(round(-shift.y-miny,2))+","+str(round(-shift.z-minz,2))) # loop across channels for ch in range(1, imp.getNChannels()+1): tmpstack = ImageStack(width, height, imp.getProcessor().getColorModel()) # get all slices of this channel and frame for s in range(1, imp.getNSlices()+1): ip = stack.getProcessor(imp.getStackIndex(ch, s, frame)) ip2 = ip.createProcessor(width, height) # potentially larger ip2.insert(ip, 0, 0) tmpstack.addSlice("", ip2) # Pad the end (in z) of this channel and frame for s in range(imp.getNSlices(), slices): tmpstack.addSlice("", empty) # subpixel translation imp_tmpstack = ImagePlus("", tmpstack) imp_translated = translate_single_stack_using_imglib2(imp_tmpstack, shift.x, shift.y, shift.z) # add translated stack to final time-series translated_stack = imp_translated.getStack() for s in range(1, translated_stack.getSize()+1): ss = "_z" + zero_pad(s, len(str(slices))) ip = translated_stack.getProcessor(s).duplicate() # duplicate is important as otherwise it will only be a reference that can change its content if virtual is True: name = fr + ss + "_c" + zero_pad(ch, len(str(imp.getNChannels()))) +".tif" names.append(name) currentslice = ImagePlus("", ip) currentslice.setCalibration(imp.getCalibration().copy()) currentslice.setProperty("Info", imp.getProperty("Info")); FileSaver(currentslice).saveAsTiff(target_folder + "/" + name) else: registeredstack.addSlice("", ip) IJ.showProgress(1) if virtual is True: # Create virtual hyper stack registeredstack = VirtualStack(width, height, None, target_folder) for name in names: registeredstack.addSlice(name) registeredstack_imp = ImagePlus("registered time points", registeredstack) registeredstack_imp.setCalibration(imp.getCalibration().copy()) registeredstack_imp.setProperty("Info", imp.getProperty("Info")) registeredstack_imp = HyperStackConverter.toHyperStack(registeredstack_imp, imp.getNChannels(), slices, imp.getNFrames(), "xyzct", "Composite"); return registeredstack_imp
image_green.show() image = ImagePlus("two channel stack", twochannel_stack) image.show() if auto_thresh: con = ImageConverter(image) con.convertToGray8() IJ.run(image, "Auto Local Threshold", "method=Bernsen radius=15 parameter_1=0 parameter_2=0 white stack") #image = CompositeImage(image_two) #image = IJ.getImage() z_slices = image.getDimensions()[3] / 2 print("order=xyczt(default) channels=2 slices="+ str(z_slices) + " frames=1 display=Color", image.getDimensions()) image_two = HyperStackConverter.toHyperStack(image,2,z_slices,1) image = CompositeImage(image_two) image.show() rt = run_comdet(image) rt.save(directory+"/"+filename+"_results.csv" ) image = IJ.getImage() if auto_cell: mask = generate_mask(image_green, auto_cell_thresh) fs = FileSaver(mask) filepath = directory + "/" + filename + "_mask.tiff" fs.saveAsTiff(filepath) rest = ResultsTable.open(directory+"/"+filename+"_results.csv")