def select_images(): """ Returns two ImagePlus objects that can be used by the drift correction. If more than two images are available a dialog is used for selection. """ if WindowManager.getImageCount() > 0: imp = WindowManager.getCurrentImage() if imp.getImageStackSize() == 2: dup = Duplicator() img1 = dup.run(imp, 1, 1) img1.setTitle("Slice1") img2 = dup.run(imp, 2, 2) img2.setTitle("Slice2") elif WindowManager.getImageCount() == 2: img1, img2 = [WindowManager.getImage(id) for id in WindowManager.getIDList()] elif WindowManager.getImageCount() > 2: image_ids = WindowManager.getIDList() image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids] try: sel1, sel2 = dialogs.create_selection_dialog(image_titles, range(2)) except TypeError: return(None, None) img1 = WindowManager.getImage(image_ids[sel1]) img2 = WindowManager.getImage(image_ids[sel2]) else: IJ.error("You need two images to run the script.") return(None, None) else: IJ.error("You need two images to run the script.") return(None, None) return (img1, img2)
def __init__(self, p): self.cellCounter = 1 self.olay = Overlay() self.position = p print p.getRoiPath() if p.getRoiPath() != None: # check if there is an existing overlay file and load it! p.loadRois() self.frame = JFrame("CellCropper", size=(200,200)) self.frame.setLocation(20,120) self.Panel = JPanel(GridLayout(0,1)) self.frame.add(self.Panel) #self.nameField = JTextField("p" + "_c",15) self.nameField = JTextField("p" + str(self.position.getID()) + "_c",15) self.Panel.add(self.nameField) self.cutoutButton = JButton("Cut out cell",actionPerformed=cut) self.Panel.add(self.cutoutButton) self.delOlButton = JButton("Delete Overlay",actionPerformed=delOverlay) self.Panel.add(self.delOlButton) self.saveOlButton = JButton("Save Overlay",actionPerformed=saveOverlay) self.Panel.add(self.saveOlButton) self.quitButton = JButton("Quit script",actionPerformed=quit) self.Panel.add(self.quitButton) self.frame.pack() WindowManager.addWindow(self.frame) self.show()
def get_images(ids): """ Returns a list of ImagePlus objects. :param ids: The ids of the ImagePlus objects to return. """ image_ids = WindowManager.getIDList() return [WindowManager.getImage(image_ids[id]) for id in ids]
def get_setup(): ''' Returns the drift correction mode and three image. The order of return values is drift detection mode, pre-edge 1, pre-edge 2, post-edge. ''' options = drift.get_options() modes = drift.get_modes() dialog = GenericDialog('3-window-method setup') dialog.addMessage('Select the mode for drift correction\n' + 'and the images to process.') dialog.addChoice('Mode:', options, options[0]) image_ids = WindowManager.getIDList() if not image_ids or len(image_ids) < 2: return [None]*4 image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids] dialog.addMessage('Post-edge is divided by the pre-edge.') dialog.addChoice('Pre-edge 1', image_titles, image_titles[0]) dialog.addChoice('Pre-edge 2', image_titles, image_titles[1]) dialog.addChoice('Post-edge', image_titles, image_titles[2]) dialog.showDialog() if dialog.wasCanceled(): return [None]*4 mode = modes[dialog.getNextChoiceIndex()] img1 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) img2 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) img3 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) return mode, img1, img2, img3
def get_image_titles(): """ Returns the titles of all open image windows as a list. """ image_ids = WindowManager.getIDList() image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids] return image_titles
def close(self): if self.olay != None: yncd = YesNoCancelDialog(self.frame, "Save overlay?", "Save overlay?") #frame, title, message if yncd.yesPressed(): self.saveOverlay() WindowManager.removeWindow(self.frame) self.frame.dispose()
def watershed_3d(imp, radius): imp.show() # one needs to display it, otherwise below function cannot find it IJ.run("3D Watershed Split", "binary=%s seeds=Automatic radius=%s" % (imp.getTitle(), radius)) imp.hide() # get the output image imp_out = IJ.getImage() imp_out.hide() # remove the EDT image, which is also displayed WindowManager.getImage("EDT").close() return imp_out
def close_all_image_windows(): # forcefully closes all open images windows ids = WindowManager.getIDList(); if (ids==None): return for i in ids: imp = WindowManager.getImage(i) if (imp!=None): win = imp.getWindow() if (win!=None): imp.changes = False # avoids the "save changes" dialog win.close()
def objects_counter_3d(imp_bw, imp_intens, measurements, threshold, vol_min, vol_max): # set options options = "%s dots_size=5 font_size=10 show_numbers white_numbers redirect_to=%s" % (measurements, imp_intens.getTitle()) IJ.run("3D OC Options", options); # make sure the output image does not exist already as this leasds to weird behaviors.... outlines_title = "Surface map of %s redirect to %s" % (imp_bw.getTitle(),imp_intens.getTitle()) if WindowManager.getImage(outlines_title) != None: WindowManager.getImage(outlines_title).close() # analyze imp_bw.show(); imp_intens.show(); IJ.run(imp_bw, "3D Objects Counter", "threshold=%s min.=%s max.=%s exclude_objects_on_edges surfaces statistics" % (threshold, vol_min, vol_max)) imp_out = IJ.getImage(); imp_out.setTitle("outlines"); imp_out.hide() return imp_out
def getImage(): """Get first open image or open Bio-Formats importer if no image is available.""" imp = WindowManager.getCurrentImage() if not imp: # Show bio formats open dialog IJ.run("Bio-Formats") imp = WindowManager.getCurrentImage() print("Start") if not imp: IJ.noImage() raise ValueError("Need image") return imp
def draw_roi_on_full_res_tile(containing_tiles_dict,subupcoords_dict): masterXs = [] masterYs = [] for key in containing_tiles_dict.keys(): if (len(containing_tiles_dict.keys())>1): active_image = WindowManager.getImage("Fused") else: active_image = WindowManager.getImage("tile_"+key+".ome.tif") for point in containing_tiles_dict[key]: masterXs.append(point[3]+subupcoords_dict["tile_"+str(point[0])][0]) masterYs.append(point[4]+subupcoords_dict["tile_"+str(point[0])][1]) proi = PolygonRoi(masterXs,masterYs,Roi.FREEROI) active_image.setRoi(proi) return active_image
def __init__(self): self.mainDir = "" self.frame = JFrame("Dots Quality Check", size=(250,300)) self.frame.setLocation(20,120) self.Panel = JPanel(GridLayout(0,1)) self.frame.add(self.Panel) self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom) self.Panel.add(self.openNextButton) self.saveButton = JButton('Save',actionPerformed=save) self.saveButton.setEnabled(False) self.Panel.add(self.saveButton) self.cropButton = JButton('Crop values from here', actionPerformed=cropVals) self.Panel.add(self.cropButton) self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell) self.DiscardButton.setEnabled(True) self.Panel.add(self.DiscardButton) self.quitButton = JButton('Quit script',actionPerformed=quit) self.Panel.add(self.quitButton) annoPanel = JPanel() #add gridlayout wtRButton = JRadioButton("wt", actionCommand="wt") defectRButton = JRadioButton("Defect", actionCommand="defect") annoPanel.add(wtRButton) annoPanel.add(defectRButton) self.aButtonGroup = ButtonGroup() self.aButtonGroup.add(wtRButton) self.aButtonGroup.add(defectRButton) self.Panel.add(annoPanel) self.ProgBar = JProgressBar() self.ProgBar.setStringPainted(True) self.ProgBar.setValue(0) self.Panel.add(self.ProgBar) self.pathLabel = JLabel("-- No main directory chosen --") self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER ) self.Panel.add(self.pathLabel) WindowManager.addWindow(self.frame) self.show()
def bSaveZProject(imp, dstFolder, shortname): #bring to front impWinStr = imp.getTitle() IJ.selectWindow(impWinStr) bPrintLog('Making Z-Project from ' + impWinStr, 2) madez = 0 z1 = 1 z2 = imp.getNSlices() if z2>1: paramStr = 'start=%s stop=%s projection=[Max Intensity]' % (z1, z2) IJ.run('Z Project...', paramStr) #makes 'MAX_' window zWinStr = 'MAX_' + impWinStr zImp = WindowManager.getImage(zWinStr) madez = 1 else: zImp = imp if dstFolder != None: dstFile = dstFolder + 'max_' + shortname + '.tif' bPrintLog('Saving Z-Project: ' + dstFile, 2) bSaveStack(zImp, dstFile) if madez: zImp.changes = 0 zImp.close()
def myrun(self): imp = IJ.openImage(self.path) #open imp if imp is None: print 'ERROR opening file:', self.path return 0 numSlices = imp.getNSlices() if numSlices<2: return 0 middleSlice = int(math.floor(imp.getNSlices() / 2)) #int() is necc., python is f*****g picky imp.show() imp.setSlice(middleSlice) impTitle = imp.getTitle() impWin = WindowManager.getWindow(impTitle) #returns java.awt.Window transformationFile = os.path.basename(self.path) transformationFile = os.path.splitext(transformationFile)[0] + '.txt' transformationFile = '/Users/cudmore/Desktop/out/' + transformationFile stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(impWin,transformationFile) IJ.run('MultiStackReg', stackRegParams) imp.close() ''' #20150723, we just aligned on a cropped copy, apply alignment to original imp origImpTitle = imp.getTitle() stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origImpTitle,transformationFile) IJ.run('MultiStackReg', stackRegParams) ''' '''
def runPoreDetection(): '''roiManager=RoiManager(False) roiManager.runCommand("open", roiname) roiHash=roiManager.getROIs() roi=roiHash.get("Right") print roi''' imageList=Utility.GetOpenImageList() nbgd=NonBlockingGenericDialog(Messages.AddRoi) nbgd.addMessage(Messages.ChooseImage) if (imageList==None): IJ.showMessage(Messages.noOpenImages) return; nbgd.addChoice("Image1:", imageList, imageList[0]); nbgd.showDialog() name = nbgd.getNextChoice() inputImp = WindowManager.getImage(name) inputDataset=Utility.getDatasetByName(data, name) detectionParameters=DetectionParameters(10, 200, 0.5, 1.0, 0.3) #inputImp.setRoi(roi) nbgd2=NonBlockingGenericDialog(Messages.PositionRoi) nbgd2.addMessage(Messages.PositionRoiAndPressOK) nbgd2.showDialog() poreDetectionUV(inputImp, inputDataset, inputImp.getRoi().clone(), ops, data, display, detectionParameters)
def close_non_image_window(window_name): # forcefully closes one specific non image window frames = WindowManager.getNonImageWindows() for i in range(len(frames)): #IJ.log(frames[i].getTitle()) if (frames[i].getTitle() == window_name): frames[i].dispose()
def __init__(self): self.mainDir = "" self.setTitle("Dots Quality Check") self.setSize(250, 300) self.setLocation(20,120) self.addWindowFocusListener(self) self.Panel = JPanel(GridLayout(0,1)) self.add(self.Panel) self.openNextButton = JButton("Open Next Random", actionPerformed=self.openRandom) self.Panel.add(self.openNextButton) self.saveButton = JButton("Save", actionPerformed=self.save, enabled=False) self.Panel.add(self.saveButton) self.cropButton = JButton("Crop values from here", actionPerformed=self.cropVals) self.Panel.add(self.cropButton) self.DiscardButton = JButton("Discard cell", actionPerformed=self.discardCell) self.Panel.add(self.DiscardButton) self.quitButton = JButton("Quit script",actionPerformed=self.quit) self.Panel.add(self.quitButton) annoPanel = JPanel() #add gridlayout self.wtRButton = JRadioButton("wt", actionCommand="wt") self.wtRButton.addActionListener(self) self.defectRButton = JRadioButton("Defect", actionCommand="defect") self.defectRButton.addActionListener(self) annoPanel.add(self.wtRButton) annoPanel.add(self.defectRButton) self.aButtonGroup = ButtonGroup() self.aButtonGroup.add(self.wtRButton) self.aButtonGroup.add(self.defectRButton) self.Panel.add(annoPanel) self.ProgBar = JProgressBar() self.ProgBar.setStringPainted(True) self.ProgBar.setValue(0) self.Panel.add(self.ProgBar) self.pathLabel = JLabel("-- No main directory chosen --") self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER ) self.Panel.add(self.pathLabel) WindowManager.addWindow(self) self.show()
def main(): """Get options and create new image.""" options = get_options() if options is not None: bwidth, bheight = options img_cur = WindowManager.getCurrentImage() img_new = boxed_intensities(img_cur, bwidth, bheight) img_new.show()
def loadVideoSegment(fwin, start, reduction, label): ''' Load a video segment, optionally trim the unused frames in the beginning (usually the 1st segment) - fwin: name of the window of the video file (already opened) - start: starting frame number, default = 1 - reduction: sampling rate (i.e. frame reduction factor) - label: label of the loaded substack ''' WM.setCurrentWindow(WM.getWindow(fwin)) im1 = IJ.getImage() nSlices = im1.getStack().getSize() IJ.run(im1, 'Make Substack...', ' slices=' + str(start) + '-' + str(nSlices) + '-' + str(reduction)) im2 = IJ.getImage() im2.setTitle('Substack ' + label) im1.close() return im2
def Resize(imp): gd = GenericDialog("Image size") scales = ["1024","2048","4096"] gd.addChoice("Choose image size",scales,scales[1]) gd.showDialog() scale_choice = gd.getNextChoice() IJ.run(imp,"Scale...", "x=- y=- z=1.0 width="+scale_choice+" height="+scale_choice+" interpolation=Bilinear average process create title=Scaled") scaled_imp = WindowManager.getImage("Scaled") return scaled_imp
def ridge_detect(imp, rd_max, rd_min, rd_width, rd_length): title = imp.getTitle() IJ.run(imp, "8-bit", ""); IJ.run(imp, "Ridge Detection", "line_width=%s high_contrast=%s low_contrast=%s make_binary method_for_overlap_resolution=NONE minimum_line_length=%s maximum=0" % (rd_width, rd_max, rd_min, rd_length)) IJ.run(imp, "Remove Overlay", "") skel = WindowManager.getImage(title + " Detected segments") IJ.run(skel, "Skeletonize (2D/3D)", "") skel.hide() return(skel)
def itemStateChanged(self,e): imgList = [] imgList.append(virginImage) for i in range(len(checkboxObjects)): if checkboxObjects[i].getState() == True: imgList.append(self.boxImages[i]) titles = WindowManager.getImageTitles() p = re.compile(r'^Result') for title in titles: m = p.search(title) if m is not None: computedImage = WindowManager.getImage(title) computedImage.close() IJ.showStatus("Computing...") computedImage = reduce(self.addImages,imgList) computedImage.show() IJ.showStatus("Ready")
def readResults(windowTitle): textPanel = WindowManager.getFrame(windowTitle).getTextPanel() headings = textPanel.getColumnHeadings() "get results from TextWindow with java.lang.string title" resolver = re.compile('\d+\t(?P<frame>\d+\.0+)\t(?P<fsDistance>\d+\.\d+)\t(?P<ffDistance>\d+\.\d+)\t(?P<ssDistance>\d+\.\d+)\t(?P<fVol>\d+\.\d+)\t(?P<sVol>\d+\.\d+)') frameA = [] distA = [] volFcA = [] volScA = [] #xFcA, yFcA, zFcA, xScA, yScA, zScA resPnl = WindowManager.getFrame(windowTitle).getTextPanel() for row in range(resPnl.getLineCount()): mo = resolver.match(resPnl.getLine(row)) frameA.append(int(float(mo.group('frame')))) distA.append(mo.group("fsDistance")) volFcA.append(mo.group("fVol")) volScA.append(mo.group("sVol")) return frameA, distA, volFcA, volScA
def merge_images(_imp1, _imp2, force_same_bit_depth): imp1 = _imp1.duplicate() imp2 = _imp2.duplicate() imp1.show(); imp2.show(); if(force_same_bit_depth): bd = max(imp1.getBitDepth(),imp2.getBitDepth()) if bd==16: convert_to_16bit(imp1) convert_to_16bit(imp2) if bd==32: convert_to_32bit(imp1) convert_to_32bit(imp2) IJ.run(imp1, "Merge Channels...", "c1=[%s] c2=[%s] create" % (imp1.getTitle(), imp2.getTitle())) imp_out = WindowManager.getImage("Composite") if not imp_out: imp_out = WindowManager.getImage("Merged") imp_out.hide() imp1.hide(); imp2.hide() return imp_out
def straighten(stackName): ''' IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3") IJ.open(stackName) imp = IJ.getImage() stack = imp.getImageStack() for i in xrange(1, imp.getNSlices()+1): image = ImagePlus(str(i), stack.getProcessor(i)) xvals = [] yvals = [] maxvals = [] j = 0 for k in xrange(0, 512, 2): IJ.makeRectangle(k, 0, 4, 512) IJ.run("Measure") table = RT.getResultsTable() x = table.getValue("XM", 0) y = table.getValue("YM", 0) #maxi = IJ.getResult("Max") table = [] xvals.append(k) yvals.append(y) #maxvals.append(maxi) #if maxvals[j] == 0 and j > 0: #yvals[j] = yvals[j-1] j += 1 print "xvals:", xvals print "yvals:", yvals mr = MR() IJ.run("Make Selection...", "freeline, "+str(xvals)+" ,"+ str(yvals)) #IJ.runMacro("makeSelection...", "freeline, "+str(xvals)+" ,"+ str(yvals)); #IJ.run("makeSelection(\"freeline\", xvals, yvals);") #IJ.run("Straighten...", "line = 80") ''' IJ.open(stackName) imp = IJ.getImage() stack = imp.getImageStack() print imp.getNSlices() for i in range(1, imp.getNSlices()+1): image = ImagePlus(str(i), stack.getProcessor(i)) IJ.runMacroFile("/Users/juliansegert/repos/Bio119_root_tracking/straightenOneImage.ijm") newImp = WM.getCurrentImage() fs = FileSaver(newImp) fs.saveAsTiff("/Users/juliansegert/Documents/Roots/Four_root_image_stacks/Pos01/"+str(i)+".tif") newImp.close()
def __selectMeasureStack(self) : # We allow the user to choose what to measure in the stack, and on which stack. gd1=NonBlockingGenericDialog("Stack Choice for measures") idimages=WindowManager.getIDList() images=[WindowManager.getImage(imgID) for imgID in idimages if WindowManager.getImage(imgID).getImageStackSize()>1 ] imagesnames=[img.getTitle() for img in images] activindex=0 for i in range(len(imagesnames)) : if imagesnames[i] == self.__activeTitle : activindex=i gd1.addChoice("Select a stack in the list : ",imagesnames,imagesnames[activindex]) gd1.showDialog() chosenstack=gd1.getNextChoice() self.__img=WindowManager.getImage(chosenstack) IJ.selectWindow(self.__img.getID()) if gd1.wasOKed() : return True else : return False
def run_script(): while WindowManager.getImageCount() < 10: create_test_image() image_titles = [WindowManager.getImage(id).getTitle() for id in WindowManager.getIDList()] # range(3) will create the list [0, 1, 2]. selected_indices = create_selection_dialog(image_titles, range(3)) # The script stops if the dialog has ben canceld (None was returned from create_selection_dialog). if selected_indices is None: print('Script was canceld.') return # We have to get the corresponding IMagePlus objects. selected_imps = [WindowManager.getImage(id) for id in [WindowManager.getIDList()[index] for index in selected_indices]] # The previous line can be split into 2 lines: # selected_ids = [WindowManager.getIDList()[index] for index in selected_indices] # selected_imps = [WindowManager.getImage(id) for id in selected_ids] for imp in selected_imps: # Strings can be formated using the % operator: # http://www.learnpython.org/en/String_Formatting IJ.log('The image \'%s\' has been selected.' % imp.getTitle())
def overlayImages(self, e): impBase = WindowManager.getImage(self.imageIDs[self.baseImageBox.getSelectedIndex()]) refBase = impBase.getStack().getProcessor(1) impOverlay = WindowManager.getImage(self.imageIDs[self.overlayImageBox.getSelectedIndex()]) refOverlay = impOverlay.getStack().getProcessor(1) print "Overlaying for stack sizes " + str(impBase.getStackSize()) + "/" + str(impOverlay.getStackSize()) + "..." stack = None if self.virtualStackCheckbox.isSelected(): stack = OverlayVirtualStack() stack.overlayOpacity = float(self.opacitySpinner.getValue())/100.0 stack.overlayColor = AWTColorToArray(self.overlayColorPreviewLabel.getBackground()) stack.base = impBase stack.overlay = impOverlay ImagePlus("Stack Overlay from " + self.imageNames[self.baseImageBox.getSelectedIndex()] + " and " + self.imageNames[self.overlayImageBox.getSelectedIndex()], stack).show() else: IJ.error("Not implemented yet", "Using normal stacks is not implemented yet. Please use the Virtual Stack option.")
def get_setup(): ''' Returns the drift correction mode and two image.''' options = drift.get_options() modes = drift.get_modes() dialog = GenericDialog('Jump-ratio setup') dialog.addMessage('Select the mode for drift correction\n' + 'and the images to process.') dialog.addChoice('Mode:', options, options[0]) image_ids = WindowManager.getIDList() if not image_ids or len(image_ids) < 2: return [None]*3 image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids] dialog.addMessage('Post-edge is divided by the pre-edge.') dialog.addChoice('Pre-edge', image_titles, image_titles[0]) dialog.addChoice('Post-edge', image_titles, image_titles[1]) dialog.showDialog() if dialog.wasCanceled(): return [None]*3 mode = modes[dialog.getNextChoiceIndex()] img1 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) img2 = WindowManager.getImage(image_ids[dialog.getNextChoiceIndex()]) return mode, img1, img2
def __init__(self): self.frame = JFrame("CellCropper: Experiment details", size=(400,200)) self.frame.setLocation(20,120) self.Panel = JPanel(GridLayout(4,2)) self.frame.add(self.Panel) self.Panel.add(JLabel("Date:")) self.dateField = JTextField( str(date.today()), 8 ) self.Panel.add(self.dateField) self.strainField = JTextField( "2926",4 ) self.Panel.add(self.strainField) self.tempField = JTextField( "34",2 ) self.Panel.add(self.tempField) self.ODField = JTextField( "0.5",3 ) self.Panel.add(self.ODField) self.condField = JTextField( "0.5",3 ) self.Panel.add(self.condField) self.OKButton = JButton("OK",actionPerformed=closeAndMakePos) self.Panel.add(self.OKButton) self.frame.pack() WindowManager.addWindow(self.frame) self.show()
def main(): # Get the wanted output directory and prepare subdirectories for output. outdir = IJ.getDirectory("output directory") # Open the 'Track statistics.csv' input file and format as getresults() dictionary. rt = opencsv() rt = getresults(rt) # Retrieve the current image as input (source) image. imp = WindowManager.getCurrentImage() cal = imp.getCalibration() IJ.log("Calibration: {}".format(cal.scaled())) # Run the main crop function on the source image. croppoints(imp, spots=rt, outdir=outdir, roi_x=150, roi_y=150) # Combine all output stacks into one movie. combinestacks(outdir, height=8)
def main(): # Get the wanted output directory and prepare subdirectories for output. outdir = IJ.getDirectory("output directory") # Open the 'Track statistics.csv' input file and format as getresults() dictionary. rt = opencsv() rt = getresults(rt) # Retrieve the current image as input (source) image. imp = WindowManager.getCurrentImage() # Run the main crop function on the source image. # croptracks(imp, tracks, outdir, trackid="TRACK_ID", # trackx="TRACK_X_LOCATION", tracky="TRACK_Y_LOCATION", # trackstart="TRACK_START", trackstop="TRACK_STOP", # roi_x=150, roi_y=150) croptracks(imp, tracks=rt, outdir=outdir, roi_x=150, roi_y=150) # Combine all output stacks into one movie. combinestacks(outdir, height=8)
def save_current_image_as_tiff(filename, filetype, target): """save the currently active image as ImageJ-Tiff Arguments: filename {string} -- filename of the image filetype {string} -- the original filetype of the image target {directory} -- directory where the image will be saved Returns: nothing """ imp = wm.getCurrentImage() savename = filename.replace(filetype, "_stitched.tif") savepath = target + savename IJ.log("now saving: " + str(savepath)) print "now saving", savepath IJ.saveAs(imp, "Tiff", savepath) imp.close() return savepath
def run(): Ch0dir = '/Volumes/TRANSCEND/Claudia/LGR5SegmentationTraining/DeformMask/' Ch1dir = '/Volumes/TRANSCEND/Claudia/LGR5SegmentationTraining/DeformMask/' DoubleChdir = '/Volumes/TRANSCEND/Claudia/LGR5SegmentationTraining/DeformDoubleChannelMask/' Raw_path = os.path.join(Ch0dir, '*tif') X = glob.glob(Raw_path) axes = 'YX' for fname in X: print(fname) IJ.open(fname); imp = IJ.getImage() Name = os.path.basename(os.path.splitext(fname)[0]) Ch1Name = Ch1dir + Name + '.tif' IJ.open(Ch1Name); impCh1 = IJ.getImage() IJ.run("Merge Channels...", "c1="+imp.getTitle()+ " c2="+impCh1.getTitle()+ " create"); IJ.saveAs('.tif', DoubleChdir + Name); imp.close(); impCh1.close(); composite = wm.getFrontWindow() if composite is not None: done = composite.close()
def pointList3DFromRT(tableName,modifierX = 0,modifierY = 0,modifierZ = 0, XColumn='X (microns)', YColumn='Y (microns)', ZColumn='Z (microns)'): win = WindowManager.getWindow(tableName) rt = win.getResultsTable() X = rt.getColumn(rt.getColumnIndex(XColumn)) Y = rt.getColumn(rt.getColumnIndex(YColumn)) Z = rt.getColumn(rt.getColumnIndex(ZColumn)) # X = rt.getColumn(XColumn) # Y = rt.getColumn(YColumn) # Z = rt.getColumn(ZColumn) dplist = [] for x, y, z in zip(X, Y, Z): array = [] array.append(x+modifierX) array.append(y+modifierY) array.append(z+modifierZ) jArray = jarray.array(array, 'd') dp = DoublePoint(jArray) dplist.append(dp) return dplist
def save_current_image_as_bdv(filename, filetype, target): """save the currently active image as BigDataViewer hdf5/xml Arguments: filename {string} -- filename of the image filetype {string} -- the original filetype of the image target {directory} -- directory where the image will be saved Returns: nothing """ imp = wm.getCurrentImage() savename = filename.replace(filetype, "_stitched.xml") savepath = target + savename IJ.log("now saving: " + str(savepath)) print "now saving", savepath IJ.run("Export Current Image as XML/HDF5", " use_deflate_compression export_path=[" + savepath + "]") imp.close() return savepath
def main(): #summary = False if (WindowManager.getImageCount() > 0): IJ.run("Save") image_dir = processImage() # if (WindowManager.getImageCount() > 0): # for image in range(WindowManager.getImageCount()): # processImage() else: #summary = True #selected_dir = IJ.getDirectory("Select Directory") if not selected_dir.endswith(os.path.sep): selected_dir = selected_dir + os.path.sep dir_list = list() file_type = [".tif", ".tiff"] image_list = listDir(selected_dir, file_type = file_type, recursive = False) for image in image_list: IJ.open(image) image_dir = processImage() summarize(os.path.join(image_dir, "markers" )) summarize(os.path.join(image_dir, "processed_markers"))
def calculateNNDsByCluster(tableName): win = WindowManager.getWindow(tableName) rt = win.getResultsTable() C = rt.getColumn(4) nrOfClusters = int(max(C)) NR = rt.getColumn(0) C = rt.getColumn(4) X = rt.getColumn(1) Y = rt.getColumn(2) Z = rt.getColumn(3) points = list(zip(NR,X,Y,Z,C)) points.sort(key = itemgetter(4)) groups = groupby(points, itemgetter(4)) clusters = [[(item[1], item[2], item[3], item[0]) for item in data] for (key, data) in groups] offset = 0; for cluster in clusters: dplist = [] for x, y, z, nr in cluster: array = [] array.append(x) array.append(y) array.append(z) array.append(nr) jArray = jarray.array(array, 'd') dp = DoublePoint(jArray) dplist.append(dp) nearestNeighborsDist, nearestNeighborsInd = calculateNNDs(dplist) index = 0 for point in cluster: row = int(point[3]) - 1 rt.setValue("nn. dist", row, nearestNeighborsDist[index]) rt.setValue("neighbor", row, nearestNeighborsInd[index]+1+offset) index = index + 1 offset = offset + len(cluster); win.rename("tmp") win.rename(tableName)
def run(): global numRep images = map(WM.getImage, WM.getIDList()) nStacks = len(images) #num of stacks opened numSlices = [images[i].getNSlices() for i in range(nStacks)] #[12,13,12] maxSlice = max( numSlices) #the max number of slices among all opened stacks #maxIndex = [i for i,j in enumerate(numSlices) if j == maxSlice] # the index of the image with maxSlice #move max to the head and min to the end imps = [ image for (numSlice, image) in sorted(zip(numSlices, images), reverse=True) ] #sort the images base on their nSlices numRep = zyGetProperty(imps[0], "nFrame") #add slices in imp[0], base on (nStacks-1)*numRep impDup(imps[0], nStacks) #for other imps, loop them and copy/paste every 3(numRep) into imp for i in range(nStacks - 1): n = i + 1 binder(imps[0], imps[n], nStacks, n) #set the nFrame = nStacks*numRep, and save the image # record the numSlices, numFrame, totalSlices and numStacks in the infoStr zyAddProperty(imps[0]) msgStr = "nslices=" + str(maxSlice / numRep) + " nframes=" + str( nStacks * numRep) #IJ.run(imps[0], "Properties...", msgStr) IJ.log("For real: " + msgStr) file_path = IJ.getDirectory('image') file_name = imps[0].getTitle() filename = 'C_' + file_name imps[0].setTitle(filename) destPath = os.path.join(file_path, 'combined') saveStack(destPath, filename, imps[0])
def save_current_image_with_BF_as_ics1(filename, filetype, target): """saves a given ImagePlus as ics1 using Bio-Formats Parameters ---------- imp : ImagePlus an open ImagePlus to be saved filename : str Filename of the image filetype : str The original filetype of the image target : string path to the original image on disc """ imp = wm.getCurrentImage() savename = filename.replace(filetype, "_stitched.ids") savepath = os.path.join(target, savename) IJ.log("now saving: " + str(savepath)) print "now saving", savepath IJ.run(imp, "Bio-Formats Exporter", "save=[" + savepath + "]") imp.close() return savepath
def Compositor(timepoints, channels, dirs): """ Creates composite images of all channels for each timepoint. """ # Creates composite stack from HDD images. for time in range (1, (timepoints*channels), channels): stack = IJ.run( "Image Sequence...", "open=" + dirs["Projections"] + " number=" + str(channels) + " starting=" + str(time) + " increment=1 scale=400 file=.tif sort") comp = IJ.run("Make Composite", "display=Composite") comp = IJ.run("Stack to RGB", comp) IJ.saveAs(comp, "Tiff", os.path.join(dirs["Composites"], "Timepoint"+str(time/channels).zfill(3))) # Close windows. for i in range (2): try: imp = WindowManager.getCurrentImage() imp.close() except: pass
def scaleImageUI(): gd = GenericDialog("Scale") gd.addSlider("Scale", 1, 200, 100) gd.addCheckbox("Preview", True) # The UI elements for the above two inputs slider = gd.getSliders().get(0) # the only one checkbox = gd.getCheckboxes().get(0) # the only one imp = WM.getCurrentImage() if not imp: print "Open an image first!" return previewer = ScalingPreviewer(imp, slider, checkbox) slider.addAdjustmentListener(previewer) checkbox.addItemListener(previewer) gd.showDialog() if gd.wasCanceled(): previewer.reset() print "User canceled dialog!" else: previewer.scale()
def generateCardiomyocyteMask(cmIp, method="Otsu", stack=True, minCmSize=500, brightfield = False): cmIp.setTitle("CmStain") if brightfield: IJ.run(cmIp, "Find Edges", "stack") if not stack: IJ.setAutoThreshold(cmIp, "{} dark".format(method)) IJ.run(cmIp, "Convert to Mask", "method={} background=Dark calculate".format(method)) else: IJ.setAutoThreshold(cmIp, "{} dark stack".format(method)) IJ.run(cmIp, "Convert to Mask", "method={} background=Dark stack".format(method)) if brightfield: IJ.run(cmIp, "Morphological Filters (3D)", "operation=Closing element=Ball x-radius=2 y-radius=2 z-radius=0") delIp = cmIp delIp.changes = False delIp.close() cmIp = WindowManager.getImage("CmStain-Closing") IJ.run(cmIp,"Fill Holes", "stack") cmIp.show() IJ.run("Set Measurements...", "stack redirect=None decimal=3") IJ.run(cmIp, "Analyze Particles...", "size={}-Infinity show=[Masks] exclude in_situ stack".format(cmMinSize)) cmMaskIp = cmIp.duplicate() IJ.run(cmIp, "Analyze Particles...", "size={}-Infinity show=[Count Masks] exclude in_situ stack".format(cmMinSize)) cmMaskIp.show(), cmIp.show() return cmIp, cmMaskIp
def importMask(evt=None): display = Display.getFront() # Obtain an image stack #imp = IJ.getImage() imp = WindowManager.getImage("Labels") layerset = display.getLayerSet() p = layerset.getProject() ali = AreaList(p, "", 0, 0) layerset.add(ali) p.getProjectTree().insertSegmentations([ali]) # Obtain the image stack stack = imp.getImageStack() # Iterate every slice of the stack for i in range(1, imp.getNSlices() + 1): ip = stack.getProcessor(i) # 1-based # Extract all areas (except background) into a map of value vs. java.awt.geom.Area m = AreaUtils.extractAreas(ip) # Report progress if len(m) > 0: IJ.log(str(i) + ":" + str(len(m))) # Get the Layer instance at the corresponding index layer = layerset.getLayers().get(i-1) # 0-based # Add the first Area instance to the AreaList at the proper Layer if ( m.values().iterator().hasNext() ): ali.addArea(layer.getId(), m.values().iterator().next()) # Change the color of the AreaList ali.setColor(Color.red) ali.adjustProperties() # Ensure bounds are as constrained as possible ali.calculateBoundingBox(None) # Repaint Display.repaint()
def duplicateMaskInRoi(imp, roi, duplicateStack=False): imp.setRoi(roi) if duplicateStack: WindowManager.setCurrentWindow(imp.getWindow()) impMT1 = IJ.run("Duplicate...", "duplicate") impMT1 = WindowManager.getCurrentImage() else: impMT1 = imp.crop() IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") IJ.run(impMT1, "Create Selection", "") roi1 = impMT1.getRoi() bounds = roi1.getBounds() if duplicateStack: WindowManager.setCurrentWindow(impMT1.getWindow()) IJ.run("Duplicate...", "duplicate") impMT = WindowManager.getCurrentImage() impMT1.close() else: impMT = impMT1.crop() IJ.run(impMT, "Canvas Size...", "width="+str(bounds.width+2)+" height="+str(bounds.height+2)+" position=Center zero") return impMT, bounds
from fiji.plugin.trackmate.io import TmXmlReader, TmXmlWriter from fiji.plugin.trackmate.util import TMUtils from fiji.plugin.trackmate.action import ExportStatsToIJAction, ExportTracksToXML from fiji.plugin.trackmate.detection import DetectorKeys from fiji.plugin.trackmate.features import FeatureAnalyzer, ModelFeatureUpdater, SpotFeatureCalculator from fiji.plugin.trackmate.features.spot import SpotContrastAndSNRAnalyzerFactory, SpotContrastAndSNRAnalyzer from fiji.plugin.trackmate.features.track import TrackDurationAnalyzer, TrackSpeedStatisticsAnalyzer import fiji.plugin.trackmate.features.track.TrackDurationAnalyzer as TrackDurationAnalyzer import fiji.plugin.trackmate.features.SpotFeatureCalculator as SpotFeatureCalculator import fiji.plugin.trackmate.features.spot.SpotContrastAndSNRAnalyzer as SpotContrastAndSNRAnalyzer import fiji.plugin.trackmate.features.spot.SpotIntensityAnalyzerFactory as SpotIntensityAnalyzerFactory # Get currently selected image imp = WindowManager.getCurrentImage() #imp = IJ.openImage('http://fiji.sc/samples/FakeTracks.tif') #imp.show() #---------------------------- # Create the model object now #---------------------------- # Some of the parameters we configure below need to have # a reference to the model at creation. So we create an # empty model now. model = Model() # Send all messages to ImageJ log window. model.setLogger(Logger.IJ_LOGGER)
# use the same renaming trick as for the macro recorder imp.setTitle("current") # IJ.run executes commands from the macro recorder IJ.run( "Scale...", "x=.5 y=.5 z=1.0 width=128 height=128 depth=930 interpolation=Bilinear average process create" ) imp.close() IJ.selectWindow("current-1") IJ.run("Z Project...", "projection=[Average Intensity]") # Note the new imports above, WindowManager and ImageCalculator # ic.run executes commands within image calculator; wm.getImage selects the image using WindowsManager imp = ic.run("Subtract create 32-bit stack", wm.getImage("current-1"), wm.getImage("AVG_current-1")) imp.show() imp = ic.run("Divide create 32-bit stack", wm.getImage("Result of current-1"), wm.getImage("AVG_current-1")) imp.show() IJ.selectWindow("Result of Result of current-1") # adjust the Brightness/Contrast IJ.setMinAndMax(-0.0200, 0.2000) # this is the Lookup Tables step IJ.run("Aselfmade3") # IJ.saveAs has 3 arguments: (image, file type, file path) IJ.saveAs(IJ.getImage(), "Tiff", out_folder + the_file + '-processed')
return retSeqP from ij.measure import ResultsTable from ij import WindowManager from ij.gui import NonBlockingGenericDialog from ij import IJ import sys sys.path.append( IJ.getDirectory("imagej") + "/jars/HaralickFeaturesInteractive/") from Haralick_Features import Haralick_Features as hf cmChan = int(IJ.getProperty("cmChan")) analyte = WindowManager.getCurrentImage() analyte.setC(cmChan) title = analyte.getTitle() cmNumber = IJ.getProperty("cmNumber") if cmNumber is None: cmNumber = 1 IJ.setProperty("cmNumber", cmNumber) cmNumber += 1 sarcomereLength = IJ.getProperty("sarcomereLength") if sarcomereLength is None: sarcomereLength = 1.5 icalibration = analyte.getCalibration() pixelDistance = round(icalibration.getRawX(sarcomereLength)) pixelDistance = round(icalibration.getRawX(sarcomereLength)) retval = findMaximaSeqs([ list(hfi) for hfi in hf().calculate(analyte, "Sarcomeres", 45,
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
def check_existence(title): if WindowManager.getIDList() is None: return False image_titles = (WindowManager.getImage(id).getTitle() for id in WindowManager.getIDList()) return title in image_titles
def runOneFile(fullFilePath): global gNumChannels global gAlignBatchVersion if not os.path.isfile(fullFilePath): bPrintLog( '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n', 0) return 0 bPrintLog( time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1) enclosingPath = os.path.dirname(fullFilePath) head, tail = os.path.split(enclosingPath) enclosingPath += '/' #make output folders destFolder = enclosingPath + tail + '_channels/' if not os.path.isdir(destFolder): os.makedirs(destFolder) destMaxFolder = destFolder + 'max/' if not os.path.isdir(destMaxFolder): os.makedirs(destMaxFolder) if gDoAlign: destAlignmentFolder = destFolder + 'alignment/' if not os.path.isdir(destAlignmentFolder): os.makedirs(destAlignmentFolder) if gSave8bit: eightBitFolder = destFolder + 'channels8/' if not os.path.isdir(eightBitFolder): os.makedirs(eightBitFolder) eightBitMaxFolder = eightBitFolder + 'max/' if not os.path.isdir(eightBitMaxFolder): os.makedirs(eightBitMaxFolder) # open image imp = Opener().openImage(fullFilePath) # get parameters of image (width, height, nChannels, nSlices, nFrames) = imp.getDimensions() bitDepth = imp.getBitDepth() infoStr = imp.getProperty("Info") #get all .tif tags if not infoStr: infoStr = '' infoStr += 'bAlignBatch_Version=' + str(gAlignBatchVersion) + '\n' infoStr += 'bAlignBatch_Time=' + time.strftime( "%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n' msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \ + ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth) bPrintLog(msgStr, 1) path, filename = os.path.split(fullFilePath) shortName, fileExtension = os.path.splitext(filename) # # look for num channels in ScanImage infoStr if gGetNumChanFromScanImage: for line in infoStr.split('\n'): #scanimage.SI4.channelsSave = [1;2] scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0 #state.acq.numberOfChannelsSave=2 scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0 if scanimage3: #print 'line:', line equalIdx = find(line, '=') line2 = line[equalIdx + 1:] if gGetNumChanFromScanImage: gNumChannels = int(line2) bPrintLog( 'over-riding gNumChannels with: ' + str(gNumChannels), 2) if scanimage4: #print ' we have a scanimage 4 file ... now i need to exptract the number of channel' #print 'line:', line equalIdx = find(line, '=') line2 = line[equalIdx + 1:] for delim in ';[]': line2 = line2.replace(delim, ' ') if gGetNumChanFromScanImage: gNumChannels = len(line2.split()) bPrintLog( 'over-riding gNumChannels with: ' + str(gNumChannels), 2) # show imp.show() # split channels if necc. and grab the original window names if gNumChannels == 1: origImpWinStr = imp.getTitle() #use this when only one channel origImpWin = WindowManager.getWindow( origImpWinStr) #returns java.awt.Window if gNumChannels == 2: winTitle = imp.getTitle() bPrintLog('Deinterleaving 2 channels...', 1) IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost origCh1WinStr = winTitle + ' #1' origCh2WinStr = winTitle + ' #2' origCh1Imp = WindowManager.getImage(origCh1WinStr) origCh2Imp = WindowManager.getImage(origCh2WinStr) origCh1File = destFolder + shortName + '_ch1.tif' origCh2File = destFolder + shortName + '_ch2.tif' # work on a copy, mostly for alignment with cropping copy = Duplicator().run(imp) #copy.copyAttributes(imp) #don't copy attributes, it copies the name (which we do not want) copy.show() # # crop (on copy) if gDoCrop: bPrintLog('making cropping rectangle (left,top,width,height) ', 1) bPrintLog( str(gCropLeft) + ' ' + str(gCropTop) + ' ' + str(gCropWidth) + ' ' + str(gCropHeight), 2) roi = Roi(gCropLeft, gCropTop, gCropWidth, gCropHeight) #left,top,width,height copy.setRoi(roi) time.sleep( 0.5 ) # otherwise, crop SOMETIMES failes. WHAT THE F**K FIJI DEVELOPERS, REALLY, WHAT THE F**K #bPrintLog('cropping', 1) IJ.run('Crop') infoStr += 'bCropping=' + str(gCropLeft) + ',' + str( gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n' # # remove calibration ( on original) if gRemoveCalibration: cal = imp.getCalibration() calCoeff = cal.getCoefficients() if calCoeff: msgStr = 'Calibration is y=a+bx' + ' a=' + str( calCoeff[0]) + ' b=' + str(calCoeff[1]) bPrintLog(msgStr, 1) #remove calibration bPrintLog('\tRemoving Calibration', 2) imp.setCalibration(None) #without these, 8-bit conversion goes to all 0 !!! what the f**k !!! #bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2) imp.resetStack() imp.resetDisplayRange() #get and print out min/max origMin = StackStatistics(imp).min origMax = StackStatistics(imp).max msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax) bPrintLog(msgStr, 2) # 20150723, 'shift everybody over by linear calibration intercept calCoeff[0] - (magic number) if 1: # [1] was this #msgStr = 'Subtracting original min '+str(origMin) + ' from stack.' #bPrintLog(msgStr, 2) #subArgVal = 'value=%s stack' % (origMin,) #IJ.run('Subtract...', subArgVal) # [2] now this #msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.' #bPrintLog(msgStr, 2) #addArgVal = 'value=%s stack' % (int(calCoeff[0]),) #IJ.run('Add...', addArgVal) # [3] subtract a magic number 2^15-2^7 = 32768 - 128 magicNumber = gLinearShift #2^15 - 128 msgStr = 'Subtracting a magic number (linear shift) ' + str( magicNumber) + ' from stack.' bPrintLog(msgStr, 2) infoStr += 'bLinearShift=' + str(gLinearShift) + '\n' subArgVal = 'value=%s stack' % (gLinearShift, ) IJ.run(imp, 'Subtract...', subArgVal) # 20150701, set any pixel <0 to 0 if 0: ip = imp.getProcessor() # returns a reference pixels = ip.getPixels() # returns a reference msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...' bPrintLog(msgStr, 2) pixels = map(lambda x: 0 if x < 0 else x, pixels) bPrintLog('\t\t... done', 2) #get and print out min/max newMin = StackStatistics(imp).min newMax = StackStatistics(imp).max msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax) bPrintLog(msgStr, 2) #append calibration to info string infoStr += 'bCalibCoeff_a = ' + str(calCoeff[0]) + '\n' infoStr += 'bCalibCoeff_b = ' + str(calCoeff[1]) + '\n' infoStr += 'bNewMin = ' + str(newMin) + '\n' infoStr += 'bNewMax = ' + str(newMax) + '\n' # # set up if gNumChannels == 1: impWinStr = copy.getTitle() #use this when only one channel impWin = WindowManager.getWindow(impWinStr) #returns java.awt.Window if gNumChannels == 2: winTitle = copy.getTitle() bPrintLog('Deinterleaving 2 channels...', 1) IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost ch1WinStr = winTitle + ' #1' ch2WinStr = winTitle + ' #2' ch1Imp = WindowManager.getImage(ch1WinStr) ch2Imp = WindowManager.getImage(ch2WinStr) ch1File = destFolder + shortName + '_ch1.tif' ch2File = destFolder + shortName + '_ch2.tif' # # alignment if gDoAlign and gNumChannels == 1 and copy.getNSlices() > 1: infoStr += 'AlignOnChannel=1' + '\n' #snap to middle slice if gAlignOnMiddleSlice: middleSlice = int( math.floor(copy.getNSlices() / 2)) #int() is necc., python is f*****g picky else: middleSlice = gAlignOnThisSlice copy.setSlice(middleSlice) transformationFile = destAlignmentFolder + shortName + '.txt' bPrintLog('MultiStackReg aligning:' + impWinStr, 1) stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % ( impWin, transformationFile) IJ.run('MultiStackReg', stackRegParams) infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n' #20150723, we just aligned on a cropped copy, apply alignment to original imp origImpTitle = imp.getTitle() stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origImpTitle, transformationFile) IJ.run('MultiStackReg', stackRegParams) if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices( ) > 1 and ch2Imp.getNSlices() > 1: #apply to gAlignThisChannel alignThisWindow = '' applyAlignmentToThisWindow = '' if gAlignThisChannel == 1: infoStr += 'AlignOnChannel=1' + '\n' transformationFile = destAlignmentFolder + shortName + '_ch1.txt' alignThisWindow = ch1WinStr applyAlignmentToThisWindow = ch2WinStr else: infoStr += 'AlignOnChannel=2' + '\n' transformationFile = destAlignmentFolder + shortName + '_ch2.txt' alignThisWindow = ch2WinStr applyAlignmentToThisWindow = ch1WinStr alignThisImp = WindowManager.getImage(alignThisWindow) #snap to middle slice if gAlignOnMiddleSlice: middleSlice = int( math.floor(alignThisImp.getNSlices() / 2)) #int() is necc., python is f*****g picky else: middleSlice = gAlignOnThisSlice alignThisImp.setSlice(middleSlice) infoStr += 'bAlignOnSlice=' + str(middleSlice) + '\n' bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1) stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % ( alignThisWindow, transformationFile) IJ.run('MultiStackReg', stackRegParams) # 20150723, we just aligned on a copy, apply alignment to both channels of original # ch1 bPrintLog('MultiStackReg applying alignment to:' + origCh1WinStr, 1) stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origCh1WinStr, transformationFile) IJ.run('MultiStackReg', stackRegParams) # ch2 bPrintLog('MultiStackReg applying alignment to:' + origCh2WinStr, 1) stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origCh2WinStr, transformationFile) IJ.run('MultiStackReg', stackRegParams) #apply alignment to other window #bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1) #applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow) #stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile) #IJ.run('MultiStackReg', stackRegParams) elif gDoAlign: bPrintLog('Skipping alignment, there may be only one slice?', 3) # # save if gNumChannels == 1: imp.setProperty("Info", infoStr) impFile = destFolder + shortName + '.tif' #bPrintLog('Saving:' + impFile, 1) bSaveStack(imp, impFile) #max project bSaveZProject(imp, destMaxFolder, shortName) if gNumChannels == 2: #ch1 origCh1Imp.setProperty("Info", infoStr) #bPrintLog('Saving:' + ch1File, 1) bSaveStack(origCh1Imp, ch1File) #max project bSaveZProject(origCh1Imp, destMaxFolder, shortName + '_ch1') #ch2 origCh2Imp.setProperty("Info", infoStr) #bPrintLog('Saving:' + ch2File, 1) bSaveStack(origCh2Imp, ch2File) #max project bSaveZProject(origCh2Imp, destMaxFolder, shortName + '_ch2') # # post convert to 8-bit and save if gSave8bit: if bitDepth == 16: if gNumChannels == 1: bPrintLog('Converting to 8-bit:' + impWinStr, 1) IJ.selectWindow(impWinStr) #IJ.run('resetMinAndMax()') IJ.run("8-bit") impFile = eightBitFolder + shortName + '.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(imp, impFile) #max project bSaveZProject(imp, eightBitMaxFolder, shortName) if gNumChannels == 2: # bPrintLog('Converting to 8-bit:' + origCh1WinStr, 1) IJ.selectWindow(origCh1WinStr) IJ.run("8-bit") impFile = eightBitFolder + shortName + '_ch1.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(origCh1Imp, impFile) #max project bSaveZProject(origCh1Imp, eightBitMaxFolder, shortName + '_ch1') # bPrintLog('Converting to 8-bit:' + origCh2WinStr, 1) IJ.selectWindow(origCh2WinStr) #IJ.run('resetMinAndMax()') IJ.run("8-bit") impFile = eightBitFolder + shortName + '_ch2.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(origCh2Imp, impFile) #max project bSaveZProject(origCh2Imp, eightBitMaxFolder, shortName + '_ch2') # # close original window imp.changes = 0 imp.close() #copy copy.changes = 0 copy.close() # # close ch1/ch2 if gNumChannels == 2: #original origCh1Imp.changes = 0 origCh1Imp.close() origCh2Imp.changes = 0 origCh2Imp.close() #copy ch1Imp.changes = 0 ch1Imp.close() ch2Imp.changes = 0 ch2Imp.close() bPrintLog( time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
from ij.text import TextPanel as TP from ij.measure import ResultsTable as RT # Create a non-blocking dialog to enter the metadata psgd = NonBlockingGenericDialog( "Choose the frame that shows the right conformation of the heart?") psgd.addNumericField("Which frame to choose?", 1, 0) psgd.addCheckbox("Use table of selected frames?", False) psgd.showDialog() choose = psgd.getNextNumber() choice = psgd.getCheckboxes().get(0).getState() #open a tab separated txt file with one column Frame selected if choice == 1: choose = 0 IJ.run("Table... ", "open=") frametable = WM.getWindow("selected_frames.txt") meta = frametable.getTextPanel() metaRT = TP.getResultsTable(meta) # Choose a directory directory_load = DirectoryChooser( "Select the directory of your files").getDirectory() directory_load = directory_load.replace("\\", "/") # get a list of all files in the directory dList = os.listdir(directory_load) # set a counter to 1 n = 1 for i in dList: dL = directory_load + "/" + str(i)
from ij import IJ, WindowManager from ij.gui import Line IJ.run("Close All") imp = IJ.openImage("/Users/jrminter/Downloads/three_phase.jpeg") IJ.run(imp, "RGB to CIELAB", "") IJ.run("Stack to Images", "") imp_L = WindowManager.getImage("L") imp_a = WindowManager.getImage("a") imp_b = WindowManager.getImage("b") the_line = Line(0,178,690,178) the_line.setWidth(20) imp_L.setRoi(the_line) imp_L.show() IJ.run(imp_L, "Plot Profile", "") imp_a.setRoi(Line(0,231,690,220)) IJ.run(imp_a, "Plot Profile", "") imp_a.show()
def runOneTif(tifPath, dstTifPath): bPrintLog('=== runOneTif processing tif:' + tifPath, 3) bPrintLog('Loading file...', 3) imp = IJ.openImage(tifPath) if imp is None: bPrintLog('ERROR: could not open image from file:' + tifPath, 3) return 0 logStr = 'done loading file: ' + str(imp.width) + ' ' + str(imp.height) + ' ' + str(imp.getNSlices()) bPrintLog(logStr, 3) numSlices = imp.getNSlices() if numSlices>1: pass else: bPrintLog('ERROR: number of slices must be more than one, file: ' + tifPath) return 0 bPrintLog('numSlices: ' + str(numSlices), 3) infoStr = imp.getProperty("Info") #get all tags #print infoStr if infoStr is None: infoStr = '' infoStr += 'bAverageFrames=v0.1\n' imp.setProperty("Info", infoStr) imp.show() impWin = imp.getTitle() # # start body #infer type of file from # get the actual bit depth used (e.g. ScanImage is 11 bit, Prairie is 13 bit) header = bParseHeader(imp) b_sequence = '' if 'b_sequence' in header: b_sequence = str(header['b_sequence']) bPrintLog('b_sequence: ' + b_sequence, 3) madeAverage = 0 # if numSlices is not divisable by gNumToAverage then chop a few slices off bottom/end if b_sequence.startswith('TSeries'): if globalOptions['gNumToAverage'] > 1: numToRemove = numSlices % globalOptions['gNumToAverage'] if numToRemove > 0: bPrintLog('Removing bottom slices: ' + str(numToRemove), 3) # run("Slice Remover", "first=3 last=5 increment=1"); removeArgs = 'first=' + str(numSlices-numToRemove+1) + ' last=' + str(numSlices) + ' increment=1' IJ.run('Slice Remover', removeArgs) numSlices = imp.getNSlices() bPrintLog('numSlices: ' + str(numSlices), 3) #fix this: if stack is really short this will not be taken if (numSlices > globalOptions['gNumToAverage']): bPrintLog('Taking average of ' + str(globalOptions['gNumToAverage']) + ' slices from ' + str(numSlices), 3) stackRegParams = 'projection=[Average Intensity] group=' + str(globalOptions['gNumToAverage']) IJ.run('Grouped Z Project...', stackRegParams) # makes window AVG_ madeAverage = 1 avgWindow = 'AVG_' + impWin avgImp = WindowManager.getImage(avgWindow) avgSlices = avgImp.getNSlices() # Grouped Z PRoject swaps slices for frames? tmpSlices = avgImp.getNSlices() tmpFrames = avgImp.getNFrames() if tmpFrames > 1: newSlices = tmpFrames newFrames = tmpSlices nChannels = 1 bPrintLog('Swaping frames for slices after grouped z',3) bPrintLog('newSlices=' + str(newSlices) + ' newFrames='+str(newFrames), 4) avgImp.setDimensions(nChannels, newSlices, newFrames) infoStr += 'gNumToAverage=' + str(globalOptions['gNumToAverage']) + '\n' # I want to adjust the framePeriod, prairie would be 'b_framePeriod' avgImp.setProperty("Info", infoStr) else: avgImp = imp avgSlices = numSlices else: bPrintLog('Not taking average of sequence: ' + b_sequence,3) avgImp = imp avgSlices = numSlices if globalOptions['medianFilter']>0: bPrintLog('Running median filter: ' + str(globalOptions['medianFilter']), 3) medianArgs = 'radius=' + str(globalOptions['medianFilter']) + ' stack' IJ.run(avgImp, "Median...", medianArgs); infoStr += 'bMedianFilter=' + str(globalOptions['medianFilter']) + '\n' avgImp.setProperty("Info", infoStr) # convert to 8 bit # 1) read bit depth from header (e.g. 2^13) # 2) do math on image and convert to 8-bit # run("Divide...", "value=32 stack"); if globalOptions['gConvertToEightBit']: bPrintLog('converting to 8-bit by dividing image down and then convert to 8-bit with ImageConverter.setDoScaling(False)', 3) bitDepth = 2^13 divideBy = bitDepth / 2^8 # divide the 13 bit image down to 8 bit #run("Divide...", "value=32 stack"); bPrintLog('divideBy:' + str(divideBy), 3) divideArgs = 'value=' + str(divideBy) + ' stack' IJ.run(avgImp, "Divide...", divideArgs); # convert to 8-bit will automatically scale, to turn this off use # eval("script", "ImageConverter.setDoScaling(false)"); ImageConverter.setDoScaling(False) # run("8-bit"); bPrintLog('converting to 8-bit with setDoScaling False', 3) IJ.run(avgImp, "8-bit", ''); bPrintLog('Saving stack with ' + str(avgSlices) + ' slices:' + dstTifPath, 3) fs = FileSaver(avgImp) if avgSlices>1: fs.saveAsTiffStack(dstTifPath) else: fs.saveAsTiff(dstTifPath) if madeAverage: avgImp.changes = 0 avgImp.close() imp.changes = 0 imp.close() # end body # # why was this here #imp.changes = 0 #imp.close() return 1
with open(path.getPath()) as csvfile: reader = csv.DictReader(csvfile) for row in reader: files.append(row) for sets in files: name = "" for filename in sets: if os.path.isfile(inputDirectory + filename): imp = IJ.openImage(inputDirectory + filename) else: imp = IJ.openImage(empty) imp.show() name = filename IJ.run("Images to Stack", "name=Stack title=[] use") imp2 = WindowManager.getCurrentImage() # the Stack #WaitForUserDialog("Title", "Try adjust balance").show() #try: IJ.run(imp2, "Make Montage...", "co lumns=5 rows=1 scale=0.5 border = 3") imp3 = WindowManager.getCurrentImage() # the Montage #FileSaver(imp2).saveAsTiff(outputDirectory + time + '_' + column + '_' + condition + "superstack.tif") FileSaver(imp3).saveAsPng(outputDirectory + name + "_custommontage.png") #IJ.run(imp2, "Save", "save=" + outputDirectory + time + '_' + column + '_' + condition + "superstack.tif") #IJ.run(imp3, "Save", "save=" + outputDirectory + time + '_' + column + '_' + condition + "supermontage.tif") imp3.close() IJ.run("Close All", "") print("Done!")
self.yScale=self.xScale self.YscaleField.setText(str(self.yScale)) self.toXfield.setText(str(self.xScale*self.impXpixel)) self.toYfield.setText(str(self.yScale*self.impYpixel)) elif source==self.YscaleField: self.yScale=float(source.getText()) self.toYfield.setText(str(self.yScale*self.impYpixel)) elif source==self.toXfield: self.toXpixel=float(source.getText()) self.xScale=self.toXpixel/self.impXpixel elif source==self.toYfield: self.toYpixel=float(source.getText()) self.yScale=self.toYpixel/self.impYpixel dg=ScaleRoiDialog() scale=dg.inputScale() roiMng=WindowManager.getWindow('ROI Manager') def scaleTypeROI(roi): if isinstance(roi,PointRoi): p=roi.getFloatPolygon() x,y=list(p.xpoints),list(p.ypoints) xNew,yNew=map(lambda c:c*scale[0],x),map(lambda c:c*scale[1],y) roiNew=PointRoi(xNew,yNew) elif isinstance(roi,ShapeRoi): roiSels=roi.getRois() roiNews=map(scaleTypeROI,roiSels) roiNew=0 for roi in roiNews: if roiNew==0: roiNew=ShapeRoi(roi) else:
def erase(): i = WindowManager.getImageCount() while i > 0: WindowManager.getImage(WindowManager.getNthImageID(i)).close() i = i - 1
color = 'white' draw(i, j, array, color) def draw_field(field, selectedX, selectedY): for j in range(0, 8): for i in range(0, 8): draw_one(i, j, field, selectedX, selectedY) IJ.setTool(Toolbar.HAND) field = initial_field() currentX = -1 currentY = -1 draw_field(field, currentX, currentY) canvas = WindowManager.getCurrentImage().getCanvas() clicked = 0 while True: p = canvas.getCursorLoc() x = int(p.x / w) y = int(p.y / h) newClicked = canvas.getModifiers() & 16 if clicked and not newClicked: if currentX >= 0: if x != currentX or y != currentY: oldOffset = currentX + 8 * currentY field[x + 8 * y] = field[oldOffset] field[oldOffset] = '' draw_one(currentX, currentY, field, -1, -1) draw_one(x, y, field, -1, -1)
imp2 = IJ.openImage(inputDirectory + "/" + image.replace("stack", "montage")) imp.show() imp2.show() gd = GenericDialog("?") gd.addChoice("Would you like to adjust this one?", ["No", "Yes"], "No") gd.showDialog() if gd.getNextChoice() == "Yes": imp2.close() IJ.run("Brightness/Contrast...") WaitForUserDialog("Title", "Adjust intensities").show() IJ.run("Stack to Images", "") IJ.run(imp, "Merge Channels...", "c2=Green c3=Blue c6=Magenta c7=Yellow create keep") imp = WindowManager.getCurrentImage() IJ.run(imp, "RGB Color", "") IJ.run(imp, "Images to Stack", "name=Stack title=[] use") #WaitForUserDialog("Title", "Now you should have a stack check it out ").show() imp = WindowManager.getCurrentImage() # the Stack imp.show() IJ.setForegroundColor(255, 255, 255) IJ.run( imp, "Make Montage...", "columns=5 rows=1 scale=0.5 borderWidth = 2 useForegroundColor = True" ) #WaitForUserDialog("Title", "Now we should have the montage").show() IJ.run( "Save", "save=" + outputDirectory + '/' + image.replace("stack", "newmontage"))
neg = IJ.openImage(folder + "\\vessels_negative.tif") negroi = neg.getRoi() pos.close() IJ.run("Select None", "") channels = ChannelSplitter.split(neg) neg.close() image = channels[3] channels = channels[0:3] proc = image.getProcessor() directional_op = ImagePlus("directional_op", proc) IJ.run(directional_op, "Directional Filtering", "type=Max operation=Opening line=30 direction=32") directional_op = WindowManager.getImage("directional_op-directional") tubes = range(5, 130, 12) img_source = ImagePlus("image", proc) src = clij2.push(img_source) dst = clij2.create(src) sigma = 2 clij2.gaussianBlur2D(src, dst, sigma, sigma) img_blur2 = clij2.pull(dst) src.close() dst.close() print("Tubeness mt start") tubenesses = [None] * len(tubes) rang = range(len(tubes))