Example #1
0
def minMax(im, min, max):
	# ip = im.getProcessor()
	# ip.setMinAndMax(min,max)
	# ip.applyLut()
	IJ.setMinAndMax(im, min, max)
	IJ.run(im, 'Apply LUT', '')
	return im
def Make8bit_UsingMinMax(_imp):
    imp = _imp.duplicate()
    stats = StackStatistics(imp)
    IJ.setMinAndMax(imp, stats.min, stats.max)
    IJ.run(imp, "8-bit", "")
    IJ.setMinAndMax(imp, 0, 255)
    return imp
def Objects3D(_img, impRedirect, mpar={"vmin": 2, "vmax": 100000}, _gui=False):
    print "Objects3D:"
    _img.show()
    impRedirect.show()
    options = (
        "mean_gray_value centroid dots_size=5 font_size=10 show_numbers white_numbers store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=[%s]"
        % impRedirect.title
    )
    # print options
    print "image: " + _img.title
    print "redirect to: " + impRedirect.title
    IJ.run("3D OC Options", options)
    IJ.run(
        _img,
        "3D Objects Counter",
        "threshold=128 slice=35 min.=%s max.=%s surfaces statistics summary" % (mpar["vmin"], mpar["vmax"]),
    )
    impObjects = IJ.getImage()
    IJ.run(impObjects, "16 colors", "")
    # somehow find the number of objects detected and set the LUT
    IJ.setMinAndMax(impObjects, 0, 2)
    impObjects.hide()
    _img.hide()
    impRedirect.hide()
    return (impObjects,)
Example #4
0
    def process(self, image, seeds=None):
        self.objects = None
        self.labelImage = None
        duplicator = Duplicator()
        spots = duplicator.run(image)
        IJ.setMinAndMax(spots, 0, 1)
        IJ.run(spots, "16-bit", "")
        spot3DImage = ImageHandler.wrap(spots)
        if seeds != None:
            seed3DImage = ImageHandler.wrap(seeds)
        else:
            seed3DImage = self.__computeSeeds(spots)

        algorithm = Segment3DSpots(spot3DImage, seed3DImage)
        algorithm.show = False
        algorithm.setSeedsThreshold(self.seedsThreshold)
        algorithm.setLocalThreshold(self.localBackground)
        algorithm.setWatershed(self.watershed)
        algorithm.setVolumeMin(self.volumeMin)
        algorithm.setVolumeMax(self.volumeMax)
        algorithm.setMethodLocal(Segment3DSpots.LOCAL_CONSTANT)
        algorithm.setMethodSeg(Segment3DSpots.SEG_MAX)
        algorithm.segmentAll()
        self.objects = algorithm.getObjects()
        self.labelImage = ImagePlus("OM_" + spots.getTitle(), algorithm.getLabelImage().getImageStack())

        return self.labelImage
def modulation_contrast(raw_image_title, sir_image_title, do_map):
    IJ.selectWindow(raw_image_title)
    IJ.run("Modulation Contrast", "angles=3 phases=5 z_window_half-width=1")

    output_images = []
    if do_map:
        IJ.run(
            "Modulation Contrast Map", "calculate_mcnr_from_raw_data=" +
            raw_image_title + " camera_bit_depth=16 or,_specify_mcnr_stack=" +
            raw_image_title.rsplit('.', 1)[0] +
            "_MCN reconstructed_data_stack=" + sir_image_title)
        IJ.selectWindow(sir_image_title.rsplit('.', 1)[0] + '_MCM')
        mcm_imp = IJ.getImage()
        output_images.append(mcm_imp)

    IJ.selectWindow(raw_image_title.rsplit('.', 1)[0] + '_MCN')
    mcn_imp = IJ.getImage()
    IJ.setMinAndMax(0, 255)
    IJ.run("8-bit")
    output_images.append(mcn_imp)

    statistics = {}
    statistics.update(parse_log('average feature MCNR = '))
    statistics.update(parse_log('estimated Wiener filter optimum = '))

    return output_images, statistics
Example #6
0
def make_16bit_using_minmax(_imp):
  # ????? this does not make sense, or ???
  imp = _imp.duplicate()
  stats = StackStatistics(imp)
  IJ.setMinAndMax(imp, stats.min, stats.max)
  IJ.run(imp, "16-bit", "")
  IJ.setMinAndMax(imp, 0, 65535)
  return imp
Example #7
0
def make_16bit_using_minmax(_imp):
  # ????? this does not make sense, or ???
  imp = _imp.duplicate()
  stats = StackStatistics(imp)
  IJ.setMinAndMax(imp, stats.min, stats.max)
  IJ.run(imp, "16-bit", "")
  IJ.setMinAndMax(imp, 0, 65535)
  return imp
def DistanceMap(_img, mpar={}, _gui=False):
    imp = Duplicator().run(_img)
    IJ.run(imp, "Exact Euclidean Distance Transform (3D)", "")
    imp = IJ.getImage()
    IJ.setMinAndMax(imp, 0, 65535)
    IJ.run(imp, "16-bit", "")
    imp.setTitle("DistanceMap")
    imp.hide()
    return (imp,)
def Multiply(imp1, imp2):
    ic = ImageCalculator()
    imp = ic.run("Multiply create stack", imp1, imp2)
    stats = StackStatistics(imp)
    IJ.setMinAndMax(imp, stats.min, stats.max)
    print stats
    imp.setTitle("Multiply")
    imp.show()
    return imp
Example #10
0
def previewDisplaySettings(image, title, zoom, cal):
    """Apply wanted settings for previews"""
    ImageConverter.setDoScaling(0)
    ImageConverter(image).convertToGray16()
    image.show()
    IJ.run("glasbey_on_dark")
    IJ.setMinAndMax(image, 0, 255)
    image.setTitle(title)
    image.setCalibration(cal)
    IJ.run("Set... ", "zoom=" + str(zoom))
def extractChannel(imp, nChannel, nFrame):
    """extract a channel from the image, at a given frame returning a new imagePlus labelled with the channel name"""

    stack = imp.getImageStack()
    ch = ImageStack(imp.width, imp.height)
    for i in range(imp.getNSlices()):
        index = imp.getStackIndex(nChannel, i, nFrame)
        ch.addSlice(str(i), stack.getProcessor(index))
    imp3 = ImagePlus("Channel " + str(nChannel), ch).duplicate()
    stats = StackStatistics(imp3)
    IJ.setMinAndMax(imp3, stats.min, stats.max)
    return imp3
Example #12
0
def kotaMiuraBrightness(targetPath, fn):
    '''Taken and updated from script by Kota Miura (2015) found at:
	http://wiki.cmci.info/documents/120206pyip_cooking/python_imagej_cookbook#automatic_brightnesscontrast_button'''
    autoThreshold = 0
    AUTO_THRESHOLD = 5000

    imp = IJ.getImage()
    cal = imp.getCalibration()
    imp.setCalibration(None)
    stats = imp.getStatistics()  # get uncalibrated stats
    imp.setCalibration(cal)
    limit = int(stats.pixelCount / 10)
    histogram = stats.histogram(
    )  #int[] I just added the () after the histogram...?
    #histogram = imp.getHistogram(256) # trying to make it bin itself in a smooth way like the java version of the code
    if autoThreshold < 10:
        autoThreshold = AUTO_THRESHOLD
    else:
        autoThreshold /= 2
    threshold = int(stats.pixelCount / autoThreshold)  #int
    i = -1
    found = False
    count = 0  # int
    while True:
        i += 1
        count = histogram[i]
        if count > limit:
            count = 0
        found = count > threshold
        if found or i >= 255:
            #   if 0 not in (!found, i<255) :
            break
    hmin = i  #int
    i = 256
    while True:
        i -= 1
        count = histogram[i]
        if count > limit:
            count = 0
        found = count > threshold
        if found or i < 1:
            #   if 0 not in (!found, i<255) :
            break
    hmax = i  #int
    IJ.setMinAndMax(imp, hmin, hmax)
    #IJ.run(imp, "8-bit", "")
    IJ.run(imp, "Apply LUT", "")  # this step makes histogram odd
    imp.updateAndDraw()
    return threshold, limit, hmin, hmax
def procAZtecImg(imp, loG, hiG, radMF, unPerPx, units=-6):
	"""procAZtecImg(imp, loG, hiG, radMF, unPerPx, units=-6)
	Process an AZTec TIF image
	Inputs:
	imp     - the image plus
	loG     - the gray level to set as black
	hiG     - the gray level to set as white
	radMF   - the radius for a median filter
	unPerPx - the size of a pixel in units
	units   - the power w.r.t. meters. Default = -6
	
	Returns:
	an image plus of a duplicated image
	"""
	name = imp.getShortTitle()
	# make a copy
	wrk = imp.duplicate()
	IJ.run(wrk, "Median...", "radius=%g" % radMF)
	IJ.setMinAndMax(wrk, loG, hiG)	
	jmg.calibImageDirect(wrk, unPerPx, units=-6)
	wrk.setTitle(name)
	return wrk
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])
Example #15
0
labId = "qm-04513"
smpId = "RAD-2015-0148Y-HCl-xs"

datDir	 = edsDir + "/Oxford/" + ePrjDir + "/reports/" + labId + "-" + smpId
sTifPath = datDir + "/tif/"

bSetMinMax = False
gMin =  1000
gMax = 11400
fwUnits = 28.9


units = IJ.micronSymbol + "m"

imp = IJ.getImage()
imp = jmg.calibImage(imp, fwUnits, units=-6)
if(bSetMinMax == True):
	IJ.setMinAndMax(gMin, gMax)
imp.updateAndRepaintWindow()

ti = imp.getShortTitle()
fi = sTifPath + ti + ".tif"
fs = FileSaver(imp)
imp.changes = False
print(fi)
if fs.saveAsTiff(fi):
	print "Tif saved successfully at ", fi  


print("done")
Example #16
0
    clij2.clear()
    segmentImp = extractChannel(imp1, segmentChannel, nFrame)
    gfx1 = clij2.push(segmentImp)
    gfx2 = clij2.create(gfx1)
    gfx3 = clij2.create(gfx1)
    gfx4 = clij2.create(gfx1)
    gfx5 = clij2.create(gfx1)
    gfx1, gfx2, gfx3, gfx4, gfx5 = segment(gfx1, gfx2, gfx3, gfx4, gfx5,
                                           gaussianSigma, thresholdMethod,
                                           maxIntensity, largeDoGSigma,
                                           pixelAspect, originalTitle, topHat,
                                           topHatSigma, manualSegment,
                                           manualThreshold)

    thresholdImp = clij2.pull(gfx3)
    IJ.setMinAndMax(thresholdImp, 0, 1)
    thresholdImp.setCalibration(cal)
    thresholdImp.setTitle("Binary mask of " + originalTitle)

    table, FRETimp2, FRETProjImp, labelImp = fretCalculations(
        imp1, nFrame, donorChannel, acceptorChannel, acceptorChannel2, table,
        gfx5, gfx2, gfx3, gfx4, gfx1, originalTitle)
    if makeNearProj == True:
        nearZImp = nearestZProject(FRETimp2)
        conNearZStack = concatStacks(conNearZStack, nearZImp)
        nearZImp.close()

    #add the images to concatenated stacks
    conThresholdStack = concatStacks(conThresholdStack, thresholdImp)
    conFRETImp2Stack = concatStacks(conFRETImp2Stack, FRETimp2)
    conFRETProjImpStack = concatStacks(conFRETProjImpStack, FRETProjImp)
# Apply an automatic threshold method to an image on the GPU
#
# Author: Robert Haase, [email protected]
#         April 2019
#########################################

from ij import IJ
from net.haesleinhuepf.clij import CLIJ

IJ.run("Close All")

# load example image
imp = IJ.openImage("c:/structure/code/clij-docs/src/main/resources/blobs.tif")
imp.show()

# init GPU
clij = CLIJ.getInstance()

# push image to GPU
input = clij.push(imp)

# reserve memory for output, same size and type as input
output = clij.create(input)

# apply threshold method on GPU
clij.op().automaticThreshold(input, output, "Otsu")

# show result
clij.pull(output).show()
IJ.setMinAndMax(0, 1)
Example #18
0
def make_8bit_using_min_max(_imp):
  imp = _imp.duplicate()
  stats = StackStatistics(imp)
  IJ.setMinAndMax(imp, stats.min, stats.max)
  ImageConverter(imp).convertToGray8() 
  return imp
    gfx1 = clij2.push(segmentImp)
    gfx2 = clij2.create(gfx1)
    gfx3 = clij2.create(gfx1)
    gfx4 = clij2.create(gfx1)
    gfx5 = clij2.create(gfx1)
    gfx1, gfx2, gfx3, gfx4, gfx5 = segment(gfx1, gfx2, gfx3, gfx4, gfx5,
                                           gaussianSigma, thresholdMethod,
                                           maxIntensity, largeDoGSigma,
                                           pixelAspect, originalTitle, topHat,
                                           topHatSigma, manualSegment,
                                           manualThreshold)

    thresholdImp = clij2.pull(gfx3)
    labelImp = clij2.pull(gfx5)
    gfx4 = clij2.push(quantImp)
    IJ.setMinAndMax(thresholdImp, 0, 1)
    thresholdImp.setCalibration(cal)
    thresholdImp.setTitle("Binary mask of " + originalTitle)

    #add the images to concatenated stacks
    conThresholdStack = concatStacks(conThresholdStack, thresholdImp)
    conlabelImpStack = concatStacks(conlabelImpStack, labelImp)
    table = quantify(gfx4, gfx5, table, nFrame, originalTitle)

    thresholdImp.close()
    labelImp.close()
    IJ.log("Processing timeframe: " + str(nFrame))
table.show("Results of " + originalTitle)
#Show the images and make the images pretty... I should have put in a function`

conThresholdImp = ImagePlus("Threshold image for " + originalTitle,
Example #20
0
def analyze(iDataSet, tbModel, p):
  
  #
  # Init
  #
  IJ.run("Options...", "iterations=1 count=1"); 
  close_all_image_windows()
    
  #
  # Open file
  #
  filepath = tbModel.getFileAbsolutePathString(iDataSet, "Input", "IMG")
  
  if filepath.endswith('.mha'):
    IJ.openImage(filepath)
    imp = IJ.getImage()
    # get rid of the unsigned int problem
    IJ.run(imp, "32-bit", "");
    IJ.setMinAndMax(0, 65535);
    IJ.run(imp, "16-bit", "");
  elif filepath.endswith('.h5'):
    imp = None
    IJ.run(imp, "Scriptable load HDF5...", "load="+filepath+" datasetnames="+p["HDF5_data_set_name"]+" nframes=1 nchannels=1");
    imp = IJ.getImage()
  else:
    imp = IJ.openImage(filepath)
    imp.show()

  #
  # Crop after loading
  #  
  if p['crop']:
    x_min = int(p['mask_roi'][0])
    y_min = int(p['mask_roi'][1])
    z_min = int(p['mask_roi'][2])
    x_width = int(p['mask_roi'][3])
    y_width = int(p['mask_roi'][4])
    z_width = int(p['mask_roi'][5])
  
    stack = imp.getImageStack()
    stack_cropped = stack.crop(x_min, y_min, z_min, x_width, y_width, z_width)
    imp = ImagePlus('',stack)
  
  #
  # Convert
  #
  IJ.setMinAndMax(p['map_to_zero'], p['map_to_max']);
  IJ.run(imp, p['output_bit_depth'], "");

  #
  # Scale (Binning)
  #
  if p['binning']:
    sx = float(1.0/p['binning_x'])
    sy = float(1.0/p['binning_y'])
    sz = float(1.0/p['binning_z'])
    parameters =  "x="+str(sx)+" y="+str(sy)+" z="+str(sz)+" interpolation=Bilinear average process create"
    IJ.run(imp, "Scale...", parameters);
    imp = IJ.getImage()


  #
  # Save converted volume data
  #
  if p['save_volume_data']:
    converted_filename = tbModel.getFileName(iDataSet, "Input", "IMG")+"--converted."+p['output_format']
    tbModel.setFileAbsolutePath(p['output_folder'], converted_filename, iDataSet, 'Output', 'IMG')
    IJ.saveAs(imp, p['output_format'], tbModel.getFileAbsolutePathString(iDataSet, 'Output', 'IMG'))
    
  #
  # Projections 
  #
  
  if p['save_xyz_projections']:
    # compute one XYZ projection in one image
    projection = 'XYZ'
    imp_projected = project_XYZ(imp)
    # construct output filename 
    projected_filename = tbModel.getFileName(iDataSet, "Input", "IMG")+"--"+projection+"."+p['output_format']
    # store in table
    tbModel.setFileAbsolutePath(p['output_folder'], projected_filename, iDataSet, projection, "IMG")
    # store on disk
    IJ.saveAs(imp_projected,p['output_format'],tbModel.getFileAbsolutePathString(iDataSet, projection, "IMG"))
    '''
    projections = ['X','Y','Z']
  
    for projection in projections:
      # compute projection  
      imp_projected = project(imp, projection)
      # construct output filename 
      projected_filename = tbModel.getFileName(iDataSet, "Input", "IMG")+"--"+projection+"."+p['output_format']
      # store in table
      tbModel.setFileAbsolutePath(p['output_folder'], projected_filename, iDataSet, projection, "IMG")
      # store on disk
      IJ.saveAs(imp_projected,p['output_format'],tbModel.getFileAbsolutePathString(iDataSet, projection, "IMG"))
    '''

   
         
  return tbModel
		tracked[i]= 11
print test.labelValues
fp= ShortProcessor(len(tracked), 1,tracked , None)

labelerImp= ImagePlus("labeler", fp)
src2=clij2.push(labelerImp)
conLabeledStack=ImageStack(imp1.width, imp1.height)


if frames>1:
	for nFrame in range(1,frames+1):

		imp3=extractFrame(imp1, nFrame)
		src=clij2.push(imp3)
		dst=clij2.create(src)
		clij2.replaceIntensities(src, src2, dst)
		LabeledImp=clij2.pull(dst)
		conLabeledStack = concatStacks( conLabeledStack, LabeledImp)
	concatLabeledImp= ImagePlus("Labeled "+imageName, conLabeledStack)
	
	ImageConverter.setDoScaling(0)
	ImageConverter(concatLabeledImp).convertToGray16()
	
	IJ.setMinAndMax(concatLabeledImp, 0, 255)
	concatLabeledImp.setCalibration(imp1.getCalibration())
	concatLabeledImp.setDimensions(1, imp1.getNSlices(), imp1.getNFrames())
	concatLabeledImp = CompositeImage(concatLabeledImp, CompositeImage.COMPOSITE)
	concatLabeledImp.show()
	IJ.run("glasbey_on_dark")
	labelerImp.close()
Example #22
0
def convert_to_8bit(imp, vmin, vmax):
  IJ.setMinAndMax(imp, vmin, vmax)
  ImageConverter(imp).convertToGray8() 
  return imp
def previewDialog(imp):
    gd = GenericDialogPlus("Nuclear segmentation and quantification v1.01")

    #create a list of the channels in the provided imagePlus
    types = []
    for i in xrange(1, imp.getNChannels() + 1):
        types.append(str(i))

    #user can pick which channel to base the segmentation on
    gd.addChoice("Channel number to use for segmentation", types, types[0])
    gd.addChoice("Channel to quantify", types, types[0])
    methods = [
        "Otsu", "Default", "Huang", "Intermodes", "IsoData", "IJ_IsoData",
        "Li", "MaxEntropy", "Mean", "MinError", "Minimum", "Moments",
        "Percentile", "RenyiEntropy", "Shanbhag", "Triangle", "Yen"
    ]
    gd.addChoice("Autosegmentation method", methods, methods[0])
    intensities = ["254", "4094", "65534"]
    gd.addChoice("Max Intensity", intensities, intensities[-1])
    gd.addSlider("Small DoG sigma", 0.5, 10, 1, 0.1)
    gd.addSlider("Large DoG sigma", 0.5, 20, 5, 0.1)
    gd.addCheckbox("TopHat background subtraction? (Slower, but better) ",
                   True)
    gd.addSlider("TopHat sigma", 5, 20, 8, 0.1)
    gd.setModal(False)
    gd.addCheckbox("Manually set threshold? ", False)
    gd.addSlider("Manual threshold", 10, 65534, 2000, 1)

    gd.hideCancelButton()
    gd.showDialog()

    cal = imp.getCalibration()
    pixelAspect = (cal.pixelDepth / cal.pixelWidth)

    originalTitle = imp1.getTitle()

    choices = gd.getChoices()
    print choices
    sliders = gd.getSliders()
    checkboxes = gd.getCheckboxes()
    segmentChannel = int(choices.get(0).getSelectedItem())
    quantChannel = int(choices.get(1).getSelectedItem())
    thresholdMethod = choices.get(2).getSelectedItem()
    maxIntensity = int(choices.get(3).getSelectedItem())
    gaussianSigma = sliders.get(0).getValue() / 10.0
    largeDoGSigma = gd.sliders.get(1).getValue() / 10.0
    topHat = gd.checkboxes.get(0).getState()
    topHatSigma = gd.sliders.get(2).getValue() / 10.0

    manualSegment = gd.checkboxes.get(1).getState()
    manualThreshold = gd.sliders.get(3).getValue()

    segmentChannelOld = segmentChannel
    thresholdMethodOld = thresholdMethod
    maxIntensityOld = maxIntensity
    gaussianSigmaOld = gaussianSigma
    largeDoGSigmaOld = largeDoGSigma
    topHatOld = topHat
    topHatSigmaOld = topHatSigma
    manualSegmentOld = manualSegment
    manualThresholdOld = manualThreshold

    clij2.clear()

    segmentImp = extractChannel(imp1, segmentChannel, 0)

    try:
        gfx1 = clij2.push(segmentImp)
        gfx2 = clij2.create(gfx1)
        gfx3 = clij2.create(gfx1)
        gfx4 = clij2.create(gfx1)
        gfx5 = clij2.create(gfx1)
        gfx7 = clij2.create([imp.getWidth(), imp.getHeight()])
    except:
        try:

            Thread.sleep(500)
            IJ.log(
                "Succeeded to sending to graphics card on the second time...")
            gfx1 = clij2.push(segmentImp)
            gfx2 = clij2.create(gfx1)
            gfx3 = clij2.create(gfx1)
            gfx4 = clij2.create(gfx1)
            gfx5 = clij2.create(gfx1)
            gfx7 = clij2.create([imp.getWidth(), imp.getHeight()])
        except:
            errorDialog(
                """Could not send image to graphics card, it may be too large!
		
			Easy solutions: Try	processing as 8-bit, cropping or scaling the image, or
			select a different CLIJ2 GPU.

			This issue is often intermittent, so trying again may also work! 

			See the "Big Images on x graphics cards' notes at:
			https://clij2.github.io/clij2-docs/troubleshooting for more solutions
			
			""" + str(clij2.reportMemory()))

    gfx1, gfx2, gfx3, gfx4, gfx5 = segment(gfx1, gfx2, gfx3, gfx4, gfx5,
                                           gaussianSigma, thresholdMethod,
                                           maxIntensity, largeDoGSigma,
                                           pixelAspect, originalTitle, topHat,
                                           topHatSigma, manualSegment,
                                           manualThreshold)
    clij2.maximumZProjection(gfx5, gfx7)

    labelPrevImp = clij2.pull(gfx7)
    IJ.setMinAndMax(labelPrevImp, 0, clij2.getMaximumOfAllPixels(gfx7))
    labelPrevImp.setTitle("Preview segmentation")
    labelPrevImp.show()

    IJ.run("glasbey_inverted")

    while ((not gd.wasCanceled()) and not (gd.wasOKed())):

        segmentChannel = int(choices.get(0).getSelectedItem())
        quantChannel = int(choices.get(1).getSelectedItem())
        thresholdMethod = choices.get(2).getSelectedItem()
        maxIntensity = int(choices.get(3).getSelectedItem())
        gaussianSigma = sliders.get(0).getValue() / 10.0
        largeDoGSigma = gd.sliders.get(1).getValue() / 10.0
        topHat = gd.checkboxes.get(0).getState()
        topHatSigma = gd.sliders.get(2).getValue() / 10.0

        manualSegment = gd.checkboxes.get(1).getState()
        manualThreshold = gd.sliders.get(3).getValue()

        if (segmentChannelOld != segmentChannel
                or thresholdMethodOld != thresholdMethod
                or maxIntensityOld != maxIntensity
                or gaussianSigmaOld != gaussianSigma
                or largeDoGSigmaOld != largeDoGSigma or topHatOld != topHat
                or topHatSigmaOld != topHatSigma
                or manualSegmentOld != manualSegment
                or manualThresholdOld != manualThreshold):

            if segmentChannelOld != segmentChannel:
                clij2.clear()
                segmentImp = extractChannel(imp1, segmentChannel, 0)
                gfx1 = clij2.push(segmentImp)
                gfx2 = clij2.create(gfx1)
                gfx3 = clij2.create(gfx1)
                gfx4 = clij2.create(gfx1)
                gfx5 = clij2.create(gfx1)
                gfx7 = clij2.create([imp.getWidth(), imp.getHeight()])
            gfx1, gfx2, gfx3, gfx4, gfx5 = segment(
                gfx1, gfx2, gfx3, gfx4, gfx5, gaussianSigma, thresholdMethod,
                maxIntensity, largeDoGSigma, pixelAspect, originalTitle,
                topHat, topHatSigma, manualSegment, manualThreshold)
            clij2.maximumZProjection(gfx5, gfx7)
            labelPrevImp.close()
            labelPrevImp = clij2.pull(gfx7)
            IJ.setMinAndMax(labelPrevImp, 0, clij2.getMaximumOfAllPixels(gfx7))
            labelPrevImp.setTitle("Preview segmentation")
            labelPrevImp.show()

            IJ.run("glasbey_inverted")

        segmentChannelOld = segmentChannel
        thresholdMethodOld = thresholdMethod
        maxIntensityOld = maxIntensity
        gaussianSigmaOld = gaussianSigma
        largeDoGSigmaOld = largeDoGSigma
        topHatOld = topHat
        topHatSigmaOld = topHatSigma

        manualSegmentOld = manualSegment
        manualThresholdOld = manualThreshold

        Thread.sleep(200)
    labelPrevImp.close()

    return segmentChannel, quantChannel, thresholdMethod, maxIntensity, gaussianSigma, largeDoGSigma, topHat, topHatSigma, manualSegment, manualThreshold
Example #24
0
def run():
    ### Default arguments
    two_sarcomere_size = 25  # determined by filter used.
    rotation_angle = 0.0

    ### Get the image we'd like to work with.
    # Don't need to ask where to save the intermediate image since it'll just be saved in the matchedmyo folder anyway
    #   may change this though. In case they want to keep that image around.
    this_img = WindowManager.getCurrentImage()
    if this_img == None:
        ud = WaitForUserDialog(
            "Please select the image you would like to analyze.")
        ud.show()
        this_img = WindowManager.getCurrentImage()
    img_name = this_img.getTitle()

    matchedmyo_path = "/home/AD/dfco222/scratchMarx/matchedmyo/"  # this would be grabbed from the prompt
    gd = GenericDialog("Preprocessing Options")
    gd.addCheckbox("Automatic Resizing/Rotation", True)
    gd.addCheckbox("CLAHE", True)
    gd.addCheckbox("Normalization to Transverse Tubules", True)
    gd.showDialog()
    if gd.wasCanceled():
        return
    auto_resize_rotate = gd.getNextBoolean()
    clahe = gd.getNextBoolean()
    normalize = gd.getNextBoolean()

    if auto_resize_rotate:
        # Clear selection so it takes FFT of full image

        rotation_angle = auto_resize_angle_measure(this_img,
                                                   two_sarcomere_size)

    if clahe:
        clahe_args = "blocksize={} histogram=256 maximum=3 mask=*None* fast_(less_accurate)".format(
            two_sarcomere_size)
        IJ.run(this_img, "Enhance Local Contrast (CLAHE)", clahe_args)

    if normalize:
        # Ask the user to select a subsection of the image that looks healthy-ish.
        ud = WaitForUserDialog(
            "Please select a subsection exhibiting a measure of healthy TT structure using the Rectangle tool.\n"
            + " Only a single cell or several are needed.\n\n" +
            " Press 'OK' when finished.")
        ud.show()
        IJ.setTool("rectangle")

        # Duplicate the selected subsection.
        selection = this_img.crop()
        IJ.run(selection, "Duplicate...", "title=subsection.tif")

        # Grab the subsection image and rotate it.
        selection = WindowManager.getImage("subsection.tif")
        IJ.run(
            selection, "Rotate...",
            "angle={} grid=1 interpolation=Bicubic enlarge".format(
                rotation_angle))

        # Ask the user to select a bounding box that contains only tubules
        # NOTE: Need to get rid of initial selection since it's the entire image and it's annoying to click out of
        IJ.setTool("rectangle")
        IJ.run(selection, "Select None", "")
        ud = WaitForUserDialog(
            "Select a subsection of the image that contains only tubules and no membrane."
        )
        ud.show()

        # Grab the subsection ImagePlus
        selection = WindowManager.getCurrentImage()
        this_window = WindowManager.getActiveWindow()
        selection_small = selection.crop()
        IJ.run(selection, "Close", "")

        # NOTE: May not actually display this depending on how the macros work
        IJ.run(selection_small, "Duplicate...", "title=subsection_small.tif")

        # Smooth the selection using the single TT filter.
        # NOTE: It won't read in so we're just going to hard code it in since it's simple
        tt_filt_row = "0 0 0 1 1 1 1 1 1 0 0 0 0\n"
        tt_filt = ""
        for i in range(21):
            tt_filt += tt_filt_row
        IJ.run("Convolve...", "text1=[" + tt_filt + "] normalize")

        # Segment out the TTs from the 'gaps' using Gaussian Adaptive Thresholding.
        selection_small = WindowManager.getImage("subsection_small.tif")
        IJ.run(selection_small, "Duplicate...", "title=thresholded.tif")
        threshed = WindowManager.getImage("thresholded.tif")
        IJ.run(threshed, "Auto Local Threshold",
               "method=Bernsen radius=7 parameter_1=1 parameter_2=0 white")

        # Select the TTs from the thresholded image.
        IJ.run(threshed, "Create Selection", "")
        tt_selection = WindowManager.getImage("subsection_small.tif")
        IJ.selectWindow("thresholded.tif")
        IJ.selectWindow("subsection_small.tif")
        IJ.run(tt_selection, "Restore Selection", "")

        # Get TT intensity statistics.
        stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV
        stats = IS.getStatistics(tt_selection.getProcessor(), stat_options,
                                 selection_small.getCalibration())
        # Calculate pixel ceiling intensity value based on heuristic.
        # TODO: Add a catch for data type overflow.
        pixel_ceiling = stats.mean + 3 * stats.stdDev
        print "px ceil:", pixel_ceiling

        # Invert selection to get inter-sarcomeric gap intensity statistics.
        IJ.run(tt_selection, "Make Inverse", "")
        stat_options = IS.MEAN | IS.MIN_MAX | IS.STD_DEV
        stats = IS.getStatistics(tt_selection.getProcessor(), stat_options,
                                 selection_small.getCalibration())
        # Calculate pixel floor intensity value based on heuristic.
        pixel_floor = stats.mean - stats.stdDev
        # TODO: Add a catch for data type underflow.
        print "px floor:", pixel_floor

        # Threshold original image based on these values.
        IJ.selectWindow(this_img.getTitle())
        IJ.run(this_img, "Select All", "")
        IJ.setMinAndMax(pixel_floor, pixel_ceiling)
        IJ.run(this_img, "Apply LUT", "")

    ## Ask if it is acceptable.
    gd = GenericDialog("Acceptable?")
    gd.addMessage(
        "If the preprocessed image is acceptable for analysis, hit 'OK' to being analysis.\n"
        + " If the image is unacceptable or an error occurred, hit 'Cancel'")
    gd.showDialog()
    if gd.wasCanceled():
        return

    ## Save the preprocessed image.
    imp = IJ.getImage()
    fs = FileSaver(imp)
    img_save_dir = matchedmyo_path + "myoimages/"  # actually get from user at some point
    img_file_path = img_save_dir + img_name[:-4] + "_preprocessed.tif"
    if os.path.exists(img_save_dir) and os.path.isdir(img_save_dir):
        print "Saving image as:", img_file_path
        if os.path.exists(img_file_path):
            # use dialog box to ask if they want to overwrite
            gd = GenericDialog("Overwrite?")
            gd.addMessage(
                "A file exists with the specified path, \"{}\". Would you like to overwrite it?"
                .format(img_file_path))
            gd.enableYesNoCancel()
            gd.showDialog()
            if gd.wasCanceled():
                return
        elif fs.saveAsTiff(img_file_path):
            print "Preprocessed image saved successfully at:", '"' + img_file_path + '"'
    else:
        print "Folder does not exist or is not a folder!"

    ### Create the YAML file containing the parameters for classification
    ## Ask user for YAML input
    gd = GenericDialog("YAML Input")
    gd.addStringField("imageName", img_file_path, 50)
    #gd.addStringField("maskName", "None")
    gd.addStringField("outputParams_fileRoot", img_file_path[:-4], 50)
    gd.addStringField("outputParams_fileType", "tif")
    gd.addNumericField("outputParams_dpi", 300, 0)
    gd.addCheckbox("outputParams_saveHitsArray", False)
    gd.addStringField("outputParams_csvFile", matchedmyo_path + "results/")
    gd.addCheckbox("TT Filtering", True)
    gd.addToSameRow()
    gd.addCheckbox("LT Filtering", True)
    gd.addToSameRow()
    gd.addCheckbox("TA Filtering", True)
    gd.addNumericField("scopeResolutions_x", 5.0, 3)
    gd.addToSameRow()
    gd.addNumericField("scopeResolutions_y", 5.0, 3)
    gd.addMessage("Enter in filter rotation angles separated by commas.")
    gd.addStringField("", "-25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25", 50)
    gd.addCheckbox("returnAngles", False)
    gd.addCheckbox("returnPastedFilter", True)
    gd.showDialog()
    if gd.wasCanceled():
        return

    strings = [st.text for st in gd.getStringFields()]
    #if strings[1] == "None" or "":
    #	strings[1] = None
    nums = [float(num.text) for num in gd.getNumericFields()]
    nums[0] = int(nums[0])  # Have to make sure the dpi variable is an integer
    checks = [str(bool(boo.state)) for boo in gd.getCheckboxes()]
    iter_argument = ','.join(
        [str(float(it) - rotation_angle) for it in strings[4].split(',')])
    string_block = """imageName: {0[0]}
outputParams:
  fileRoot: {0[1]}
  fileType: {0[2]}
  dpi: {1[0]}
  saveHitsArray: {2[0]}
  csvFile: {0[3]}
preprocess: False
filterTypes:
  TT: {2[1]}
  LT: {2[2]}
  TA: {2[3]}
scopeResolutions:
  x: {1[1]}
  y: {1[2]}
iters: [{3}]
returnAngles: {2[4]}
returnPastedFilter: {2[5]}""".format(strings, nums, checks, iter_argument)
    im_title = this_img.getTitle()
    with cd(matchedmyo_path):
        yaml_file_path = "./YAML_files/" + im_title[:-4] + ".yml"
        with open("./YAML_files/" + im_title[:-4] + ".yml", "w") as ym:
            ym.write(string_block)
        print "Wrote YAML file to:", matchedmyo_path + yaml_file_path[2:]

    ### Run the matchedmyo code on the preprocessed image
    with cd(matchedmyo_path):
        #os.chdir(matchedmyo_path)
        #subprocess.call(["python3", matchedmyo_path+"matchedmyo.py", "fullValidation"])
        subprocess.call(
            ["python3", "matchedmyo.py", "run", "--yamlFile", yaml_file_path])
Example #25
0
def convert_to_8bit(imp, vmin, vmax):
  IJ.setMinAndMax(imp, vmin, vmax)
  ImageConverter(imp).convertToGray8() 
  return imp
Example #26
0
for i in range(0, 36):

	# change the shift from slice to slice
	at = AffineTransform2D();
	at.translate(-input.getWidth() / 2, -input.getHeight() / 2);
	at.rotate(i * 10.0 / 180.0 * Math.PI);
	at.translate(input.getWidth() / 2, input.getHeight() / 2);

	clij.op().affineTransform2D(shiftXgpu, rotatedShiftXgpu, at);
	
	# apply transform
	clij.op().applyVectorfield(input, rotatedShiftXgpu, shiftYgpu, temp);

	# put resulting 2D image in the right plane
	clij.op().copySlice(temp, output, i);

# show result
clij.pull(output).show();
IJ.setMinAndMax(0, 255);

input.close();
shiftXgpu.close();
rotatedShiftXgpu.close();
shiftYgpu.close();
temp.close();
output.close();



Example #27
0
def processImage(filename):
    # many zeiss images have a pyramid format. In order to speed up the evaluation, we chose only the second highest resolution (=series_2).
    # depending on your computer/workstation this parameter can be optimized (i.e. chose series_1 if you have a fast computer or series_3 for slow ones)
    IJ.run(
        "Bio-Formats", "open=" + filename +
        " color_mode=Composite rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT series_2"
    )
    imp = IJ.getImage()
    imp.show()
    if (not entertain):
        imp.show()

    # preparing memory for saving the results
    original1 = NewImage.createFloatImage("Original 1",
                                          imp.getWidth() / tileSize + 1,
                                          imp.getHeight() / tileSize + 1, 1,
                                          NewImage.FILL_BLACK)
    original1Map = original1.getProcessor()

    original2 = NewImage.createFloatImage("Original 2",
                                          imp.getWidth() / tileSize + 1,
                                          imp.getHeight() / tileSize + 1, 1,
                                          NewImage.FILL_BLACK)
    original2Map = original2.getProcessor()

    spotCount1 = NewImage.createFloatImage("Spot count 1",
                                           imp.getWidth() / tileSize + 1,
                                           imp.getHeight() / tileSize + 1, 1,
                                           NewImage.FILL_BLACK)
    spotCount1Map = spotCount1.getProcessor()

    spotCount2 = NewImage.createFloatImage("Spot count 2",
                                           imp.getWidth() / tileSize + 1,
                                           imp.getHeight() / tileSize + 1, 1,
                                           NewImage.FILL_BLACK)
    spotCount2Map = spotCount2.getProcessor()

    ratio = NewImage.createFloatImage("Ratio",
                                      imp.getWidth() / tileSize + 1,
                                      imp.getHeight() / tileSize + 1, 1,
                                      NewImage.FILL_BLACK)
    ratioMap = ratio.getProcessor()

    if (entertain):
        ratio.show()

    # go through all tiles
    for x in range(0, ratioMap.getWidth() - 1):
        for y in range(0, ratioMap.getHeight() - 1):
            # crop out the tile from the original images
            imp.setRoi(Roi(x * tileSize, y * tileSize, tileSize, tileSize))
            channel1 = Duplicator().run(imp, 1, 1, 1, 1, 1, 1)
            channel2 = Duplicator().run(imp, 2, 2, 1, 1, 1, 1)

            # spot detection
            spots1 = detectSpots(channel1,
                                 spotDetection_GaussianBlur_sigma_GFP,
                                 spotDetection_findMaxima_noise_GFP)
            spots2 = detectSpots(channel2,
                                 spotDetection_GaussianBlur_sigma_DAPI,
                                 spotDetection_findMaxima_noise_DAPI)

            # pixel statistics
            statistics1 = channel1.getStatistics()
            statistics2 = channel2.getStatistics()

            # calculate ratio if spots were found
            s1 = 0
            s2 = 0
            r = 0
            if (spots1 is not None and spots2 is not None):
                fp1 = spots1.getFloatPolygon()
                fp2 = spots2.getFloatPolygon()
                s1 = fp1.npoints
                s2 = fp2.npoints
                if (s2 > cutOff_DAPI and s1 > cutOff_GFP):
                    r = 1.0 * s1 / s2

            # fill result memory
            original1Map.setf(x, y, statistics1.mean)
            original2Map.setf(x, y, statistics2.mean)
            spotCount1Map.setf(x, y, s1)
            spotCount2Map.setf(x, y, s2)
            ratioMap.setf(x, y, r)

        if (entertain):
            # show current result image
            ratio.updateAndDraw()
            IJ.run(ratio, "Enhance Contrast", "saturated=0.35")

    # put all results image channels together to one image
    images = []
    images.append(original1)
    images.append(original2)
    images.append(spotCount1)
    images.append(spotCount2)
    images.append(ratio)
    resultMap = RGBStackMerge.mergeChannels(images, False)

    # fix pixel size
    # factor is multiplied by 2 because ImageJ seems to have a problem when using .czi file series of lower resolution (i.e. series_2); please check for individual cases!
    factor = (imp.getWidth() / resultMap.getWidth()) * 2
    IJ.run(
        resultMap, "Properties...", "channels=5 slices=1 frames=1 unit=" +
        imp.getCalibration().getUnit() + " pixel_width=" +
        str(imp.getCalibration().pixelWidth * factor) + " pixel_height=" +
        str(imp.getCalibration().pixelHeight * factor) + " voxel_depth=1.0000")
    IJ.run(
        ratio, "Properties...", "channels=1 slices=1 frames=1 unit=" +
        imp.getCalibration().getUnit() + " pixel_width=" +
        str(imp.getCalibration().pixelWidth * factor) + " pixel_height=" +
        str(imp.getCalibration().pixelHeight * factor) + " voxel_depth=1.0000")

    # visualisation
    resultMap.setC(1)
    IJ.run(resultMap, "Green", "")
    IJ.run(resultMap, "Enhance Contrast", "saturated=0.35")
    resultMap.setC(2)
    IJ.run(resultMap, "Blue", "")
    IJ.run(resultMap, "Enhance Contrast", "saturated=0.35")
    resultMap.setC(3)
    IJ.run(resultMap, "mpl-inferno", "")
    IJ.run(resultMap, "Enhance Contrast", "saturated=0.35")
    resultMap.setC(4)
    IJ.run(resultMap, "mpl-inferno", "")
    IJ.run(resultMap, "Enhance Contrast", "saturated=0.35")
    resultMap.setC(5)
    IJ.run(resultMap, "mpl-inferno", "")
    resultMap.show()
    IJ.resetMinAndMax(resultMap)
    resultMap.setDisplayMode(IJ.COLOR)

    IJ.run(ratio, "mpl-inferno", "")
    IJ.setMinAndMax(ratio, 0, 1)

    # save result
    IJ.saveAsTiff(resultMap, filename + "_suitable-name_map.tif")
    IJ.saveAsTiff(ratio, filename + "_suitable-name_ratio.tif")

    IJ.run("Close All", "")
# simpleSetHiLoDisplayLimits.py
#
# Manually set the Hi and Low display limits for a 16 or 32 bit image
#
#  Modifications
#   Date      Who  Ver                       What
# ----------  --- ------  -------------------------------------------------
# 2017-10-1p  JRM 0.0.01  prototype

from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')

import os
import glob
import time

from ij import IJ, Prefs

gLo = 1800
gHi = 14973

orig = IJ.getImage()
bd = orig.getBitDepth()
if(bd==16):
    IJ.setMinAndMax(orig, gLo, gHi)
elif(bd==32):
    IJ.setMinAndMax(orig, gLo, gHi)

Example #29
0
def previewDialog(imp):
	gd = GenericDialogPlus("FRETENATOR")

	#create a list of the channels in the provided imagePlus
	types = []
	for i in xrange(1, imp.getNChannels()+1):
		types.append(str(i))
	gd.addMessage("""Rowe, J. H, Rizza, A., Jones A. M. (2022) Quantifying phytohormones
	in vivo with FRET biosensors and the FRETENATOR analysis toolset
	Methods in Molecular Biology
	Rowe, JH., Grangé-Guermente, M., Exposito-Rodriguez, M.,Wimalasekera, R., Lenz, M.,
	Shetty, K., Cutler, S., Jones, AM., Next-generation ABACUS biosensors reveal cellular
	ABA dynamics driving root growth at low aerial humidity
	""")
	#user can pick which channel to base the segmentation on
	if len(types)>2:
		gd.addChoice("Channel number to use for segmentation", types, types[2])
		gd.addChoice("Channel number to use for donor", types, types[0])
		gd.addChoice("Channel number to use for acceptor (FRET)", types, types[1])
		gd.addChoice("Channel number to use for acceptor", types, types[2])
		#print('YAY')
	else:
		gd.addChoice("Channel number to use for segmentation", types, types[-1])
		gd.addChoice("Channel number to use for donor", types, types[0])
		gd.addChoice("Channel number to use for acceptor (FRET)", types, types[-2])
		gd.addChoice("Channel number to use for acceptor", types, types[-1])
	
	methods=["Otsu","Default", "Huang", "Intermodes", "IsoData", "IJ_IsoData", "Li", "MaxEntropy", "Mean", "MinError", "Minimum", "Moments", "Percentile", "RenyiEntropy", "Shanbhag", "Triangle", "Yen"]
	gd.addChoice("Autosegmentation method", methods, methods[0])
	intensities=["254", "4094", "65534"]
	gd.addChoice("Max Intensity", intensities, intensities[-1])
	gd.addSlider("Small DoG sigma", 0.5, 10, 0.8, 0.1)
	gd.addSlider("Large DoG sigma", 0.5, 20, 4 ,0.1)
	gd.addCheckbox("TopHat background subtraction? (Slower, but better) ", False)
	gd.addSlider("TopHat sigma", 5, 20, 8 ,0.1)
	gd.setModal(False)
	gd.addCheckbox("Manually set threshold? ", False)
	gd.addSlider("Manual threshold", 10, 65534, 2000, 1)
	dilationOptions=["0", "1", "2","3", "4", "5", "6"]
	gd.addChoice("Dilation?", dilationOptions, "0")
	gd.addCheckbox("Size exclusion of ROI? ", False)
	gd.addSlider("Minimum ROI size", 0, 9999, 20, 1)
	gd.addSlider("Maximum ROI size", 1, 10000, 10000, 1)
	gd.addCheckbox("Create nearest point projection with outlines (SLOW)? ", True)
	gd.addCheckbox("Watershed object splitting? ", True)
	gd.showDialog()

		
	cal = imp.getCalibration()
	pixelAspect=(cal.pixelDepth/cal.pixelWidth)
	
	originalTitle=imp1.getTitle()
	
	choices=gd.getChoices()
	sliders=gd.getSliders()
	checkboxes=gd.getCheckboxes()		
	segmentChannel=int(choices.get(0).getSelectedItem())
	donorChannel=int(choices.get(1).getSelectedItem())
	acceptorChannel=int(choices.get(2).getSelectedItem())
	acceptorChannel2=int(choices.get(3).getSelectedItem())
	thresholdMethod=choices.get(4).getSelectedItem()
	maxIntensity=int(choices.get(5).getSelectedItem())
	gaussianSigma=sliders.get(0).getValue()/10.0
	largeDoGSigma = gd.sliders.get(1).getValue()/10.0
	topHat=gd.checkboxes.get(0).getState()
	topHatSigma=gd.sliders.get(2).getValue()/10.0
	
	manualSegment = gd.checkboxes.get(1).getState()
	manualThreshold=gd.sliders.get(3).getValue()
	dilation=int(choices.get(6).getSelectedItem())
	sizeExclude=gd.checkboxes.get(2).getState()
	minSize = gd.sliders.get(4).getValue()
	maxSize = gd.sliders.get(5).getValue()
	watershed = gd.checkboxes.get(4).getState()
	#print dir(gd.sliders.get(5))
	#print maxSize
	
	segmentChannelOld=segmentChannel
	thresholdMethodOld=thresholdMethod
	maxIntensityOld=maxIntensity
	gaussianSigmaOld=gaussianSigma
	largeDoGSigmaOld= largeDoGSigma
	topHatOld=topHat
	topHatSigmaOld=topHatSigma
	manualSegmentOld= manualSegment
	manualThresholdOld=manualThreshold
	dilationOld=dilation
	sizeExcludeOld=sizeExclude
	minSizeOld=minSize
	maxSizeOld=maxSize
	watershedOld=watershed
	clij2.clear()
	
	segmentImp=extractChannel(imp1, segmentChannel, 0)

	try:
		gfx1=clij2.push(segmentImp)
		gfx2=clij2.create(gfx1)
		gfx3=clij2.create(gfx1)
		gfx4=clij2.create(gfx1)
		gfx5=clij2.create(gfx1)
		gfx7=clij2.create([imp.getWidth(), imp.getHeight()])
	except:	
		try:
		
			Thread.sleep(500)
			print("Succeeded to sending to graphics card on the second time...")
			gfx1=clij2.push(segmentImp)
			gfx2=clij2.create(gfx1)
			gfx3=clij2.create(gfx1)
			gfx4=clij2.create(gfx1)
			gfx5=clij2.create(gfx1)
			gfx7=clij2.create([imp.getWidth(), imp.getHeight()])
		except:
			errorDialog("""Could not send image to graphics card, it may be too large!
		
			Easy solutions: Try	processing as 8-bit, cropping or scaling the image, or
			select a different CLIJ2 GPU.

			This issue is often intermittent, so trying again may also work! 

			See the "Big Images on x graphics cards' notes at:
			https://clij2.github.io/clij2-docs/troubleshooting for more solutions
			
			"""	+ str(clij2.reportMemory()) )


	gfx1,gfx2,gfx3,gfx4,gfx5 = segment(gfx1,gfx2,gfx3,gfx4,gfx5, gaussianSigma, thresholdMethod,maxIntensity, largeDoGSigma, pixelAspect, originalTitle, topHat, topHatSigma , manualSegment, manualThreshold, dilation,sizeExclude, minSize, maxSize, watershed)
	clij2.maximumZProjection(gfx5, gfx7)

	labelPrevImp= clij2.pull(gfx7)
	IJ.setMinAndMax(labelPrevImp, 0,clij2.getMaximumOfAllPixels(gfx7))
	labelPrevImp.setTitle("Preview segmentation")
	labelPrevImp.show()
	
	IJ.run("glasbey_inverted")
	
	while ((not gd.wasCanceled()) and not (gd.wasOKed())):
		

		segmentChannel=int(choices.get(0).getSelectedItem())
		donorChannel=int(choices.get(1).getSelectedItem())
		acceptorChannel=int(choices.get(2).getSelectedItem())
		acceptorChannel2=int(choices.get(3).getSelectedItem())
		thresholdMethod=choices.get(4).getSelectedItem()
		maxIntensity=int(choices.get(5).getSelectedItem())
		gaussianSigma=sliders.get(0).getValue()/10.0
		largeDoGSigma = gd.sliders.get(1).getValue()/10.0
		topHat=gd.checkboxes.get(0).getState()
		topHatSigma=gd.sliders.get(2).getValue()/10.0

		manualSegment = gd.checkboxes.get(1).getState()
		manualThreshold = gd.sliders.get(3).getValue()
		
		dilation=int(choices.get(6).getSelectedItem())
		
		sizeExclude=gd.checkboxes.get(2).getState()
		minSize = gd.sliders.get(4).getValue()
		maxSize = gd.sliders.get(5).getValue()
		watershed = gd.checkboxes.get(4).getState()
			
	
		if (segmentChannelOld !=segmentChannel or
		thresholdMethodOld !=thresholdMethod or
		maxIntensityOld !=maxIntensity or
		gaussianSigmaOld !=gaussianSigma or
		largeDoGSigmaOld != largeDoGSigma or
		topHatOld !=topHat or
		topHatSigmaOld !=topHatSigma or
		manualSegmentOld != manualSegment or
		manualThresholdOld !=manualThreshold or
		dilation != dilationOld or
		sizeExcludeOld!=sizeExclude or
		minSizeOld!=minSize or
		maxSizeOld!=maxSize or
		watershedOld!=watershed
		):
			if minSizeOld!=minSize:
				if minSize>=maxSize:
					maxSize=minSize+1
					gd.sliders.get(5).setValue(maxSize)
			if maxSizeOld!=maxSize:
				if minSize>=maxSize:
					minSize=maxSize-1
					gd.sliders.get(4).setValue(minSize)
			if segmentChannelOld!=segmentChannel:
					clij2.clear()
					segmentImp=extractChannel(imp1, segmentChannel, 0)
					gfx1=clij2.push(segmentImp)
					gfx2=clij2.create(gfx1)
					gfx3=clij2.create(gfx1)
					gfx4=clij2.create(gfx1)
					gfx5=clij2.create(gfx1)
					gfx7=clij2.create([imp.getWidth(), imp.getHeight()])
			gfx1,gfx2,gfx3,gfx4,gfx5 = segment(gfx1,gfx2,gfx3,gfx4,gfx5, gaussianSigma, thresholdMethod,maxIntensity, largeDoGSigma, pixelAspect, originalTitle, topHat,topHatSigma, manualSegment, manualThreshold, dilation,sizeExclude, minSize, maxSize, watershed)
			clij2.maximumZProjection(gfx5, gfx7)
			labelPrevImp.close()
			labelPrevImp= clij2.pull(gfx7)
			IJ.setMinAndMax(labelPrevImp, 0,clij2.getMaximumOfAllPixels(gfx7))
			labelPrevImp.setTitle("Preview segmentation")
			labelPrevImp.show()
			
			IJ.run("glasbey_inverted")
		
		segmentChannelOld=segmentChannel
		thresholdMethodOld=thresholdMethod
		maxIntensityOld=maxIntensity
		gaussianSigmaOld=gaussianSigma
		largeDoGSigmaOld = largeDoGSigma
		topHatOld=topHat
		topHatSigmaOld=topHatSigma
		manualSegmentOld= manualSegment
		manualThresholdOld=manualThreshold
		dilationOld=dilation
		sizeExcludeOld=sizeExclude
		minSizeOld=minSize
		maxSizeOld=maxSize
		watershedOld=watershed
		Thread.sleep(200)
	labelPrevImp.close()
	makeNearProj = gd.checkboxes.get(3).getState()
	return segmentChannel, donorChannel, acceptorChannel, acceptorChannel2, thresholdMethod, maxIntensity, gaussianSigma, largeDoGSigma, topHat, topHatSigma, manualSegment, manualThreshold, makeNearProj, dilation, sizeExclude, minSize, maxSize, watershed
Example #30
0
def overlay_curvatures(imp,
                       curvature_profiles,
                       params,
                       limits=None,
                       annotate=True):
    """Overlay curvature pixels on membrane image"""
    membrane_channel = params.membrane_channel_number
    overlay_base_imp = imp.clone()
    curvature_stack = ImageStack(imp.getWidth(), imp.getHeight())
    for profile in curvature_profiles:
        curvature_stack = generate_curvature_overlays(profile, curvature_stack)
    overlay_imp = ImagePlus("Curvature stack", curvature_stack)
    IJ.run(overlay_imp, params.curvature_overlay_lut_string, "")
    if limits is None:
        flat_list_curv = [c[1] for cs in curvature_profiles for c in cs]
        limits = [min(flat_list_curv),
                  max(flat_list_curv)]
    IJ.setMinAndMax(overlay_imp, limits[0], limits[1])
    raw_overlay = Duplicator().run(overlay_imp)
    if annotate:
        cb_fraction = 0.05
        overlay_imp = add_colorbar(overlay_imp, limits, cb_fraction)
    IJ.run(overlay_imp, "RGB Color", "")
    w = overlay_imp.getWidth()
    h = overlay_imp.getHeight()
    overlaid_stack = ImageStack(w, h)
    for fridx in range(1, curvature_stack.getSize() + 1):
        raw_idx = overlay_base_imp.getStackIndex(membrane_channel, 1, fridx)
        ip = overlay_base_imp.getStack().getProcessor(raw_idx).convertToRGB()
        pix = overlay_imp.getStack().getProcessor(fridx).getPixels()
        base_pix = ip.getPixels()
        curv = [c for ((x, y), c) in curvature_profiles[fridx - 1]]
        start_idx = next((i for i, x in enumerate(curv) if x), None)
        end_idx = next(
            (len(curv) - i for i, x in enumerate(reversed(curv)) if x), None)
        for ((x, y), c) in curvature_profiles[fridx - 1][start_idx:end_idx]:
            # ensure that no rounding issues cause pixels to fall outside image...
            if x > (w - 1):
                x = w - 1
            if y > (h - 1):
                y = h - 1
            if x < 0:
                x = 0
            if y < 0:
                y = 0
            if params.filter_negative_curvatures:
                if (c > 0):
                    base_pix[int(round(y)) * w +
                             int(round(x))] = pix[int(round(y)) * w +
                                                  int(round(x))]
            else:
                base_pix[int(round(y)) * w +
                         int(round(x))] = pix[int(round(y)) * w +
                                              int(round(x))]
        if annotate:
            for x in range(w - int(w * cb_fraction), w):
                for y in range(0, h):
                    base_pix[int(round(y)) * w +
                             int(round(x))] = pix[int(round(y)) * w +
                                                  int(round(x))]
        overlaid_stack.addSlice(ip)
    out_imp = ImagePlus("Overlaid curvatures", overlaid_stack)
    if annotate:
        out_imp = generate_limit_labels(out_imp, limits, cb_fraction, params)
    FileSaver(raw_overlay).saveAsTiff(
        os.path.join(params.output_path, "raw curvature.tif"))
    return out_imp, raw_overlay
	glVal[i] = i
	cts = hist[i]
	if(cts > maxCts):
		maxCts = cts
	totCts += cts
	glCum[i] = float(totCts)

# print(totCts)

for i in range(0, nBins):
	glCum[i] /= totCts

frac = 1.0
n = 1
thr = 0
while(frac >= factor):
	thr = nBins-n
	frac = glCum[thr]
	n += 1

print(thr)

IJ.setMinAndMax(imp, 0, thr)


	
	
	
	

import glob, os

__author__ = 'Nichole Wespe'

imp = IJ.getImage()
directory = IJ.getDirectory("image")
f = str(imp.getTitle())
date, rows, columns, time_tif = str.split(f)  # deconstruct filename
time = time_tif.replace('tif','jpg')  # need to remove .tif from time
row_IDs = list(6*rows[0] + 6*rows[1])
column_IDs = [str(i) for i in 2*(range(int(columns[0]), int(columns[0]) + 6))]
zipped = zip(row_IDs, column_IDs)
sample_names = ["".join(values) for values in zipped]


IJ.setMinAndMax(1900, 11717) # adjust brightness and contrast
IJ.run("Apply LUT")
IJ.makeRectangle(200, 50, 730, 950) # initialize selection
dial = WaitForUserDialog("Adjust selection area")
dial.show() # ask user to place selection appropriately
IJ.run("Crop")
adjDir = os.path.join(directory, "Adjusted")
if not os.path.exists(adjDir):
	os.mkdir(adjDir)
adjImage = os.path.join(adjDir, "Adj " + f)
IJ.saveAs("Jpeg", adjImage)

## make ROI list
w = 130
h = 480
x_vals = 2*[10, 128, 246, 360, 478, 596]
Example #33
0
def process(dirIn, dirOut, expName, ps, pe, ts, te):

	
	jobid = commands.getoutput("echo $PBS_JOBID").split('.')[0]
	jobid = jobid.replace("[","_").replace("]","")  # because the jobids look like 2356385[1] which causes problems
	print "job id: "+jobid
	jobdir = os.path.join("/tmp",str(jobid)+"_fiji")
	print "job dir: "+jobdir
	
	for p in range(ps,pe+1):
		
		
		pID = str(p);
		
		for t in range(ts,te+1):
			
			print "TIMEPOINT STARTING ***************"
				
			tID = "t"+str(t);
			print "time-point: "+tID;

			if os.path.isdir(jobdir):
				print "removing "+jobdir
				shutil.rmtree(jobdir)                
			print "creating "+jobdir
			os.mkdir(jobdir)
					
		
			if stitching:
				
				fileOut = "rescaled_flipped_";
					
				for z in range(zs,ze+1):
				
					zID = "z"+str(z);
					print "z-plane: "+zID;
					
					if bandpass:
		
						IJ.log("bandpass....")
				
						# load all images from same time point and same z-position
						fileID = expName+pID+"_b0"+tID+zID+"m.*";
						IJ.log("opening images: "+os.path.join(dirIn,fileID))
						IJ.run("Image Sequence...", "open=["+dirIn+"] starting=1 increment=1 scale=100 file=[] or=["+fileID+"] sort");
						#selectWindow("im-2012-0007_Position35.tif_Files");
						imp = IJ.getImage();
						#imp.show();
						
						
						imp.setTitle("Stack");
						
						# illumination correction
						IJ.log("computing FFT...");
						# run("Flip Horizontally", "stack");
						impFFT = Duplicator().run(imp);
						for i in range(1, impFFT.getNSlices()+1):
							print "FFT of slice "+str(i)
							impFFT.setSlice(i)
							IJ.run(impFFT, "Bandpass Filter...", "filter_large=10000 filter_small=200 suppress=None tolerance=5 ");
						#impFFT.show()
						
						#stats = imp.getStatistics(Measurements.MEAN)
						#IJ.log("stats.mean = "+str(stats.mean)); # this is only the mean of one slice...is this a problem?
						
						print "dividing image stack by FFT stack...";
						ic = ImageCalculator()
						impCorr = ic.run("Divide create 32-bit stack", imp, impFFT);
						#impCorr.show()

						def computeMean(pixels):
  							return sum(pixels) / float(len(pixels))
						
						print "multiplying each image by 128/mean for going back to 8 bit space..."
						stack = impCorr.getStack()
						for i in range(1, impCorr.getNSlices()+1):
							ip = stack.getProcessor(i).convertToFloat()
					 		mean = computeMean(ip.getPixels())
					 		print "multiplying slice "+str(i)+" by "+str(float(128/mean))
	    						ip.multiply(float(128/mean))
	    						
	    					
						IJ.log("converting from 32-bit to 8-bit...")
						IJ.setMinAndMax(impCorr, 0, 255);
						IJ.run(impCorr,"8-bit","");
						#IJ.saveAs(impCorr, "Tiff", "/Users/tischi/Documents/processed.tif");
						#ff
						#impCorr.show()
						
						# save images
						IJ.log("saving bandpass corrected image sequence: "+os.path.join(jobdir,fileOut))
						IJ.run(impCorr, "Image Sequence... ", "format=TIFF name=["+fileOut+"] start=1 digits=4 save=["+jobdir+"]");
						if check:
							IJ.run(impCorr, "Image Sequence... ", "format=TIFF name=["+fileOut+"] start=1 digits=4 save=["+dirOut+"]");
						#impCorr.close(); imp.close(); impFFT.hide();  
						
	
					# stitching
					IJ.log("STITCHING START **********")
					layoutFile = copyStitchingLayoutFile(dirIn,expName,jobdir,ps)
					###layoutFile = makeStitchingLayoutFile(jobdir)
					createPreview = 0
					computeOverlap = 0
					fusion_method="Linear Blending"
					handleRGB = "Red, Green and Blue"
					showImage = 0
					#fusion=1 regression=0.30 max/avg=2.50 absolute=3.50"
					st = Stitch_Image_Collection() 
					st.alpha = 1
					IJ.log("layout file: "+str(layoutFile))
					impStitched = st.work(layoutFile, createPreview, computeOverlap,  fusion_method,  handleRGB,  showImage) 
					stitchedFile = os.path.join(jobdir,tID+zID+"_stitched.tif");
					#impStitched.show()
					IJ.saveAs(impStitched,"Tiff", stitchedFile);
					if check: 
						print os.path.join(dirOut,tID+zID+"_stitched.tif")
						stitchedFile = os.path.join(dirOut,tID+zID+"_stitched.tif");
						IJ.saveAs(impStitched,"Tiff", stitchedFile);
					
					IJ.log("STITCHING END **********")
					
			
			if combine_z:
			
				IJ.log("combine z.....")	
				
				#########
				IJ.log("load stitched images into a stack...")
				for z in range(zs,ze+1):
					zID = "z"+str(z);	
					stitchedFile = os.path.join(jobdir,tID+zID+"_stitched.tif");
					IJ.log("opening "+stitchedFile)
					imp = IJ.openImage(stitchedFile)
					if z==zs:
						stack = ImageStack(imp.width,imp.height)
					stack.addSlice(imp.getProcessor())
				imp = ImagePlus("stack", stack)
				#imp.show()
				########
				
				########
				IJ.log("cropping...")
				imp.setRoi(xs, ys, xe, ye);
				IJ.run(imp, "Crop", "");	
				#imp.show()
				########


				# the following normalisation should not be necessary, because they are already all 128/mean normalised
				#IJ.log("-- normalise intensity of all slices...")
				#stats = imp.getStatistics(Measurements.MEAN)
				#IJ.log("stats.mean = "+str(stats.mean)); # this is only the mean of one slice...is this a problem?		
				#stack = imp.getStack()
				#for i in range(1, impFFT.getNSlices()+1):
			 	#	ip = stack.getProcessor(i).convertToFloat()
	    		#	ip.multiply(128/stats.mean)
	    	    #		#stack.setSlice(stack.getSliceLabel(i), ip)
						
				#run("Set Slice...", "slice="+1);
		        	#run("Set Measurements...", "  mean redirect=None decimal=9");
				#run("Select None");
				#setBatchMode(true);
				#setMinAndMax(0, 255); run("32-bit");				
				#for(l=0; l<nSlices+1; l++) {
				##	run("Select All");
				#	run("Clear Results");
				#	run("Measure");
				#	picsum=getResult("Mean",0);
				#	//if(l==0){picsum1=picsum;}
				#	//int_ratio=picsum1/picsum;
				#	int_ratio=128/picsum;
				#	run("Select None");
				#	IJ.log("ratio ="+int_ratio);
				#	run("Multiply...", "slice value="+int_ratio);
				#	run("Next Slice [>]");
				#}
				#setBatchMode(false);
			
				# stop here and try by hand
				#...
				#dfgfd
				
				#//stack-reg
				#//IJ.log("register xy...")
				#//run("StackReg", "transformation=Translation");
				
				#// project into 1 plane ....
				#// run("Extended Depth of Field (Easy mode)...");
				#//run("Z Project...", "start=["+1+"] stop=["+ze+"] projection=[Standard Deviation]");
		
	
				doEDF = True
				if doEDF:
					IJ.log("EDF: start...")
					parameters = Parameters()
					parameters.setQualitySettings(1)
					parameters.setTopologySettings(0)
					parameters.show3dView = False 
					parameters.showTopology = False
					edfh = ExtendedDepthOfFieldHeadless(imp, parameters)
					imp = edfh.processHeadless()
					IJ.log("EDF: done.")
					#imp.show()
								
					IJ.log("EDF: converting from 32-bit to 8-bit...")
					IJ.setMinAndMax(imp, 0, 255);
					IJ.run(imp,"8-bit","");
							
					edfFile = os.path.join(dirOut,expName+pID+"-"+tID+"_EDOF_noTimeNorm.tif");
					IJ.log("EDF save: "+edfFile)			
					IJ.saveAs(imp,"Tiff", edfFile);
					IJ.log("EDF save: done.")
					#close(); // projection
					#close(); // stack

				print "TIMEPOINT FINISHED ***************"
				if os.path.isdir(jobdir):
					print "removing "+jobdir
					shutil.rmtree(jobdir)                
Example #34
0
imp.setTitle("current")

# IJ.run executes commands from the macro recorder
IJ.run(
    "Scale...",
    "x=.5 y=.5 z=1.0 width=128 height=128 depth=930 interpolation=Bilinear average process create"
)
imp.close()
IJ.selectWindow("current-1")
IJ.run("Z Project...", "projection=[Average Intensity]")

# Note the new imports above, WindowManager and ImageCalculator
# ic.run executes commands within image calculator; wm.getImage selects the image using WindowsManager
imp = ic.run("Subtract create 32-bit stack", wm.getImage("current-1"),
             wm.getImage("AVG_current-1"))
imp.show()
imp = ic.run("Divide create 32-bit stack", wm.getImage("Result of current-1"),
             wm.getImage("AVG_current-1"))
imp.show()
IJ.selectWindow("Result of Result of current-1")

# adjust the Brightness/Contrast
IJ.setMinAndMax(-0.0200, 0.2000)

# this is the Lookup Tables step
IJ.run("Aselfmade3")

# IJ.saveAs has 3 arguments: (image, file type, file path)
IJ.saveAs(IJ.getImage(), "Tiff", out_folder + the_file + '-processed')
IJ.run("Close All", "")
source_path = "Correspondence_ZBrain/ZBtoEM/ZBdata_warped/"
reformat_path = "Correspondence_ZBrain/ZBtoEM/ZBdata_imseq/"

for filename in os.listdir(source_path):
  if filename.endswith(".tif"):
    print "Processing file:", filename

    ## Open image from file
    imp = IJ.openImage(os.path.join(source_path, filename))
    if imp is None:
      print "Could not open image from file:", filename
      continue
    ## Set appropriate resolution (matching BigWarp settings here)
    IJ.run(imp, "Properties...", "channels=1 slices=811 frames=1 unit=um pixel_width=0.6 pixel_height=0.6 voxel_depth=1.2")
    ## Make sure full 16-bit or 8-bit range is used
    IJ.setMinAndMax(imp, 0, 65535) # ZBrain/ZBB data stacks
    imp.setDefault16bitRange(16)
    #IJ.setMinAndMax(imp, 0, 255); # ZBrain masks/labels
    #imp.setDefault16bitRange(8);
    ## Convert to 8-bit (optional, if desired)
    IJ.run(imp, "8-bit", "")
    ## If converted, make sure full 8-bit range is used before saving
    IJ.setMinAndMax(imp, 0, 255);
    imp.setDefault16bitRange(8);
    
    fs = FileSaver(imp)
    if not path.exists(reformat_path):
      os.makedirs(reformat_path)
    if path.exists(reformat_path) and path.isdir(reformat_path):
      dirpath = path.join(reformat_path, string.replace(filename, '_Warped.tif', ''))
      if not path.exists(dirpath):