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
Пример #2
0
def ReturnColorThresholdedPicture(PICPATH, L_min, L_max, a_min, a_max, b_min,
                                  b_max):

    imp = IJ.openImage(PICPATH)
    imp.show()
    ImageTitle = imp.getTitle()

    LabThresold_List = [[L_min, L_max], [a_min, a_max], [b_min, b_max]]
    Filt_List = ["pass", "pass", "pass"]

    ColorThresholder.RGBtoLab()

    IJ.run(imp, "RGB Stack", "")
    IJ.run("Stack to Images", "")

    IJ.selectWindow("Red")
    IJ.run('Rename...', 'title=0')  #title=hoge =(equal)の間にスペースを入れてならない。
    imp0 = IJ.getImage()

    IJ.selectWindow("Green")
    IJ.run('Rename...', 'title=1')
    imp1 = IJ.getImage()

    IJ.selectWindow("Blue")
    IJ.run('Rename...', 'title=2')
    imp2 = IJ.getImage()

    for i in range(3):

        WindowTitle = str(i)
        MinValue = float(LabThresold_List[i][0])
        MaxValue = float(LabThresold_List[i][1])

        IJ.selectWindow(WindowTitle)
        IJ.setThreshold(MinValue, MaxValue)
        IJ.run(IJ.getImage(), "Convert to Mask", "")

        if Filt_List[i] == "stop":
            ImageProcessor.invert()

    #コメントアウトした、imgculcは動かなくなくなった,謎
    #imp3 = ImageCalculator.run(imp0, imp1, "and create")
    #imp4 = ImageCalculator.run(imp3,imp2, "and create")
    imp3 = ImageCalculator().run("and create", imp0, imp1)
    imp4 = ImageCalculator().run("and create", imp3, imp2)

    imp3.show()
    imp4.show()
    ResultTitle = imp4.getTitle()
    IJ.selectWindow(ResultTitle)
    imp4.setTitle(ImageTitle)

    #Saveした時点で画像の情報が失われる.
    imp.close()
    imp0.close()
    imp1.close()
    imp2.close()
    imp3.close()

    return imp4
Пример #3
0
def threshold(imPlus, edgeThreshold=2500):
    mask = Duplicator().run(imPlus)
    mask_stk = mask.getStack()

    # First, we threshold based on edges
    IJ.setThreshold(mask, edgeThreshold, 100000, "No Update")
    for i in range(mask.getImageStackSize()):
        mask_stk.getProcessor(i + 1).findEdges()
    IJ.run(mask, "Make Binary", "method=Default background=Default black")

    # Now, we need to clean up the binary images morphologically
    IJ.run(mask, "Dilate", "stack")
    IJ.run(mask, "Fill Holes", "stack")
    IJ.run(mask, "Erode", "stack")
    IJ.run(mask, "Erode", "stack")

    # Finally, remove the small particles
    stk = ImageStack(mask.getWidth(), mask.getHeight())
    p = PA(PA.SHOW_MASKS, 0, None, 200, 100000)
    p.setHideOutputImage(True)
    for i in range(mask_stk.getSize()):
        mask.setSliceWithoutUpdate(i + 1)
        p.analyze(mask)
        mmap = p.getOutputImage()
        stk.addSlice(mmap.getProcessor())

    mask.setStack(stk)
    mask.setSliceWithoutUpdate(1)
    mask.setTitle(mask_title(imPlus.getTitle()))
    mask.show()
    return mask
def threshold_and_binarise(imp):
	"""Return thresholded stack"""
	print("performing segmentation on channel: " + imp.getTitle());
	stats = StackStatistics(imp);
	IJ.run(imp, "Subtract...", "value={} stack".format(stats.min));
	IJ.run(imp, "Divide...", "value={} stack".format((stats.max - stats.min)/255.0));
	WaitForUserDialog("pre 8-bit").show();
	imp = robust_convertStackToGray8(imp);
	WaitForUserDialog("post 8-bit").show();

	# Apply automatic THRESHOLD to differentiate cells from background
	histo = StackStatistics(imp).histogram;
	thresh_lev = AutoThresholder().getThreshold(AutoThresholder.Method.Default, histo);
	print(thresh_lev);
	min_volume = int(float(imp.getHeight() * imp.getWidth() * imp.getNSlices())/100);
	IJ.run(imp, "3D Simple Segmentation", "low_threshold=" + str(thresh_lev + 1) + 
												" min_size=" + str(min_volume) + " max_size=-1");
	fit_basis_imp = WM.getImage("Seg");
	bin_imp = WM.getImage("Bin");
	bin_imp.changes=False;
	bin_imp.close();
	IJ.setThreshold(fit_basis_imp, 1, 65535);
	IJ.run(fit_basis_imp, "Convert to Mask", "method=Default background=Dark list");
	#IJ.run(fit_basis_imp, "Fill Holes", "stack");
#	IJ.run("3D Fill Holes", "");
	return fit_basis_imp;
def threshold(imp, threshold):
	""" Threshold image """
	impout = Duplicator().run(imp)
	IJ.setThreshold(impout, threshold, 1000000000)
	IJ.run(impout, "Convert to Mask", "stack")
	impout.setTitle("Threshold");
	return impout
def findclearcell(inDir, currentDir, fileName):
  print "Opening", fileName
  file_path= os.path.join(currentDir, fileName)
  options = ImporterOptions()
  options.setId(file_path)
  options.setSplitChannels(True)
  imps = BF.openImagePlus(options)
  for imp in imps:
  	imp.show()
  if not imps:
  	return
  IJ.selectWindow(fileName + " - C=2")
  IJ.run("Close")
  IJ.selectWindow(fileName + " - C=1")
  IJ.run("Close")
  IJ.selectWindow(fileName + " - C=0")
  IJ.run("Close")
  IJ.selectWindow(fileName + " - C=3")
  IJ.run("8-bit")
  IJ.run("Options...", "iterations=1 count=1 black edm=8-bit")
  IJ.setThreshold(62, 255)
  IJ.run("Convert to Mask", "method=Default backgorund=Dark black")
  Macro.setOptions("Stack position")
  for n in range(4,15):
	n+=1
	IJ.setSlice(n)
	IJ.run(imp, "Analyze Particles...", "size=7.2-9 circularity=0.7-0.95 display")
Пример #7
0
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
Пример #8
0
def getFlipArray(maskPAImgPlus):
    """Given the PA-aligned mask image, return a list of booleans, indicating whether or not we should flip the corresponding index"""
    maskPAImgPlus.show()
    #	IJ.run(maskPAImgPlus, "Shape Smoothing", "relative_proportion_fds=15 absolute_number_fds=2 keep=[Relative_proportion of FDs] stack");

    IJ.run("Set Measurements...", "shape")
    IJ.setThreshold(maskPAImgPlus, 1, 1000, "No Update")
    stk = maskPAImgPlus.getStack()

    tableLeft = ResultsTable()
    PA.setResultsTable(tableLeft)
    IJ.makeRectangle(0, 0,
                     maskPAImgPlus.getWidth() / 2 - 5,
                     maskPAImgPlus.getHeight())
    IJ.run(maskPAImgPlus, "Analyze Particles...", "stack")

    tableRight = ResultsTable()
    PA.setResultsTable(tableRight)
    IJ.makeRectangle(maskPAImgPlus.getWidth() / 2 - 5, 0,
                     maskPAImgPlus.getWidth() / 2 + 5,
                     maskPAImgPlus.getHeight())
    IJ.run(maskPAImgPlus, "Analyze Particles...", "stack")
    maskPAImgPlus.hide()

    IJ.resetThreshold(maskPAImgPlus)

    leftCirc = [tableLeft.getValue("Circ.", i) for i in range(stk.getSize())]
    rightCirc = [tableRight.getValue("Circ.", i) for i in range(stk.getSize())]
    return [leftCirc[i] < rightCirc[i] for i in range(len(leftCirc))]
Пример #9
0
def preprocess(filePath, fileName, fileID):
    global radius
    global circularity
    global size
    global lowerThreshold
    global upperThreshold
    global bytesInMB

    curr = IJ.openImage(filePath + '/' + fileName)
    c1, c2, c3 = ChannelSplitter.split(curr) # type:
    c1.show()
    c2.show()
    IJ.log("before blur: " +  str(IJ.currentMemory()/bytesInMB) + " MB")
    IJ.run(c1,"Gaussian Blur...","sigma=%i" %radius)
    IJ.log("after blur: " +  str(IJ.currentMemory()/bytesInMB) + " MB" + "\n")
    IJ.setThreshold(c1, lowerThreshold, upperThreshold)
 
    #IJ.run("Set Measurements...", "mean center redirect=C2-GT_%s-Stitch.tif decimal=1" %fileID)
    #IJ.run("Set Measurements...", "mean center redirect=C2-GT_A4-Stitch.tif decimal=1")
    IJ.run("Set Measurements...", "mean center redirect=C2-GT_%s-Stitch.tif decimal=1" %fileID) # there is a space after "redirect ="
    # produces 1980 cells but totally wrong measurements, record them next time when continued manually
    IJ.run(c1, "Analyze Particles...", "size=50.00-Infinity circularity=0.70-1.00 show=Nothing display exclude include")
    # I suspect that IJ.run(c1, "Analyze Particles...", "size=%s-Infinity circularity=%s-1.00 show=Nothing display exclude include" %(size, circularity)) works
    c1.changes = False
    c1.close()
    c2.close()
    return c3
Пример #10
0
def analyzeImage(passImage, passModel, passChannel, passProbability,
                 passPixels, passOutput):
    retResults = list()
    windows = set()

    # Register current window
    registerWindow(passImage.title, windows)

    # Extract the requested channel
    IJ.run("Z Project...", "projection=[Max Intensity]")
    registerWindow("MAX_" + passImage.title, windows)
    IJ.run("Duplicate...", "title=temp")
    registerWindow("temp", windows)

    # Apply WEKA training model to image
    wekaSeg = WekaSegmentation(WindowManager.getCurrentImage())
    wekaSeg.loadClassifier(passModel)
    wekaSeg.applyClassifier(True)

    # Extract first slice of probability map
    wekaImg = wekaSeg.getClassifiedImage()
    wekaImg.show()
    registerWindow("Probability maps", windows)
    IJ.setSlice(1)
    IJ.run("Duplicate...", "title=temp2")
    registerWindow("temp2", windows)

    # Apply threshold and save
    IJ.setThreshold(passProbability, 1, "Black & White")
    fileParts = passImage.getTitle().split(".")
    IJ.save(
        os.path.join(
            passOutput, "{0}-probmap.png".format(fileParts[0],
                                                 '.'.join(fileParts[1:]))))

    # Perform particle analysis and save
    IJ.run("Analyze Particles...",
           "size={0}-Infinity show=Outlines pixel clear".format(passPixels))
    registerWindow("Drawing of temp2", windows)
    IJ.save(
        os.path.join(
            passOutput, "{0}-particles.png".format(fileParts[0],
                                                   '.'.join(fileParts[1:]))))

    # Get measurements
    tableResults = ResultsTable.getResultsTable()
    for rowIdx in range(tableResults.size()):
        retResults.append(tableResults.getRowAsString(rowIdx).split())
        retResults[-1].insert(
            0,
            WindowManager.getCurrentImage().getCalibration().unit)
        retResults[-1].append(
            float(retResults[-1][4]) / float(retResults[-1][3]))

    # Close windows
    closeWindows(windows)

    return retResults
Пример #11
0
def auto_resize_angle_measure(img, two_sarcomere_size):
    """Resizes and measures angle of offset for img based on T-tubules."""
    # Run Fast Fourier Transform on Image to get Power Spectral Density
    IJ.run(img, "FFT", "")

    # Select PSD image.
    fft_title = "FFT of " + img.getTitle()
    fft_img = WindowManager.getImage(fft_title)

    # Threshold the image and create binary mask.
    IJ.setThreshold(151, 255)
    #IJ.setThreshold(135, 255)
    IJ.run(fft_img, "Convert to Mask", "")

    # Set measurements for fitting an ellipse and fit them to data.
    IJ.run(fft_img, "Set Measurements...",
           "area centroid fit redirect=None decimal=2")
    if dev_options:
        args = "size=10-Infinity show=Ellipses display"
    else:
        args = "size=10-Inifinity"
    IJ.run(fft_img, "Analyze Particles...", args)
    results = ResultsTable.getResultsTable()
    angle_column = results.getColumnIndex("Angle")
    area_column = results.getColumnIndex("Area")
    centroid_x_column = results.getColumnIndex("X")
    centroid_y_column = results.getColumnIndex("Y")
    # Sort by area since we need the largest two ellipses.
    results.sort("Area")
    # Grab info for the largest two ellipses.
    areas = results.getColumnAsDoubles(area_column)
    angles = results.getColumnAsDoubles(angle_column)
    c_xs = results.getColumnAsDoubles(centroid_x_column)
    c_ys = results.getColumnAsDoubles(centroid_y_column)

    # Calculate offset angle from main ellipse.
    rotation_angle = angles[-1] - 90.

    # Measure distance between centroids of two largest ellipses using distance measurement tool to get spatial frequency of T-tubules.
    # Note: This needs to be in pixels since the filter size is in pixels.
    c_x_0 = c_xs[-1]
    c_y_0 = c_ys[-1]
    c_x_1 = c_xs[-2]
    c_y_1 = c_ys[-2]
    dist_gap = ((c_x_0 - c_x_1)**2 + (c_y_0 - c_y_1)**2)**0.5
    old_two_sarcomere_size = 2 * fft_img.getDimensions()[0] / dist_gap

    # Resize based on measured two sarcomere size
    resize_ratio = float(two_sarcomere_size) / float(old_two_sarcomere_size)
    old_width = img.width
    old_height = img.height
    new_width = resize_ratio * old_width
    new_height = resize_ratio * old_height
    resize_args = "width={} height={} depth=1 constrain average interpolation=Bicubic".format(
        new_width, new_height)
    IJ.run(img, "Size...", resize_args)

    return rotation_angle
Пример #12
0
def threshold_brightfield(imp, threshold_percent):
    # this code is based on my "Threshold brightfield [Q]" macro. Need to automate 
    # finding threshold values instead of hardcoding themm here.
    IJ.run("Find Edges")
    lower_threshold = get_percentile(imp, threshold_percent)
    IJ.setThreshold(lower_threshold, 65535)
    IJ.run("Convert to Mask")
    IJ.run("Fill Holes")
    IJ.run("Watershed")
Пример #13
0
def threshold(_img, threshold):
  imp = Duplicator().run(_img)
  #imp.show(); time.sleep(0.2)
  #IJ.setThreshold(imp, mpar['lthr'], mpar['uthr'])
  IJ.setThreshold(imp, threshold, 1000000000)
  IJ.run(imp, "Convert to Mask", "stack")
  imp.setTitle("Threshold");
  #IJ.run(imp, "Divide...", "value=255 stack");
  #IJ.setMinAndMax(imp, 0, 1);
  return imp
def threshold(_img, threshold):
  imp = Duplicator().run(_img)
  #imp.show(); time.sleep(0.2)
  #IJ.setThreshold(imp, mpar['lthr'], mpar['uthr'])
  IJ.setThreshold(imp, threshold, 1000000000)
  IJ.run(imp, "Convert to Mask", "stack")
  imp.setTitle("Threshold");
  #IJ.run(imp, "Divide...", "value=255 stack");
  #IJ.setMinAndMax(imp, 0, 1);
  return imp
def Threshold(_img, mpar={"threshold": 15}, _gui=False):
    print "Threshold"
    imp = Duplicator().run(_img)
    # imp.show(); time.sleep(0.2)
    # IJ.setThreshold(imp, mpar['lthr'], mpar['uthr'])
    IJ.setThreshold(imp, mpar["threshold"], 1000000000)
    IJ.run(imp, "Convert to Mask", "stack")
    imp.setTitle("Threshold")
    # IJ.run(imp, "Divide...", "value=255 stack");
    # IJ.setMinAndMax(imp, 0, 1);
    return imp, _img.duplicate()
Пример #16
0
def Generate_segmented_fixedThreshold(imp, channel, thres_min):
    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.setThreshold(imp_Threshold_1, thres_min, 100000)
    #Prefs.blackBackground = True;
    IJ.run(imp_Threshold_1, "Convert to Mask", "")
    return imp_Threshold_1
Пример #17
0
def walkAnalysis(fileList, directory, outpath):
    from ij import IJ, ImagePlus
    from ij.macro import Interpreter as IJ1
    from datetime import datetime
    IJ1.batchMode = True
    current = 0
    pnum = 0
    nooresults = ''
    for files in os.walk(directory, topdown=True):
        for file in fileList:
            drc = ''.join(directory + file)
            cfile = file
            imp = IJ.open(drc)
            IJ.run("16-bit")
            IJ.setThreshold(65409, 65532)
            IJ.run("Subtract Background...", "rolling=" + Roll + " dark")
            ##*LIGHT CONDITIONS MUST BE CONSTANT!!* possibly omit light call in order to bugfix
            IJ.run(imp, "Gaussian Blur...", "sigma=" + SigM)
            IJ.run("Make Binary")
            ##increases contrast and allows watershed
            IJ.run("Watershed")
            dt = str(datetime.now())[:11]
            savestring = out + "mask" + dt + cfile
            IJ.saveAs(imp, "Jpeg", out + "mask" + cfile)
            ##jpeg saveas dramatically decreases process time
            IJ.run("Set Measurements...",
                   "integrated area_fraction redirect=None decimal=" + Dec)
            IJ.run(
                imp, "Analyze Particles...",
                "size=10-Infinity circularity=0.05-1.00 show=[Outlines] display clear include summarize in_situ"
            )
            ##most likely the value will change according to desired cell line
            current += 1  ##current is a counter for images processed, as well as possible naming convention for renaming images.
    numstr = str(current)
    #current is a int class and cannot be concat with a string.
    dt = str(
        datetime.now()
    )[:
      10]  ## this slice truncates the colon that is unacceptable in file naming convention. find an alternative solution if possible.
    results = (out + "Results" + dt + ".csv")
    if os.path.exists(results):
        while os.path.exists(results):
            pnum += 1
            results = (out + "Results" + dt + '-' + str(pnum) + ".csv")
        IJ.saveAs("Results", results)
    else:
        IJ.saveAs("Results", results)
    csvStr = (out + "Results" + dt + ".csv")
    IJ1.batchMode = False
    return numstr, csvStr
Пример #18
0
def Generate_segmented_manual(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.run("Threshold...")
    # this is the method to wait the user set up the threshold
    WaitForUserDialog("Threshold", "set a threshold").show()
    thres_min = imp_Threshold_1.getProcessor().getMinThreshold()
    thres_max = imp_Threshold_1.getProcessor().getMaxThreshold()
    IJ.setThreshold(imp_Threshold_1, thres_min, thres_max)
    #Prefs.blackBackground = True;
    IJ.run(imp_Threshold_1, "Convert to Mask", "")
    return imp_Threshold_1
Пример #19
0
def show_thresholded(event):
    """ Show virtual stack of image thresholded to mu +/- 1x sigma of each Gaussian component

    Parameters
    ----------
    event : Event
        Waits for show_thresholded_JB JButton to be pressed

    Returns
    -------
    None
    """

    # Get image filename
    results_dir = get_results_dir()
    with open(os.path.join(results_dir, "Users_Params.csv")) as csv_file:
        reader = csv.DictReader(csv_file)
        for row in reader:
            img_fname = row['img_fname']
            n_gaussians = int(row['n_gaussians'])
    print("Displaying image {} with {} Gaussians fitted".format(
        img_fname, n_gaussians))

    # Read mu and sigma from results directory
    with open(os.path.join(results_dir, "fitted_results.csv")) as csv_file:
        reader = csv.reader(csv_file)
        results = []  # list containing lines in fitted_results.csv
        for row in reader:
            results.append(row)
    mu_all = []
    sigma_all = []
    for i in range(3, len(results)):
        mu_all.append(float(results[i][0]))
        sigma_all.append(float(results[i][1]))

    # Calculate values for thresholding (mu +/- 1x sigma)
    lower_threshold = map(lambda mu, sigma: mu - sigma, mu_all, sigma_all)
    upper_threshold = map(lambda mu, sigma: mu + sigma, mu_all, sigma_all)

    # Display each slice thresholded with the Gaussian number in title
    for gaussian in range(n_gaussians):
        imp = IJ.openVirtual(img_fname)
        imp.setTitle("Gaussian {}".format(gaussian))
        imp.show()
        IJ.setThreshold(imp, lower_threshold[gaussian],
                        upper_threshold[gaussian])
        print("Gaussian {} threshold values [{} - {}]".format(
            gaussian, lower_threshold[gaussian], upper_threshold[gaussian]))
Пример #20
0
def process(inputpath, outputpath):

    imp = IJ.openImage(inputpath)
    IJ.run(
        imp, "Properties...",
        "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
    )

    IJ.setThreshold(imp, t1, 255)
    #imp.show()
    #WaitForUserDialog("Title", "Look at image").show()
    IJ.run(imp, "Convert to Mask", "")
    IJ.run(imp, "Watershed", "")

    # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager

    table = ResultsTable()
    roim = RoiManager(True)
    ParticleAnalyzer.setRoiManager(roim)
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA,
                          table, 50, 9999999999999999, 0.2, 1.0)
    pa.setHideOutputImage(True)
    pa.analyze(imp)

    imp.changes = False
    imp.close()

    areas = table.getColumn(0)

    summary = {}

    if areas:

        summary['Image'] = filename
        summary['Nuclei.count'] = len(areas)
        summary['Area.Covered'] = sum(areas)

    fieldnames = list(summary.keys())

    with open(outputpath, 'a') as csvfile:

        writer = csv.DictWriter(csvfile,
                                fieldnames=fieldnames,
                                extrasaction='ignore',
                                lineterminator='\n')
        if os.path.getsize(outputDirectory + "/" + outputname + ".csv") < 1:
            writer.writeheader()
        writer.writerow(summary)
Пример #21
0
 def do_ellipse_testing(self, imw, imh, centre, angle, axl):
     """Utility function to provide test ellipse data"""
     imp = IJ.createImage("test", imw, imh, 1, 8)
     imp.show()
     roi = ellipse_fitting.generate_ellipse_roi(centre, angle, axl)
     imp.setRoi(roi)
     IJ.run(imp, "Set...", "value=128")
     IJ.setThreshold(imp, 1, 255)
     IJ.run(imp, "Convert to Mask", "method=Default background=Dark list")
     IJ.run(imp, "Outline", "stack")
     IJ.run(imp, "Create Selection", "")
     roi = imp.getRoi()
     pts = [(pt.x, pt.y) for pt in roi.getContainedPoints()]
     imp.changes = False
     imp.close()
     return pts
Пример #22
0
def analyzeImage(passImage, passModel, passProbability, passPixels,
                 passOutput):
    retResults = list()

    # Apply WEKA training model to image
    wekaSeg = WekaSegmentation(passImage)
    wekaSeg.loadClassifier(passModel)
    wekaSeg.applyClassifier(True)

    # Extract first slice of probability map
    wekaImg = wekaSeg.getClassifiedImage()
    wekaImg.show()

    IJ.selectWindow("Probability maps")
    IJ.setSlice(1)
    IJ.run("Duplicate...", "title=temp")

    # Apply threshold and save
    IJ.setThreshold(passProbability, 1, "Black & White")
    fileParts = passImage.getTitle().split(".")
    IJ.save(
        os.path.join(
            passOutput, "{0}-probmap.png".format(fileParts[0],
                                                 '.'.join(fileParts[1:]))))

    # Perform particle analysis and save
    IJ.run("Analyze Particles...",
           "size={0}-Infinity show=Outlines pixel clear".format(passPixels))
    IJ.selectWindow("Drawing of temp")
    IJ.save(
        os.path.join(
            passOutput, "{0}-particles.png".format(fileParts[0],
                                                   '.'.join(fileParts[1:]))))

    # Get measurements (skip final row, this will correspond to legend)
    tableResults = ResultsTable.getResultsTable()
    for rowIdx in range(tableResults.size() - 1):
        retResults.append(tableResults.getRowAsString(rowIdx).split())

    # Close interim windows
    IJ.run("Close")
    IJ.selectWindow("temp")
    IJ.run("Close")
    IJ.selectWindow("Probability maps")
    IJ.run("Close")

    return retResults
Пример #23
0
def analyzeTUB():

    rm = RoiManager().getInstance()

    #Set imageJ preference meassurements to "area"
    IJ.run("Set Measurements...", "area display redirect=None decimal=3")

    #Variable used for iteration
    counter = 0

    #Clear previous resuslts
    IJ.run("Clear Results")

    # Make library, to be iterated through. Room for improvement
    lis_dic = [{'path': sub[i]} for i in range(len(sub))]
    if not lis_dic:
        sys.exit('Did you check the right box?')

    # Calculate area of channel #1 (Calculation requires that area is chosen as measured value)
    for i in lis_dic:
        print i
        for p in data[counter][::-1]:
            print p
            if '_' + channel1 + '_' in p:
                imp1 = IJ.openImage(i['path'] + '/' + p)
                IJ.setThreshold(imp1, lowth1, 255)
                IJ.run(imp1, "Create Selection", "")
                roi = rm.getRoi(imp1)
                #rm.runCommand(imp1, 'Add')
                IJ.run(imp1, "Measure", "")

            if '_' + channel2 + '_' in p:
                imp2 = IJ.openImage(i['path'] + '/' + p)
                IJ.setThreshold(imp2, lowth2, 255)
                rm.runCommand(imp1, 'Select')
                IJ.run(imp2, "Analyze Particles...", "size=0-4000 summarize")

        counter += 1

    # Reset counter
    counter = 0

    IJ.renameResults(channel2)
Пример #24
0
def analyzeDAPI():

    #Set imageJ preference meassurements to "area"
    IJ.run("Set Measurements...", "area display redirect=None decimal=3")

    #Variable used for iteration
    counter = 0

    #Clear previous resuslts
    IJ.run("Clear Results")

    # Make library, to be iterated through. Room for improvement
    lis_dic = [{'path': sub[i]} for i in range(len(sub))]
    if not lis_dic:
        sys.exit('Did you check the right box?')

    # Calculate number of particles in channel #1 (Calculation requires that DAPI is chosen as measured value)
    for i in lis_dic:
        for p in data[counter]:
            if '_' + channel1 + '_' in p:
                imp1 = IJ.openImage(i['path'] + '/' + p)
                IJ.setThreshold(imp1, lowth1, 255)
                IJ.run(imp1, "Convert to Mask", "")
                IJ.run(imp1, "Watershed", "")
                IJ.run(imp1, "Analyze Particles...",
                       "size=200-3000 pixel summarize")

        counter += 1
    IJ.renameResults(channel1)

    # Reset counter
    counter = 0

    # Calculate area of channel #2
    for i in lis_dic:
        for p in data[counter]:
            if '_' + channel2 + '_' in p:
                imp2 = IJ.openImage(i['path'] + '/' + p)
                IJ.setThreshold(imp2, lowth2, 255)
                IJ.run(imp2, "Create Selection", "")
                IJ.run(imp2, "Measure", "")
        counter += 1
    IJ.renameResults(channel2)
Пример #25
0
def edit_in_imj(folder_f, file_dir_f, new_folder_name_f):

    list_of_files = sorted(os.listdir(file_dir_f + "\\" + folder_f))

    imp = IJ.run(
        "Image Sequence...", "open=[" + file_dir_f + "\\" + folder_f + "\\" +
        list_of_files[0] + "] sort")

    IJ.run(imp, "Gaussian Blur 3D...", "x=1 y=1 z=1")

    # IJ.setAutoThreshold(imp, "Default dark")
    IJ.setThreshold(thresholds[0], thresholds[1])
    IJ.run(imp, "Convert to Mask", "method=Default background=Dark black")
    # IJ.run("Close")
    IJ.run(
        imp, "Image Sequence... ", "format=TIFF name=" + newFolderName +
        " save=" + fileDir + "_Processed\\")

    IJ.run("Close")
Пример #26
0
    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 threshold_and_binarise(imp,
                           z_xy_ratio,
                           approx_median=True,
                           prune_slicewise=True):
    """Return thresholded stack"""
    print("performing segmentation on channel: " + imp.getTitle())
    if approx_median:
        imp = utils.cross_planes_approx_median_filter(imp)
        imp = utils.robust_convertStackToGrayXbit(imp, x=8, normalise=True)
    else:
        filter_radius = 3.0
        IJ.run(
            imp, "Median 3D...", "x=" + str(filter_radius) + " y=" +
            str(math.ceil(filter_radius / z_xy_ratio)) + " z=" +
            str(filter_radius))
        IJ.run(imp, "8-bit", "")
    imp.show()

    # Apply automatic THRESHOLD to differentiate cells from background
    # get threshold value from stack histogram using otsu
    histo = StackStatistics(imp).histogram
    thresh_lev = AutoThresholder().getThreshold(
        AutoThresholder.Method.IJ_IsoData, histo)
    #thresh_lev = AutoThresholder().getThreshold(AutoThresholder.Method.Otsu, histo);
    max_voxel_volume = int(
        float(imp.getHeight() * imp.getWidth() * imp.getNSlices()) / 100)
    IJ.run(
        imp, "3D Simple Segmentation", "low_threshold=" + str(thresh_lev + 1) +
        " min_size=" + str(max_voxel_volume) + " max_size=-1")
    fit_basis_imp = WM.getImage("Seg")
    bin_imp = WM.getImage("Bin")
    bin_imp.changes = False
    bin_imp.close()
    IJ.setThreshold(fit_basis_imp, 1, 65535)
    IJ.run(fit_basis_imp, "Convert to Mask",
           "method=Default background=Dark list")
    #IJ.run(fit_basis_imp, "Fill Holes", "stack");
    IJ.run("3D Fill Holes", "")
    if prune_slicewise:
        fit_basis_imp = utils.keep_largest_blob(fit_basis_imp)
        # note this will be unstable if "branches" of approx equal x-section exist
    return fit_basis_imp
Пример #28
0
	def __falign(self) :
		
		#self.__impRes=IJ.getImage()
		stack = self.__impRes.getStack() # get the stack within the ImagePlus
		n_slices = stack.getSize() # get the number of slices
		ic = ImageCalculator()
		w = self.__impRes.getWidth()
		h = self.__impRes.getHeight()
		self.__sens[:] = []
		self.__listrois[:] = []

		
		
		for index in range(1, n_slices+1):	
			
			self.__impRes.setSlice(index)
			ip1 = stack.getProcessor(index)
			imp1 = ImagePlus("imp1-"+str(index), ip1)
			imp1sqr = ic.run("Multiply create 32-bit", imp1, imp1)			

			IJ.setThreshold(imp1sqr, 1, 4294836225)
			IJ.run(imp1sqr, "Create Selection", "")
			roi = imp1sqr.getRoi()
			rect=roi.getBounds()
			roi = Roi(rect)
			self.__listrois.append(roi)
			ipsqr = imp1sqr.getProcessor()
			is1 = ipsqr.getStatistics()
			self.__impRes.killRoi()

			
			
			if is1.xCenterOfMass > w/2.00 : 
				self.__impRes.setRoi(roi)
				ip1 = self.__impRes.getProcessor()
				ip1.flipHorizontal()
				self.__impRes.killRoi()
				self.__sens.append(-1)
			else : self.__sens.append(1)
				
			self.__impRes.updateAndDraw()
Пример #29
0
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
Пример #30
0
def process(srcDir, currentDir, fileName):
  image = IJ.openImage(os.path.join(currentDir, fileName))
  IJ.run("Clear Results")
  #set lowerbound threshold here
  IJ.setThreshold(image, 200, 10000)

  # Change (1,25) below to (1,n+1) where n is the number of frames
  for slice in range(1,(image.getNSlices()+1),1):
  	image.setSlice(slice)
  	IJ.run(image, "Select All", "")
  	IJ.run(image, "Measure", "")
  
  rt = ResultsTable.getResultsTable()
  # this line calculates the baseline
  baseline = (rt.getValue("IntDen",1) + rt.getValue("IntDen",2) + rt.getValue("IntDen",3))/3.0
  for result in range(0,rt.getCounter()):
  	cur_intensity = rt.getValue("IntDen",result)
  	ratio = cur_intensity/baseline
  	rt.setValue("RawIntDen",result,ratio)

  rt.updateResults()
  image.close()
def analyse(imp, root, filename, thresholds):
  closeAllImageWindows() 
  imp.show()
  print ""
  print(imp.getTitle())
  print "**********************************"

  IJ.run("Set Measurements...", "integrated redirect=None decimal=2");
  # get image calibration info
  IJ.run(imp, "Properties...", "unit=pixel pixel_width=1 pixel_height=1");
  
  # convert to 8-bit
  IJ.setMinAndMax(imp, 0, 65535);
  IJ.run(imp, "8-bit", "");
  thresholds = [(x / 65535 * 255) for x in thresholds]

  # Nuclei
  #closeAllNoneImageWindows()
  iChannel = 1
  imp.setSlice(iChannel)
  IJ.run(imp, "Gaussian Blur...", "sigma=2 slice");
  IJ.setThreshold(imp, thresholds[iChannel-1], 1000000000)
  IJ.run(imp, "Convert to Mask", "method=Default background=Dark only black");
  IJ.run(imp, "Measure", "");
  rt = ResultsTable.getResultsTable()
  values = rt.getColumnAsDoubles(rt.getColumnIndex("RawIntDen"))
  print("Area Nuclei (pixel^2) =",values[-1]/255)
  
  
  # Dots
  #closeAllNoneImageWindows()
  iChannel = 3
  imp.setSlice(iChannel)
  IJ.run(imp, "Gaussian Blur...", "sigma=1 slice");
  IJ.run(imp, "Find Maxima...", "noise="+str(thresholds[iChannel-1])+" output=Count");
  rt = ResultsTable.getResultsTable()
  values = rt.getColumnAsDoubles(rt.getColumnIndex("Count"))
  print("Number of Dots =",values[-1])
Пример #32
0
    hist_x_max = stats.histMax
    hist_x_range = hist_x_max - hist_x_min

    hist_x_values = []

    for bin in range(0, stats.nBins):

        print("Fraction pixels with intensity in bins 0 to {}".format(bin))
        integral = sum(hist[0:bin]) / sum(hist)
        print(integral)

        intensity = hist_x_range * bin / stats.nBins
        hist_x_values.append(intensity)

        print(intensity)

        if integral > percentile:
            threshold_intensity = intensity
            break
        else:
            pass

    return threshold_intensity


# example run
threshold_value = get_percentile(0.80)
print(threshold_value)

IJ.setThreshold(threshold_value, 65535)
IJ.run("Convert to Mask")
impSub = ImagePlus("Sub", ipSub)
impSub.show()
IJ.selectWindow("Result")
IJ.run("Close")
IJ.selectWindow("Sub")
imp=WM.getCurrentImage()
imp.setTitle(strName+"-acf")
imp.show()

centX = ip.width/2
centY = ip.height/2
top = centX-halfWidth
left = centY-halfWidth
IJ.makeRectangle(top,left,2*halfWidth,2*halfWidth)
IJ.run("Crop")
IJ.setThreshold(0.65, 1.00)
Analyzer.setOption("BlackBackground", False)
if bMakeBinary:
  IJ.run("Make Binary")
  IJ.run("Convert to Mask")
  IJ.run("Set Measurements...", "area centroid redirect=None decimal=3")
  IJ.run("Analyze Particles...", "display exclude clear include")
  rt = ResultsTable.getResultsTable()
  nMeas = rt.getCounter()
  print(nMeas)
  cntX  = rt.getColumn(ResultsTable.X_CENTROID)
  cntY  = rt.getColumn(ResultsTable.Y_CENTROID)
  cntA  = rt.getColumn(ResultsTable.AREA)
  # find the center - will be closest to half width
  fHw = float(halfWidth)
  minDelta = 1000000.
Пример #34
0
			for i, channel in enumerate(channels):
			
				
				summary[color[i] + "-intensity"] = "NA"
				summary[color[i] + "-ROI-count"] = "NA"
				
					#gets the mean grey intensity of the channel
				
				summary[color[i] + "-intensity"] = channel.getStatistics(Measurements.MEAN).mean

				channel.show()

					#Sets the thresholds from the dialog box 
				
				IJ.setThreshold(channel, thresholds[color[i]], 255)

				if thresholdMode:
					channel.show()
					IJ.run("Threshold...")
					WaitForUserDialog("Title", "Adjust threshold for " + color[i]).show()



					#Get the threshold you've used

				summary[color[i] + "-threshold-used"] = ImageProcessor.getMinThreshold(channel.getProcessor())

					#Threshold and watershed

				IJ.run(channel, "Convert to Mask", "")
Пример #35
0

#genero duplicados de x1 para efectuar umbralización en cada uno
list_x2 = [] #guarda las imagenes umbralizadas
list_x3 = []#guarda las mascaras
list_x4 = []#guarda los esqueletos
ic = ImageCalculator() #para hacer llamadas más cortas de la clase

#UMBRALIZACION
for i in range(stepNumber):#hacer tantas veces como diga stepNumber
	x2= x1.duplicate() 
	x2.setTitle('x2_'+repr(i))
	#x2.show()
	#efectúo la umbralización con OTSU
	#IJ.run("Threshold...")#si se quiere correr las opciones Fiji
	IJ.setThreshold(x2, (lowerThreshold +stepThreshold*i) , upperThreshold, "Black & White")
	IJ.run(x2, "Convert to Mask", "method=Otsu background=Dark black" )
	#se guarda resultado umbralización en list_x2
	list_x2.append( x2 )
	#
	#

#3D OBJECTS COUNTER
for i in range(stepNumber):
	x2  = list_x2[i] 	
	x2_aux = x2.duplicate()
	x2_aux.setTitle('x2_aux')
	#run("3D OC Options", "volume surface nb_of_obj._voxels nb_of_surf._voxels integrated_density mean_gray_value std_dev_gray_value median_gray_value minimum_gray_value maximum_gray_value centroid mean_distance_to_surface std_dev_distance_to_surface median_distance_to_surface centre_of_mass bounding_box show_masked_image_(redirection_requiered) dots_size=5 font_size=10 store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=x1")
	arguments = "volume centroid bounding_box show_masked_image_(redirection_requiered) dots_size=5 font_size=10 store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=x2_aux"
	IJ.run("3D OC Options", arguments)
	IJ.run(x2, "3D Objects Counter", "threshold=0 slice=0 min.=" + repr(p3DOCmin)+" max.=" + repr(p3DOCmax)+ " exclude_objects_on_edges objects statistics")
Пример #36
0
def batch_open_images(pathRoi,
                      pathMask,
                      file_typeImage=None,
                      name_filterImage=None,
                      recursive=False):
    '''Open all files in the given folder.
    :param path: The path from were to open the images. String and java.io.File are allowed.
    :param file_type: Only accept files with the given extension (default: None).
    :param name_filter: Reject files that contain the given string (default: wild characters).
    :param recursive: Process directories recursively (default: False).
    '''
    # Converting a File object to a string.
    if isinstance(pathMask, File):
        pathMask = pathMask.getAbsolutePath()

    def check_type(string):
        '''This function is used to check the file type.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the check on.
        '''
        if file_typeImage:
            # The first branch is used if file_type is a list or a tuple.
            if isinstance(file_typeImage, (list, tuple)):
                for file_type_ in file_typeImage:
                    if string.endswith(file_type_):
                        # Exit the function with True.
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if file_type is a string.
            elif isinstance(file_typeImage, string):
                if string.endswith(file_typeImage):
                    return True
                else:
                    return False
            return False
        # Accept all files if file_type is None.
        else:
            return True

    def check_filter(string):
        '''This function is used to check for a given filter.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the filtering on.
        '''
        if name_filterImage:
            # The first branch is used if name_filter is a list or a tuple.
            if isinstance(name_filterImage, (list, tuple)):
                for name_filter_ in name_filterImage:
                    if name_filter_ in string:
                        # Exit the function with True.

                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if name_filter is a string.
            elif isinstance(name_filterImage, string):
                if name_filterImage in string:
                    return True
                else:
                    return False
            return False
        else:
            # Accept all files if name_filter is None.
            return True

    # We collect all files to open in a list.
    path_to_Image = []
    # Replacing some abbreviations (e.g. $HOME on Linux).
    path = os.path.expanduser(pathMask)
    path = os.path.expandvars(pathMask)
    # If we don't want a recursive search, we can use os.listdir().
    if not recursive:
        for file_name in os.listdir(pathMask):
            full_path = os.path.join(pathMask, file_name)
            if os.path.isfile(full_path):
                if check_type(file_name):
                    if check_filter(file_name):
                        path_to_Image.append(full_path)
    # For a recursive search os.walk() is used.
    else:
        # os.walk() is iterable.
        # Each iteration of the for loop processes a different directory.
        # the first return value represents the current directory.
        # The second return value is a list of included directories.
        # The third return value is a list of included files.
        for directory, dir_names, file_names in os.walk(pathMask):
            # We are only interested in files.
            for file_name in file_names:
                # The list contains only the file names.
                # The full path needs to be reconstructed.
                full_path = os.path.join(directory, file_name)
                # Both checks are performed to filter the files.
                if check_type(file_name):
                    if check_filter(file_name) is False:
                        # Add the file to the list of images to open.
                        path_to_Image.append([
                            full_path,
                            os.path.basename(os.path.splitext(full_path)[0])
                        ])
    # Create the list that will be returned by this function.
    Masks = []
    rois = []
    ImageRois = []
    for img_path, file_name in path_to_Image:
        # IJ.openImage() returns an ImagePlus object or None.
        if check_filter(file_name):
            continue
        else:
            MaskName = str(pathMask) + '/' + file_name + '.tif'
            Mask = IJ.openImage(MaskName)

            Mask.show()
            rm = RoiManager.getInstance()
            if (rm == None):
                rm = RoiManager()
            rm.runCommand("Delete")
            IJ.selectWindow(file_name + '.tif')
            IJ.run("Find Edges")
            IJ.setAutoThreshold(Mask, "Default dark")
            IJ.run("Threshold")
            IJ.setThreshold(0, 0)

            IJ.run("Convert to Mask")
            IJ.run("Invert")
            IJ.run("Create Selection")
            rm.runCommand("Add")

            # An object equals True and None equals False.

            rois = rm.getRoisAsArray()
            rm.runCommand("Save",
                          str(pathRoi) + "/" + file_name + '.roi')
            Mask.changes = False
            Mask.close()

            ImageRois.append(rois)
    return ImageRois
Пример #37
0
	def ImThresh(self, event): #play wiht the threshold for every image
		IJ.setThreshold(float(self.ThreshField.getText()), 255)
		IJ.setOption("BlackBackground", false)
Пример #38
0
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 ) )
Пример #39
0
def process(subFolder, outputDirectory, filename):

    imp = IJ.openImage(inputDirectory + subFolder + '/' +
                       rreplace(filename, "_ch00.tif", ".tif"))
    IJ.run(
        imp, "Properties...",
        "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
    )
    ic = ImageConverter(imp)
    ic.convertToGray8()
    IJ.setThreshold(imp, 2, 255)
    IJ.run(imp, "Convert to Mask", "")
    IJ.run(imp, "Remove Outliers...",
           "radius=5" + " threshold=50" + " which=Dark")
    IJ.run(imp, "Remove Outliers...",
           "radius=5" + " threshold=50" + " which=Bright")

    imp.getProcessor().invert()
    rm = RoiManager(True)
    imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE)

    boundroi = ThresholdToSelection.run(imp)
    rm.addRoi(boundroi)

    if not displayImages:
        imp.changes = False
        imp.close()

    images = [None] * 5
    intensities = [None] * 5
    blobsarea = [None] * 5
    blobsnuclei = [None] * 5
    bigAreas = [None] * 5

    for chan in channels:
        v, x = chan
        images[x] = IJ.openImage(inputDirectory + subFolder + '/' +
                                 rreplace(filename, "_ch00.tif", "_ch0" +
                                          str(x) + ".tif"))
        imp = images[x]
        for roi in rm.getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA)
            intensities[x] = stats.mean
            bigAreas[x] = stats.area

    rm.close()
    # Opens the ch00 image and sets default properties

    imp = IJ.openImage(inputDirectory + subFolder + '/' + filename)
    IJ.run(
        imp, "Properties...",
        "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
    )

    # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html

    ic = ImageConverter(imp)
    ic.convertToGray8()

    IJ.run(imp, "Remove Outliers...",
           "radius=2" + " threshold=50" + " which=Dark")

    IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur))

    IJ.setThreshold(imp, lowerBounds[0], 255)

    if displayImages:
        imp.show()
    IJ.run(imp, "Convert to Mask", "")
    IJ.run(imp, "Watershed", "")

    if not displayImages:
        imp.changes = False
        imp.close()

    # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager

    table = ResultsTable()
    roim = RoiManager(True)
    ParticleAnalyzer.setRoiManager(roim)
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA,
                          table, 15, 9999999999999999, 0.2, 1.0)
    pa.setHideOutputImage(True)
    #imp = impM

    # imp.getProcessor().invert()
    pa.analyze(imp)

    areas = table.getColumn(0)

    # This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel
    # It will save all the area fractions into a 2d array called areaFractionsArray

    areaFractionsArray = [None] * 5
    for chan in channels:
        v, x = chan
        # Opens each image and thresholds

        imp = images[x]
        IJ.run(
            imp, "Properties...",
            "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
        )

        ic = ImageConverter(imp)
        ic.convertToGray8()
        IJ.setThreshold(imp, lowerBounds[x], 255)

        if displayImages:
            imp.show()
            WaitForUserDialog("Title",
                              "Adjust Threshold for Marker " + v).show()

        IJ.run(imp, "Convert to Mask", "")

        # Measures the area fraction of the new image for each ROI from the ROI manager.
        areaFractions = []
        for roi in roim.getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.AREA_FRACTION)
            areaFractions.append(stats.areaFraction)

        # Saves the results in areaFractionArray

        areaFractionsArray[x] = areaFractions

    roim.close()

    for chan in channels:
        v, x = chan

        imp = images[x]
        imp.deleteRoi()
        roim = RoiManager(True)
        ParticleAnalyzer.setRoiManager(roim)
        pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                              Measurements.AREA, table, 15, 9999999999999999,
                              0.2, 1.0)
        pa.analyze(imp)

        blobs = []
        for roi in roim.getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.AREA)
            blobs.append(stats.area)

        blobsarea[x] = sum(blobs)
        blobsnuclei[x] = len(blobs)

        if not displayImages:
            imp.changes = False
            imp.close()
        roim.reset()
        roim.close()

    # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column

    summary = {}

    summary['Image'] = filename
    summary['Directory'] = subFolder

    # Adds usual columns

    summary['size-average'] = 0
    summary['#nuclei'] = 0
    summary['all-negative'] = 0

    summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0
    summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0

    # Creates the fieldnames variable needed to create the csv file at the end.

    fieldnames = [
        'Name', 'Directory', 'Image', 'size-average',
        'too-big-(>' + str(tooBigThreshold) + ')',
        'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei',
        'all-negative'
    ]

    # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei)

    summary["organoid-area"] = bigAreas[x]
    fieldnames.append("organoid-area")

    for chan in channels:
        v, x = chan
        summary[v + "-positive"] = 0
        fieldnames.append(v + "-positive")

        summary[v + "-intensity"] = intensities[x]
        fieldnames.append(v + "-intensity")

        summary[v + "-blobsarea"] = blobsarea[x]
        fieldnames.append(v + "-blobsarea")

        summary[v + "-blobsnuclei"] = blobsnuclei[x]
        fieldnames.append(v + "-blobsnuclei")

    # Adds the column for colocalization between first and second marker

    if len(channels) > 2:
        summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0
        fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive')

    # Adds the columns for colocalization between all three markers

    if len(channels) > 3:
        summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0
        summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0
        summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] +
                '-positive'] = 0

        fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive')
        fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive')
        fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' +
                          channels[3][0] + '-positive')

    # Loops through each particle and adds it to each field that it is True for.

    areaCounter = 0
    for z, area in enumerate(areas):

        log.write(str(area))
        log.write("\n")

        if area > tooBigThreshold:
            summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1
        elif area < tooSmallThreshold:
            summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1
        else:

            summary['#nuclei'] += 1
            areaCounter += area

            temp = 0
            for chan in channels:
                v, x = chan
                if areaFractionsArray[x][z] > areaFractionThreshold[
                        0]:  #theres an error here im not sure why. i remember fixing it before
                    summary[chan[0] + '-positive'] += 1
                    if x != 0:
                        temp += 1

            if temp == 0:
                summary['all-negative'] += 1

            if len(channels) > 2:
                if areaFractionsArray[1][z] > areaFractionThreshold[1]:
                    if areaFractionsArray[2][z] > areaFractionThreshold[2]:
                        summary[channels[1][0] + '-' + channels[2][0] +
                                '-positive'] += 1

            if len(channels) > 3:
                if areaFractionsArray[1][z] > areaFractionThreshold[1]:
                    if areaFractionsArray[3][z] > areaFractionThreshold[3]:
                        summary[channels[1][0] + '-' + channels[3][0] +
                                '-positive'] += 1
                if areaFractionsArray[2][z] > areaFractionThreshold[2]:
                    if areaFractionsArray[3][z] > areaFractionThreshold[3]:
                        summary[channels[2][0] + '-' + channels[3][0] +
                                '-positive'] += 1
                        if areaFractionsArray[1][z] > areaFractionThreshold[1]:
                            summary[channels[1][0] + '-' + channels[2][0] +
                                    '-' + channels[3][0] + '-positive'] += 1

    # Calculate the average of the particles sizes

    if float(summary['#nuclei']) > 0:
        summary['size-average'] = round(areaCounter / summary['#nuclei'], 2)

    # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image)

    with open(outputDirectory + "/" + outputName + ".csv", 'a') as csvfile:

        writer = csv.DictWriter(csvfile,
                                fieldnames=fieldnames,
                                extrasaction='ignore',
                                lineterminator='\n')
        if os.path.getsize(outputDirectory + "/" + outputName + ".csv") < 1:
            writer.writeheader()
        writer.writerow(summary)
Пример #40
0
from ij import IJ
from ij.measure import ResultsTable

# Get current ImagePlus
image = IJ.getImage()
IJ.run("Clear Results")
IJ.setThreshold(200, 10000)

for slice in range(1,image.getNSlices()+1,1):
	image.setSlice(slice)
	IJ.run("Select All")
	IJ.run("Measure")

rt = ResultsTable.getResultsTable()
baseline = (rt.getValue("IntDen",0) + rt.getValue("IntDen",1) + rt.getValue("IntDen",2) + rt.getValue("IntDen",3))/4.0
for result in range(0,rt.getCounter()):
	cur_intensity = rt.getValue("IntDen",result)
	ratio = cur_intensity/baseline
	rt.setValue("RawIntDen",result,ratio)

rt.updateResults()
Пример #41
0
if not os.path.exists(saving_dir):
	os.makedirs(saving_dir)
	print('i made it')
else:
	print('it already exists')



rm=None

for img_ind,image in enumerate(proc_images):
	imp = IJ.openImage(image);
	imp.show()

	IJ.setThreshold(128,128)

	#rm = None#RoiManager.getInstance()
	if not rm:
	  rm = RoiManager()
	else:
		rm.reset()
	
	#IJ.run(imp,"Analyze Particles...", "size=112-Infinity exclude add")
	rt=ResultsTable()
	pa=ParticleAnalyzer(EXCLUDE_EDGE_PARTICLES | ADD_TO_MANAGER,
                        0,
                        rt,
                        112/4,
                        200,
                        0.0,
def analyzeImage(passImage, passModel, passProbability, passOutput):
    retResults = list()

    # Apply weka training model to image
    wekaSeg = WekaSegmentation(passImage)
    wekaSeg.loadClassifier(passModel)
    wekaSeg.applyClassifier(True)

    # Extract probability map
    wekaImg = wekaSeg.getClassifiedImage()
    wekaImg.show()
    IJ.run("Clear Results")

    # Process each slice
    for sliceIdx in range(ROW_BACKGROUND + 1):
        # Select slice and duplicate
        IJ.selectWindow("Probability maps")
        IJ.setSlice(sliceIdx + 1)
        IJ.run("Duplicate...", "title=temp")

        # Apply threshold to probability
        IJ.setThreshold(passProbability, 1, "Black & White")

        # For background, take inverse
        if sliceIdx == ROW_BACKGROUND: IJ.run("Invert")

        # Change background to NaN for area, then measure
        IJ.run("NaN Background", ".")
        IJ.run("Measure")

        # Save image to output directory
        fileParts = passImage.getTitle().split(".")
        IJ.save(
            os.path.join(
                passOutput,
                "{0}-{1}.{2}".format(fileParts[0], FILE_TYPE[sliceIdx],
                                     '.'.join(fileParts[1:]))))

        IJ.selectWindow("temp")
        IJ.run("Close")

    # Close probability maps
    IJ.selectWindow("Probability maps")
    IJ.run("Close")

    # Obtain results
    tempResults = list()
    tableResults = ResultsTable.getResultsTable()
    for rowIdx in range(tableResults.size()):
        tempResults.append(
            [float(x) for x in tableResults.getRowAsString(rowIdx).split()])

    # Compile image statistics as M/(M+F), F/(M+F), M/total, F/total, U/total, E/total, M+F, total
    mfTotal = tempResults[ROW_MALE][FIELD_AREA] + tempResults[ROW_FEMALE][
        FIELD_AREA]
    total = tempResults[ROW_BACKGROUND][FIELD_AREA]

    retResults.append(tempResults[ROW_MALE][FIELD_AREA] / mfTotal)
    retResults.append(tempResults[ROW_FEMALE][FIELD_AREA] / mfTotal)
    retResults.append(tempResults[ROW_MALE][FIELD_AREA] / total)
    retResults.append(tempResults[ROW_FEMALE][FIELD_AREA] / total)
    retResults.append(tempResults[ROW_UNDIF][FIELD_AREA] / total)
    retResults.append(tempResults[ROW_EXTRA][FIELD_AREA] / total)
    retResults.append(mfTotal)
    retResults.append(total)

    return retResults