def calculate_mean_r(imp, ring_rois, centres): """calculate the average distance of the cell surface from the vessel axis""" w = imp.getWidth() h = imp.getHeight() rp = FloatProcessor(w, h) rpix = rp.getPixels() for lidx, (roi, centre) in enumerate(zip(ring_rois, centres)): for thetaidx, (x, y) in enumerate( zip(roi.getPolygon().xpoints, roi.getPolygon().xpoints)): rpix[lidx * w + thetaidx] = math.sqrt((x - centre[0])**2 + (y - centre[1])**2) rimp = ImagePlus("Radii", rp) IJ.setAutoThreshold(rimp, "Intermodes light") bp = rimp.createThresholdMask() bp.dilate() bp.erode() mask_imp = ImagePlus("Mask", bp) IJ.run(mask_imp, "Create Selection", "") roi = mask_imp.getRoi() rimp.setRoi(roi) mean_r = rimp.getStatistics().mean rimp.close() mask_imp.close() return mean_r
def nuclei_processor(imp_particles, thresh_type, folder, impname, channel_name): rm = RoiManager.getInstance() if not rm: rm = RoiManager() rm.reset() # define a results table rt = ResultsTable.getResultsTable() imp_particles.show() # generate thresholded image for ROI nuclei = imp_particles.duplicate() nuclei.show() IJ.run("Gaussian Blur...", "sigma=3") IJ.setAutoThreshold(nuclei, thresh_type) IJ.run("Convert to Mask") IJ.run("Fill Holes") # IJ.run("Watershed") # select thresholded image (to set ROIs) IJ.run( "Set Measurements...", "area mean standard min area_fraction limit display add redirect=[" + imp_particles.title + "] decimal=3") IJ.run("Analyze Particles...", "size=30-Infinity show=Outlines display clear add") # get the ROI manager and save rm.runCommand( "save selected", os.path.join(folder, impname + '_' + channel_name + "_ROIs.zip"))
def Analyze(imp): IJ.setAutoThreshold(imp, "Otsu Dark stack") IJ.run(imp, "Convert to Mask", "method=MaxEntropy background=Dark calculate black") #IJ.run(imp, "Invert", "stack") #IJ.run(imp, "Despeckle", "stack") IJ.run(imp, "Watershed", "stack") IJ.run(imp, "Analyze Particles...", "size=2-Infinity pixel show=Masks summarize stack")
def segmentNuc(impc2): impdup = Duplicator().run(impc2) IJ.run(impdup, "8-bit", "") IJ.run(impdup, "Gaussian Blur...", "sigma=1.5 stack") # AutoThresholder().getThreshold(AutoThresholder.Method.valuOf('Otsu'), int[] histogram) IJ.setAutoThreshold(impdup, "Otsu dark") IJ.run(impdup, "Convert to Mask", "stack") #IJ.setAutoThreshold(impdup, "Otsu dark") #opt = PA.SHOW_MASKS + PA.SHOW_RESULTS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing opt = PA.SHOW_MASKS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing ##area mean centroid bounding integrated stack redirect=None decimal=4 meas = Meas.AREA + Meas.MEAN + Meas.CENTROID + Meas.RECT + Meas.INTEGRATED_DENSITY + Meas.STACK_POSITION rt = ResultsTable().getResultsTable() pa = PA(opt, meas, rt, 10.0, 300000.0, 0, 1.0) PA.processStack = True pa.setHideOutputImage(True) ##run("Analyze Particles...", "size=800-Infinity circularity=0.00-1.00 pixel show=Masks display exclude include stack"); outstack = ImageStack(impdup.getWidth(), impdup.getHeight()) for i in range(1,impdup.getStackSize()+1): impdup.setSlice(i) pa.analyze(impdup) impbin = pa.getOutputImage() outstack.addSlice(impbin.getProcessor()) impbin = ImagePlus("out", outstack) IJ.run(impbin, "Invert LUT", "") #IJ.run(impbin, "Fill Holes", "stack") return impbin, rt
def binarize(f): Prefs.blackBackground = True imp = IJ.openImage(f) if imp: binimp = imp.duplicate() bs = BackgroundSubtracter() ip = binimp.getProcessor() bs.rollingBallBackground(ip, 15, False, False, False, True, True) IJ.run(binimp, "Unsharp Mask...", "radius=2 mask=0.9") def smooth(n=1): for i in range(n): IJ.run(binimp, "Smooth", "") smooth(10) IJ.setAutoThreshold(binimp, "Moments dark") IJ.run(binimp, "Make Binary", "thresholded remaining") smooth(12) IJ.setAutoThreshold(binimp, "Moments white") IJ.run(binimp, "Make Binary", "thresholded remaining") IJ.run(binimp, "Erode", "") IJ.run(binimp, "Dilate", "") IJ.run(binimp, "Analyze Particles...", "size=250-Infinity circularity=0.2-1.00 exclude clear add") binimp.close() else: pass
def threshold(imp, lower, upper): duplicate=Duplicator().run(imp) duplicate.getProcessor().resetMinAndMax() IJ.setAutoThreshold(duplicate, "Default dark"); IJ.setThreshold(duplicate, lower, upper) IJ.run(duplicate, "Convert to Mask", ""); return duplicate
def receive_image(): print "recieving an image ....." the_data=request.data fh = open("imageToSave.jpg", "wb") fh.write(the_data) fh.close() imp=IJ.openImage("C:/Users/Lynn/Documents/GitHub/server/imageToSave.jpg") IJ.run(imp,"8-bit","") IJ.run(imp,"Subtract Background...", "rolling=100 light disable") IJ.setAutoThreshold(imp,"Default") IJ.setAutoThreshold(imp,"Triangle") IJ.setThreshold(imp,0, 237) #Macro.setOptions("BlackBackground") IJ.run(imp, "Convert to Mask","") IJ.run(imp, "Convert to Mask","") IJ.run(imp, "Make Binary","") IJ.run(imp,"Fill Holes","") IJ.run(imp,"Watershed","") #IJ.run(imp,"Analyze Particles...", "size=2000-20000 display clear summarize add") IJ.run(imp,"Analyze Particles...", "size=6000-18000 circularity=0.07-0.25 show=[Overlay Outlines] display clear summarize") imp.show() FileSaver(imp).saveAsJpeg("C:/Users/Lynn/Documents/GitHub/server/imageToSave3.jpg") with open("imageToSave3.jpg", "rb") as imageFile: to_be_sent_str = imageFile.read() #print imp test=bytearray(to_be_sent_str) print "done" #RoiManager.runCommand("Show All with labels") #RoiManager.runCommand("Show All") #return "other" return test
def binarize_image(imp_in, str_thr, black_bkg): """ binarize_image Parameters ---------- imp_in: ImagePlus The ImagePlus to binarize str_thr String The threshold string. Example: "Default" black_bkg: Boolean Whether the background is black (True) or not (False) Returns ------- imp_out ImagePlus The binarized image """ imp_out = imp_in.duplicate() ti = imp.getShortTitle() imp_out.setTitle(ti + "_bin") IJ.setAutoThreshold(imp_out, str_thr) Prefs.blackBackground = black_bkg IJ.run(imp_out, "Make Binary", "") IJ.run(imp_out, "Convert to Mask", "") return (imp_out)
def analyze(imagefile, outdir, size=10000): """Opens a file and creates masks.""" masks = [] image = IJ.openImage(imagefile) imagetitle = image.getTitle().split(".")[0] # close existing Summary window rtframe = WindowManager.getFrame("Summary") if rtframe is not None: rtframe.close() # segmentation IJ.setAutoThreshold(image, "Default dark"); IJ.run(image, "Options...", "iterations=1 count=1 do=Nothing"); #IJ.run(mask, "Convert to Mask", ""); IJ.run(image, "Analyze Particles...", "size=0-"+str(size)+" show=Masks summarize"); masks.append(IJ.getImage()) IJ.run(image, "Analyze Particles...", "size="+str(size)+"-infinity show=Masks summarize"); masks.append(IJ.getImage()) # get ResultsTable object and save it rt = WindowManager.getFrame("Summary").getTextPanel().getResultsTable() rtfile = path.join(outdir, str(size)+"Summary_" + imagetitle + ".csv") rt.save(rtfile) # create multi-color merged mask mergedmask = RGBStackMerge.mergeChannels(masks, False) for m in masks: m.close() mergedmask.setTitle(imagetitle + "-mask.tif") outputfile = path.join(outdir, mergedmask.getTitle()) IJ.saveAs(mergedmask, "TIFF", outputfile)
def resetpressed(event): self.__ranges.clear() self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() IJ.setAutoThreshold(self.__image, "MaxEntropy") rt=ResultsTable() pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00) pa.analyze(self.__image) self.__roisArray=[] self.__roisArray=rm.getRoisAsArray() #rm.runCommand("Show All") #rm.runCommand("Select All") #rm.runCommand("Set Color", "blue") IJ.resetThreshold(self.__image) keys=self.__slidersDict.keys() for k in keys: if k.endswith("min"): self.__slidersDict[k].setValue(0) self.__slidersDict[k].repaint() else: self.__slidersDict[k].setValue(self.__slidersDict[k].getMaximum()) self.__slidersDict[k].repaint()
def ThresholdMaxEntropy(imp0): """Thresholds image and returns thresholded image, merge code still quite clumsy but functional""" imp0 = IJ.getImage() impthres = imp0.duplicate() imp01 = ImagePlus("Channel1", ChannelSplitter.getChannel(imp0, 1)) imp02 = ImagePlus("Channel2", ChannelSplitter.getChannel(imp0, 2)) imp001 = imp01.duplicate() imp002 = imp02.duplicate() IJ.setAutoThreshold(imp001, "MaxEntropy dark") IJ.run(imp001, "Convert to Mask", "") IJ.run(imp001, "Divide...", "value=255") IJ.setAutoThreshold(imp002, "MaxEntropy dark") IJ.run(imp002, "Convert to Mask", "") IJ.run(imp002, "Divide...", "value=255") ic = ImageCalculator() imp0001 = ic.run("Multiply create", imp01, imp001) ic2 = ImageCalculator() imp0002 = ic2.run("Multiply create", imp02, imp002) imp0001.copy() impthres.setC(1) impthres.paste() imp0002.copy() impthres.setC(2) impthres.paste() imp01.close() imp02.close() imp001.close() imp002.close() imp0001.close() imp0002.close() return impthres
def Generate_segmented_image(imp, channel): imp_Threshold_1 = ExtractChannel(imp1, channel) imp_Threshold_1.setTitle(("Threshold" + "Channel" + str(channel))) imp_Threshold_1.show() IJ.run(imp_Threshold_1, "Median...", "radius=1") IJ.run(imp_Threshold_1, "Subtract Background...", "rolling=50") IJ.setAutoThreshold(imp_Threshold_1, "Triangle dark") #Prefs.blackBackground = True; IJ.run(imp_Threshold_1, "Convert to Mask", "") return imp_Threshold_1
def Generate_segmented(imp, channel, threshold_method, filtersize): imp_Threshold_1 = ExtractChannel(imp1, channel) imp_Threshold_1.setTitle(("Threshold" + "Channel" + str(channel))) imp_Threshold_1.show() IJ.run(imp_Threshold_1, "Median...", "radius=" + str(filtersize)) IJ.run(imp_Threshold_1, "Subtract Background...", "rolling=50") IJ.setAutoThreshold(imp_Threshold_1, threshold_method + " dark") #Prefs.blackBackground = True; IJ.run(imp_Threshold_1, "Convert to Mask", "") return imp_Threshold_1
def get_threshold(imp, method): # from ij.process import AutoThresholder # from ij.process import ImageStatistics # thresholder = AutoThresholder() # stats = imp.getProcessor().getStatistics() # value = thresholder.getThreshold(method, stats.histogram) arg = "%s dark" % method IJ.setAutoThreshold(imp, arg) value = imp.getProcessor().getMinThreshold() IJ.resetThreshold(imp) return value
def process(imp): try: IJ.run(imp, "Subtract Background...", "rolling=50"); IJ.run(imp, "Subtract Background...", "rolling=50"); ImageConverter.setDoScaling(True); IJ.run(imp, "32-bit", ""); IJ.run(imp, "Smooth", ""); IJ.setAutoThreshold(imp, "Default dark"); IJ.run(imp, "NaN Background", ""); return imp; except(AttributeError): print("error processing!");
def measureChannels(ROIset, imp, frameNumber): rm = RoiManager.getInstance() if not rm: rm = RoiManager() nChannels = imp.getNChannels() for channel in range(nChannels): target_imp = extractChannel(imp, channel + 1, frameNumber) target_imp.show() for roi in ROIset: rm.setSelectedIndexes([roi]) IJ.setAutoThreshold(target_imp, "Huang dark") rm.runCommand(target_imp, "Measure") target_imp.close()
def getRadius(image): IJ.run('8-bit') Img = IJ.getImage() IJ.run('Invert') IJ.setAutoThreshold(Img, 'Default') IJ.run('Convert to Mask') # Must change units to pixels --> 10px. minimum IJ.run(Img, 'Analyze Particles...', 'size=10-Infinity show=[Overlay Outlines] display clear') rt = IJ.getTextPanel() data = [] for line in range(rt.getLineCount()): data.append(rt.getLine(line)) return data
def generateNucleusMask(nucIp, method="Otsu", stack=True, minNucleusSize=50): nucMaskIp = nucIp.duplicate() if not stack: IJ.setAutoThreshold(nucMaskIp, "{} dark".format(method)) IJ.run(nucMaskIp, "Convert to Mask", "method={} background=Dark calculate".format(method)) else: IJ.setAutoThreshold(nucMaskIp, "{} dark stack".format(method)) IJ.run(nucMaskIp, "Convert to Mask", "method={} background=Dark stack".format(method)) IJ.run(nucMaskIp, "Open", "stack") IJ.run("Set Measurements...", "stack redirect=None decimal=3") IJ.run(nucMaskIp, "Analyze Particles...", "size={}-Infinity circularity=0.2-1.00 show=Masks exclude in_situ stack".format(minNucleusSize)) IJ.run(nucMaskIp,"Fill Holes", "stack") nucMaskIp.show() return nucMaskIp
def apply_threshold(imp, method='Otsu', background_threshold='dark', stackopt=False, corrf=1.0): # one threshold value for the whole stack with correction if stackopt: # create argument string for the IJ.setAutoThreshold thcmd = method + ' ' + background_threshold + ' stack' # set threshold and get the lower threshold value IJ.setAutoThreshold(imp, thcmd) ip = imp.getProcessor() # get the threshold value and correct it lowth = ip.getMinThreshold() lowth_corr = int(round(lowth * corrf, 0)) # process stack with corrected threshold value imp = ThresholdTools.apply_threshold_stack_corr(imp, lowth_corr, method=method) # threshold slice-by-slice with correction if not stackopt: # get the stack stack = imp.getStack() # get the stack within the ImagePlus nslices = stack.getSize() # get the number of slices print('Slices: ' + str(nslices)) print('Thresholding slice-by-slice') for index in range(1, nslices + 1): ip = stack.getProcessor(index) # get the histogramm hist = ip.getHistogram() # get the threshold value lowth = ThresholdTools.apply_autothreshold(hist, method=method) lowth_corr = int(round(lowth * corrf, 0)) ip.threshold(lowth_corr) # convert to 8bit without rescaling ImageConverter.setDoScaling(False) ImageConverter(imp).convertToGray8() return imp
def getMask(imp, chan): dup = Duplicator() mask = dup.run(imp, chan, chan, 1,1, 1,1) sigma = 0.2 IJ.run(mask, "Gaussian Blur...", "sigma="+str(sigma)+" scaled") if chan==1: method = "Otsu" else: method = "MaxEntropy" IJ.setAutoThreshold(mask, method+" dark") Prefs.blackBackground = True IJ.run(mask, "Convert to Mask", "") IJ.run(mask, "Close-", "") IJ.run(mask, "Watershed", "") return mask
def Generate_segmented_bgsub(imp, channel, threshold_method, filtersize): imp_Threshold_1 = ExtractChannel(imp1, channel) imp_Threshold_1.setTitle(("Threshold" + "Channel" + str(channel))) imp_Threshold_1.show() IJ.run(imp_Threshold_1, "Select All", "") stats = imp_Threshold_1.getStatistics(Measurements.MEAN | Measurements.STD_DEV) IJ.run(imp_Threshold_1, "Select None", "") background = stats.mean + (2 * stats.stdDev) IJ.run(imp_Threshold_1, "Subtract...", "value=" + str(background)) IJ.run(imp_Threshold_1, "Median...", "radius=" + str(filtersize)) IJ.run(imp_Threshold_1, "Subtract Background...", "rolling=50") IJ.setAutoThreshold(imp_Threshold_1, threshold_method + " dark") #Prefs.blackBackground = True; IJ.run(imp_Threshold_1, "Convert to Mask", "") return imp_Threshold_1
def countobjects(imp, rt, subtractBackground=False, watershed=False, dilate=False, threshMethod="Otsu", physicalUnits=True, minSize=0.00, maxSize=float("inf"), minCirc=0.00, maxCirc=1.00): """Threshold and count objects in channel 'channelNumber'. This function splits an image in the separate channels, and counts the number of objects in the thresholded channel. Args: imp: An ImagePlus with 1 frame, 1 slice. Returns: A list of filepaths. """ cal = imp.getCalibration() if subtractBackground: IJ.run(imp, "Subtract Background...", "rolling=50") IJ.setAutoThreshold(imp, "{} dark".format(threshMethod)) IJ.run(imp, "Convert to Mask", "") if dilate: IJ.run(imp, "Dilate", "") if watershed: IJ.run(imp, "Watershed", "") if physicalUnits: # Convert physical units to pixels for the current calibration. minSize = cal.getRawX(math.sqrt(minSize))**2 maxSize = cal.getRawX(math.sqrt(maxSize))**2 pa = ParticleAnalyzer( ParticleAnalyzer.SHOW_OVERLAY_OUTLINES | ParticleAnalyzer.DISPLAY_SUMMARY, #int options Measurements.AREA | Measurements.SHAPE_DESCRIPTORS | Measurements.MEAN | Measurements.CENTROID | Measurements.LABELS, #int measurements rt, #ResultsTable minSize, #double maxSize, #double minCirc, #double maxCirc) #double pa.analyze(imp) return imp
def SegmentMask(ip): ''' Returns a Region of Interest (ROI) that contains a proposed segmentation for the input image processor imp Binarization: Find the GaussianBlur with minimum radius necessary to perform a Minimum Autothreshold ''' minThresholdValue=-1 radius=GaussianBlurParam['initialRadius'] #Initial Radius os the Gaussian Blur contador=0 while (minThresholdValue==-1 and contador<6): contador=contador+1 #Make a copy of the image impThres = ImagePlus() ipThres = ip.duplicate() impThres.setProcessor("Copy for thresholding", ipThres) GaussianBlur().blurGaussian( impThres.getProcessor(), radius, radius,GaussianBlurParam['accuracy']) #impThres.show() try: IJ.setAutoThreshold(impThres, "Minimum dark") minThresholdValue = impThres.getProcessor().getMinThreshold() except: print("No threshold found for segmentation") if minThresholdValue !=-1: #Check thresholded image contains at least 50% of the original stats = impThres.getStatistics() histogram = stats.histogram binSize=(stats.max-stats.min)/256 ThresholdBin=int(round((minThresholdValue-stats.min)/binSize)) CumulativeValues=0 for i in range(ThresholdBin): CumulativeValues+=histogram[i] ImageAboveThreshold=1-float(CumulativeValues)/(ip.width*ip.height) #(ImageAboveThreshold) #ImageAboveThreshold must be above 50% if ImageAboveThreshold < 0.5: minThresholdValue=-1 radius=radius+1 impThres.getProcessor().setThreshold(minThresholdValue, stats.max, ImageProcessor.NO_LUT_UPDATE) boundRoi = ThresholdToSelection.run(impThres) return boundRoi
def renyiBinarization(self): try: IJ.selectWindow(self.primaryImage) primaryImageID = IJ.getImage() IJ.setAutoThreshold(primaryImageID, "RenyiEntropy dark") IJ.setThreshold(self.primaryLowerThreshold, self.primaryUpperThreshold) IJ.run("Convert to Mask") IJ.selectWindow(self.secondaryImage) secondaryImageID = IJ.getImage() IJ.setAutoThreshold(secondaryImageID, "RenyiEntropy dark") IJ.setThreshold(self.secondaryLowerThreshold, self.secondaryUpperThreshold) IJ.run("Convert to Mask") except: print("unable to binarize images.") finally: return self
def analyze(image, outdir, index, size=10000): """Opens a file and creates masks.""" masks = [] imagetitle = image.getTitle().split(".")[0] # segmentation IJ.setAutoThreshold(image, "Default dark"); IJ.run(image, "Options...", "iterations=1 count=1 do=Nothing"); #IJ.run(mask, "Convert to Mask", ""); IJ.run(image, "Analyze Particles...", "size=0-"+str(size)+" show=Masks summarize display"); masks.append(IJ.getImage()) IJ.run(image, "Analyze Particles...", "size="+str(size)+"-infinity show=Masks summarize display"); masks.append(IJ.getImage()) # create multi-color merged mask mergedmask = RGBStackMerge.mergeChannels(masks, False) for m in masks: m.close() mergedmask.setTitle(imagetitle + "-"+str(index)+"-mask.tif") outputfile = path.join(outdir, mergedmask.getTitle()) IJ.saveAs(mergedmask, "TIFF", outputfile)
def auto_threshold(imp, ch_name, is_auto_thresh, method="IsoData"): if is_auto_thresh: IJ.setAutoThreshold(imp, "{} dark".format(method)) thres_min = imp.getProcessor().getMinThreshold() else: imp.show() IJ.run("Threshold...") # this is the method to wait the user set up the threshold wu = WaitForUserDialog("Set manual threshold for {}".format(ch_name), "Use slider to adjust threshold and press OK") wu.show() thres_min = imp.getProcessor().getMinThreshold() thres_max = imp.getProcessor().getMaxThreshold() IJ.log(" -- {}: Min threshold {}".format(ch_name, thres_min)) IJ.setThreshold(imp, thres_min, thres_max) imp.hide() WindowManager.getWindow("Threshold").close() return thres_min
def create_mock_resultstable(): """Creates small ResultsTable with fictive values""" # Create a ImageJ ResultsTable, convert it into Omero table object, upload and link it to target object imp = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif") imp.show() mask = imp.duplicate() IJ.run(mask, "Median...", "radius=2") IJ.run(mask, "Options...", "iterations=1 count=1 black") IJ.setAutoThreshold(mask, "Default") IJ.run(mask, "Convert to Mask", "") IJ.run(mask, "Watershed", "") IJ.run( mask, "Set Measurements...", "area mean min centroid integrated display redirect=%s decimal=3" % imp.getTitle()) IJ.run(mask, "Analyze Particles...", "size=0-Infinity display exclude clear summarize add") imp.close() rt = ResultsTable.getResultsTable() rt.show("Results") return rt
def Segment_Nuclei(imp, channel): imp_Threshold_1 = ExtractChannel(imp1, channel) imp_Threshold_1.setTitle(("Threshold" + "Channel" + str(channel))) imp_Threshold_1.show() IJ.run(imp_Threshold_1, "Subtract...", "value=5000") IJ.run(imp_Threshold_1, "Median...", "radius=3") #IJ.run(imp_Threshold_1, "Subtract Background...", "rolling=500"); IJ.setAutoThreshold(imp_Threshold_1, "Li dark") #Prefs.blackBackground = True; IJ.run(imp_Threshold_1, "Convert to Mask", "") IJ.run(imp_Threshold_1, "Erode", "") IJ.run(imp_Threshold_1, "Erode", "") IJ.run(imp_Threshold_1, "Erode", "") IJ.run(imp_Threshold_1, "Erode", "") IJ.run(imp_Threshold_1, "Erode", "") IJ.run(imp_Threshold_1, "Dilate", "") IJ.run(imp_Threshold_1, "Dilate", "") IJ.run(imp_Threshold_1, "Dilate", "") IJ.run(imp_Threshold_1, "Dilate", "") IJ.run(imp_Threshold_1, "Dilate", "") #IJ.run(imp_Threshold_1, "Dilate", ""); return imp_Threshold_1
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 prepareImage(passDir, passFile, passOutput, passPixels, passBlur, passThreshold): # Attempt to open as image, exit if not fullPath = os.path.join(passDir, passFile) retImage = IJ.openImage(fullPath) if not retImage: return None retImage.show() # Resize canvas to prepare for fast rotations, select original imgWidth = retImage.getWidth() imgHeight = retImage.getHeight() maxDim = math.sqrt(imgWidth ** 2 + imgHeight ** 2) borderX = (maxDim - imgWidth)/2 borderY = (maxDim - imgHeight)/2 IJ.run("Canvas Size...", "width={0} height={0} position=Center".format(maxDim)) IJ.makeRectangle(borderX, borderY, imgWidth, imgHeight) # Set scale to pixels (will manually calculate later) IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel"); # Blur "overhanging" projections IJ.run("Gaussian Blur...", "sigma={0}".format(passBlur)) # Set threshold IJ.setAutoThreshold(retImage, "{0} dark apply".format(passThreshold)) IJ.makeRectangle(0, 0, retImage.getWidth(), retImage.getHeight()) # Analyze particles and obtain outline image IJ.run("Analyze Particles...", "size={0}-Infinity show=Outlines pixel clear".format(passPixels)); IJ.selectWindow("Drawing of {0}".format(retImage.getTitle())) fileParts = passFile.split(".") IJ.save(os.path.join(passOutput, "{0}-outline-{1}.{2}".format(fileParts[0], passThreshold, '.'.join(fileParts[1:])))) IJ.run("Close") return retImage
def analyze_homogeneity(image_title): IJ.selectWindow(image_title) raw_imp = IJ.getImage() IJ.run(raw_imp, "Duplicate...", "title=Homogeneity duplicate") IJ.selectWindow('Homogeneity') hg_imp = IJ.getImage() # Get a 2D image if hg_imp.getNSlices() > 1: IJ.run(hg_imp, "Z Project...", "projection=[Average Intensity]") hg_imp.close() IJ.selectWindow('MAX_Homogeneity') hg_imp = IJ.getImage() hg_imp.setTitle('Homogeneity') # Blur and BG correct the image IJ.run(hg_imp, 'Gaussian Blur...', 'sigma=' + str(HOMOGENEITY_RADIUS) + ' stack') # Detect the spots IJ.setAutoThreshold(hg_imp, HOMOGENEITY_THRESHOLD + " dark") rm = RoiManager(True) table = ResultsTable() pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES, Measurements.AREA, # measurements table, # Output table 0, # MinSize 500, # MaxSize 0.0, # minCirc 1.0) # maxCirc pa.setHideOutputImage(True) pa.analyze(hg_imp) areas = table.getColumn(table.getHeadings().index('Area')) median_areas = compute_median(areas) st_dev_areas = compute_std_dev(areas, median_areas) thresholds_areas = (median_areas - (2 * st_dev_areas), median_areas + (2 * st_dev_areas)) roi_measurements = {'integrated_density': [], 'max': [], 'area': []} IJ.setForegroundColor(0, 0, 0) for roi in rm.getRoisAsArray(): hg_imp.setRoi(roi) if REMOVE_CROSS and hg_imp.getStatistics().AREA > thresholds_areas[1]: rm.runCommand('Fill') else: roi_measurements['integrated_density'].append(hg_imp.getStatistics().INTEGRATED_DENSITY) roi_measurements['max'].append(hg_imp.getStatistics().MIN_MAX) roi_measurements['integrated_densities'].append(hg_imp.getStatistics().AREA) rm.runCommand('Delete') measuremnts = {'mean_integrated_density': compute_mean(roi_measurements['integrated_density']), 'median_integrated_density': compute_median(roi_measurements['integrated_density']), 'std_dev_integrated_density': compute_std_dev(roi_measurements['integrated_density']), 'mean_max': compute_mean(roi_measurements['max']), 'median_max': compute_median(roi_measurements['max']), 'std_dev_max': compute_std_dev(roi_measurements['max']), 'mean_area': compute_mean(roi_measurements['max']), 'median_area': compute_median(roi_measurements['max']), 'std_dev_area': compute_std_dev(roi_measurements['max']), } # generate homogeinity image # calculate interpoint distance in pixels nr_point_columns = int(sqrt(len(measuremnts['mean_max']))) # TODO: This is a rough estimation that does not take into account margins or rectangular FOVs inter_point_dist = hg_imp.getWidth() / nr_point_columns IJ.run(hg_imp, "Maximum...", "radius="+(inter_point_dist*1.22)) # Normalize to 100 IJ.run(hg_imp, "Divide...", "value=" + max(roi_measurements['max'] / 100)) IJ.run(hg_imp, "Gaussian Blur...", "sigma=" + (inter_point_dist/2)) hg_imp.getProcessor.setMinAndMax(0, 255) # Create a LUT based on a predefined threshold red = zeros(256, 'b') green = zeros(256, 'b') blue = zeros(256, 'b') acceptance_threshold = HOMOGENEITY_ACCEPTANCE_THRESHOLD * 256 / 100 for i in range(256): red[i] = (i - acceptance_threshold) green[i] = (i) homogeneity_LUT = LUT(red, green, blue) hg_imp.setLut(homogeneity_LUT) return hg_imp, measuremnts
imp = IJ.openImage( "/Users/jrminter/Desktop/Pella_617_Au_on_C_100kX_15kV_cr.tif") imp.setTitle("Orig") imp.show() imp_proc = imp.duplicate() imp_proc.setTitle("Proc") IJ.run(imp_proc, "Median...", "radius=2") IJ.run(imp_proc, "Invert", "") IJ.run(imp_proc, "Enhance Contrast", "saturated=0.35") imp_proc.show() imp_bin = imp_proc.duplicate() imp_bin.setTitle("Bin") IJ.setAutoThreshold(imp_bin, "MinError") imp_bin.show() IJ.run("Make Binary") imp_seg = imp_bin.duplicate() imp_seg.setTitle("Seg") IJ.run("Set Measurements...", "area mean perimeter fit shape display add redirect=Orig decimal=3") IJ.run( imp_seg, "Analyze Particles...", "size=20-Infinity circularity=0.3-1.00 show=[Overlay Masks] display exclude clear add" ) # rm.runCommand(imp_seg,"Show None") rm.runCommand(imp, "Show All with labels") imp_seg.show() imp_ori.show()
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 updatepressed(event): self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() IJ.run("Threshold...") IJ.setAutoThreshold(self.__image, "MaxEntropy") rt=ResultsTable() pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00) pa.analyze(self.__image) self.__roisArray=[] self.__roisArray=rm.getRoisAsArray() #for i in range(rm.getCount()) : # rm.select(i) # rm.runCommand("Set Color", "0000FF", 2) IJ.resetThreshold(self.__image) rt.show("tempRT") areas=rt.getColumn(ResultsTable.AREA) means=rt.getColumn(ResultsTable.MEAN) majors=rt.getColumn(ResultsTable.MAJOR) minors=rt.getColumn(ResultsTable.MINOR) #print 0 if self.__slidersDict["Area_max"].getMaximum() < int(max(areas)+1): # print 1 self.__slidersDict["Area_max"].setMaximum(int(max(areas))+1) if self.__slidersDict["Area_min"].getMaximum() < int(max(areas)+1): # print 2 self.__slidersDict["Area_min"].setMaximum(int(max(areas))+1) if self.__slidersDict["Mean_max"].getMaximum() < int(max(means)+1): # print 3 self.__slidersDict["Mean_max"].setMaximum(int(max(means))+1) if self.__slidersDict["Mean_min"].getMaximum() < int(max(means)+1): # print 4 self.__slidersDict["Mean_min"].setMaximum(int(max(means))+1) if self.__slidersDict["Major_max"].getMaximum() < int(max(majors)): # print 5 self.__slidersDict["Major_max"].setMaximum(int(max(majors))+1) if self.__slidersDict["Major_min"].getMaximum() < int(max(majors)+1): # print 6 self.__slidersDict["Major_min"].setMaximum(int(max(majors))+1) if self.__slidersDict["Minor_max"].getMaximum() < int(max(minors)+1): # print 7 self.__slidersDict["Minor_max"].setMaximum(int(max(minors))+1) if self.__slidersDict["Minor_min"].getMaximum() < int(max(minors)+1): # print 8 self.__slidersDict["Minor_min"].setMaximum(int(max(minors))+1) if self.__slidersDict["AR_max"].getMaximum() < int((max(majors)+1)/min(minors)+1): # print 9 self.__slidersDict["AR_max"].setMaximum(int((max(majors)+1)/(min(minors)))) if self.__slidersDict["AR_min"].getMaximum() < int((max(majors)+1)/min(minors)): # print 10 self.__slidersDict["AR_min"].setMaximum(int((max(majors)+1)/(min(minors)))) #print 11 for sb in self.__slidersDict.values(): sb.repaint() #rm.runCommand("reset") #temprois=self.getIncludeRois() #IJ.run(self.__image, "Remove Overlay", "") #o=Overlay() #for roi in temprois: # o.addElement(roi) #self.__image.killRoi() #self.__image.setOverlay(o) self.__image.updateAndDraw()
# 2014-11-27 JRM 1.1.00 Get result from summary table from org.python.core import codecs codecs.setDefaultEncoding('utf-8') from ij import IJ, WindowManager from ij.measure import ResultsTable from ij.text import TextWindow bClose = True IJ.run("Blobs (25K)") imp = IJ.getImage() IJ.setAutoThreshold(imp, "Default") IJ.run(imp, "Convert to Mask", "") IJ.run(imp, "Set Measurements...", "area center redirect=None decimal=3") IJ.run(imp, "Analyze Particles...", "display exclude clear include summarize") tw = WindowManager.getFrame("Summary") if tw != None: st = tw.getTextPanel().getResultsTable() IJ.log("1st row of Summary:\n"+ st.getRowAsString(0)) v = st.getCounter() w = st.getLastColumn() s = st.size() z = st.getValueAsDouble(w, 0) af = float(z) af /= 100. print("Area Fraction: %.3f" % af)
IJ.run("Close All", "") # access to the folder and the files in it directory = File(folder) listOfFilesInFolder = directory.listFiles() for file in listOfFilesInFolder: if (file.toString().endswith(".tif")): # load image and show it imp = IJ.openImage(file.toString()) imp.show() copy = Duplicator().run(imp) # apply a threshold to detect objects (cells, nuclei,...) IJ.setAutoThreshold(imp, "Otsu") Prefs.blackBackground = False IJ.run(imp, "Convert to Mask", "") # analyse objects and put results in table IJ.run("Set Measurements...", "area display redirect=None decimal=5") IJ.run(imp, "Analyze Particles...", "exclude add") manager = RoiManager.getRoiManager() manager.runCommand("Save", file.toString() + ".RoiSet.zip") for roi in manager.getRoisAsArray(): copy.setRoi(roi) copy.show() IJ.run(copy, "Enlarge...", "enlarge=-2")
def main(imp): # We may want to set specific options depending on whether we are parsing a # 2D or a 3D image. If the image has multiple channels/time points, we set # the C,T position to be analyzed by activating them. The channel and frame # will be stored in the profile properties map and can be retrieved later): if imp.getNSlices() == 1: parser = ImageParser2D(imp, context) parser.setRadiiSpan(0, ImageParser2D.MEAN) # mean of 4 measurements at every radius parser.setPosition(1, 1, 1) # channel, frame, Z-slice else: parser = ImageParser3D(imp, context) parser.setSkipSingleVoxels(True) # ignore isolated voxels parser.setPosition(1, 1) # channel, frame # Segmentation: we can set the threshold manually using one of 2 ways: # 1. manually: parser.setThreshold(lower_t, upper_t) # 2. from the image itself: e.g., IJ.setAutoThreshold(imp, "Huang") # If the image is already binarized, we can skip setting threshold levels: if not (imp.isThreshold() or imp.getProcessor().isBinary()): from ij import IJ IJ.setAutoThreshold(imp, "Otsu dark") # Center: the x,y,z coordinates of center of analysis. In a real-case usage # these would be retrieved from ROIs or a centroid of a segmentation routine. # If no ROI exists coordinates can be set in spatially calibrated units # (floats) or pixel coordinates (integers): if imp.getRoi() is None: xc = int(round(imp.getWidth()/2)) yc = int(round(imp.getHeight()/2)) zc = int(round(imp.getNSlices()/2)) parser.setCenterPx(xc, yc, zc) # center of image else: parser.setCenterFromROI() # Sampling distances: start radius (sr), end radius (er), and step size (ss). # A step size of zero would mean 'continuos sampling'. Note that end radius # could also be set programmatically, e.g., from a ROI parser.setRadii(10, 5, parser.maxPossibleRadius()) # (sr, er, ss) # We could now set further options as we would do in the dialog prompt: parser.setHemiShells('none') # (...) # Parse the image. This may take a while depending on image size. 3D images # will be parsed using the number of threads specified in ImageJ's settings: parser.parse() if not parser.successful(): log.error(imp.getTitle() + " could not be parsed!!!") return # We can e.g., access the 'Sholl mask', a synthetic image in which foreground # pixels have been assigned the no. of intersections: parser.getMask().show() # Now we can access the Sholl profile: profile = parser.getProfile() if profile.isEmpty(): log.error("All intersection counts were zero! Invalid threshold range!?") return # We can now access all the measured data stored in 'profile': Let's display # the sampling shells and the detected sites of intersections (NB: If the # image already has an overlay, it will be cleared): profile.getROIs(imp) # For now, lets's perform a minor cleanup of the data and plot it without # doing any polynomial regression. Have a look at Sholl_Extensive_Stats_Demo # script for details on how to analyze profiles with detailed granularity profile.trimZeroCounts() profile.plot().show()
input_image_plus = IJ.openImage( input ) # Create a copy of the image. input_image_plus_copy = input_image_plus.duplicate() image_processor_copy = input_image_plus_copy.getProcessor() try: # Convert image to binary if necessary. if not image_processor_copy.isBinary(): # Convert the image to binary grayscale. IJ.run( input_image_plus_copy, "Make Binary","iterations=1 count=1 edm=Overwrite do=Nothing" ) # Set the options. if jython_utils.asbool( dark_background ): method_str = "%s dark" % method else: method_str = method IJ.setAutoThreshold( input_image_plus_copy, method_str ) if display == "red": display_mode = "Red" elif display == "bw": display_mode = "Black & White" elif display == "over_under": display_mode = "Over/Under" IJ.setThreshold( input_image_plus_copy, threshold_min, threshold_max, display_mode ) # Run the command. IJ.run( input_image_plus_copy, "threshold", "" ) # Save the ImagePlus object as a new image. IJ.saveAs( input_image_plus_copy, output_datatype, tmp_output_path ) except Exception, e: jython_utils.handle_error( error_log, str( e ) )