示例#1
0
    def dog_detection(overlay,img, imp, cal):

                 # Create a variable of the correct type (UnsignedByteType) for the value-extended view
				 zero = img.randomAccess().get().createVariable()
				
				 # Run the difference of Gaussian
				 cell = 8.0 # microns in diameter
				 min_peak = 2.0 # min intensity for a peak to be considered
				 dog = DogDetection(Views.extendValue(img, zero), img,
				                   [cal.pixelWidth, cal.pixelHeight,cal.pixelDepth],
				                   cell / 2, cell,
				                   DogDetection.ExtremaType.MINIMA, 
				                   min_peak, False,
				                   DoubleType())
				
				 peaks = dog.getPeaks()
				 roi = OvalRoi(0, 0, cell/cal.pixelWidth, cell/cal.pixelHeight)  
				 print ('Number of cells = ', len(peaks))
			 	 p = zeros(img.numDimensions(), 'i')  
			 	
				 boundRect = imp.getRoi()
				 for peak in peaks:  
				    # Read peak coordinates into an array of integers  XYZ location of spots
				    peak.localize(p)  
				    print(p)
				    if(boundRect is not None and boundRect.contains(p[0], p[1])):
						    oval = OvalRoi(p[0], p[1],cell/cal.pixelWidth,  cell/cal.pixelHeight)
						    oval.setColor(Color.RED)
						    overlay.add(oval) 
示例#2
0
def circle_roi(cs, r, color):
    # type: (CellStack, int, Color) -> None
    """
Draw a circle roi with center and radius of the cell
    """
    d = r * 2
    x, y = cs.center[0] - r, cs.center[1] - r
    roi = OvalRoi(x, y, d, d)
    roi.setColor(color)
    cs.setRoi(roi)
示例#3
0
def pre_process_images(image_input, timepoints):
    #correct drift
    IJ.run(
        image_input, "Properties...",
        "channels=2 slices=1 frames=" + str(timepoints) +
        " unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000"
    )
    corrected_img = run_3d_drift_correct(image_input)

    #split channels
    red_corrected_img, phase_corrected_img = ChannelSplitter.split(
        corrected_img)

    #get image dimensions, set ROI remove part of flouresncent ring
    x_size = ImagePlus.getDimensions(red_corrected_img)[0]
    y_size = ImagePlus.getDimensions(red_corrected_img)[1]
    x_start = 0
    y_start = 0

    red_corrected_img.setRoi(OvalRoi(x_start, y_start, x_size, y_size))

    IJ.run(red_corrected_img, "Make Inverse", "")
    IJ.setForegroundColor(0, 0, 0)
    IJ.run(red_corrected_img, "Fill", "stack")
    red_corrected_img.killRoi()

    #correcting background
    IJ.run(
        red_corrected_img, "Properties...",
        "channels=1 slices=" + str(timepoints) +
        " frames=1 unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000"
    )
    #red_corrected_background_img = apply_rollingball(red_corrected_img, 7.0, False, False,False, False, False)

    testset = basic.BaSiCSettings()

    testset.imp = red_corrected_img
    testset.myShadingEstimationChoice = "Estimate shading profiles"
    testset.myShadingModelChoice = "Estimate both flat-field and dark-field"
    testset.myParameterChoice = "Manual"
    testset.lambda_flat = 2.0
    testset.lambda_dark = 2.0
    testset.myDriftChoice = "Replace with zero"
    testset.myCorrectionChoice = "Compute shading and correct images"

    test = basic.BaSiC(testset)
    test.run()
    red_corrected_background_img = test.getCorrectedImage()

    #change properties back and perform bleach correction
    IJ.run(
        red_corrected_background_img, "Properties...",
        "channels=1 slices=1 frames=" + str(timepoints) +
        " unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000"
    )
    red_corrected_background_img_dup = red_corrected_background_img.duplicate()
    corrected_bleach = BleachCorrection_MH(red_corrected_background_img)
    corrected_bleach.doCorrection()

    return (red_corrected_background_img_dup, red_corrected_background_img)
示例#4
0
 def drawMinima(self):
     IJ.run("Remove Overlay", "")
     self.calculateSubtreeMinima()
     overlay = Overlay()
     for child in self.children:
         for spot in child.minima:
             roi = OvalRoi(spot.x - spot.radius, spot.y - spot.radius,
                           2 * spot.radius, 2 * spot.radius)
             overlay.add(roi)
     IJ.getImage().setOverlay(overlay)
def drawMinima(minima):
	rt = ResultsTable.getResultsTable()
	X = rt.getColumn(ResultsTable.X_CENTROID)
	Y = rt.getColumn(ResultsTable.Y_CENTROID)
	D = rt.getColumn(ResultsTable.FERET)	
	overlay = Overlay()
	for minimum in minima:
		index = minima[minimum]
	 	r = float(D[index]) / 2
		roi = OvalRoi(float(X[index])-r, float(Y[index])-r, float(D[index]), float(D[index]))	
		overlay.add(roi)
	IJ.getImage().setOverlay(overlay)
示例#6
0
def createROI(xy_coord, diameter):
    imp = WindowManager.getCurrentImage()
    pixelWidth = imp.getCalibration().pixelWidth
    pixelHeight = imp.getCalibration().pixelHeight
    x_diameter = diameter / pixelWidth
    y_diameter = diameter / pixelHeight
    x_coord = xy_coord[0] / pixelWidth - (0.5 * x_diameter)
    y_coord = xy_coord[1] / pixelHeight - (0.5 * y_diameter)

    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()

    roi = OvalRoi(x_coord, y_coord, x_diameter, y_diameter)
    rm.addRoi(roi)
示例#7
0
 def mousePressed(self, keyEvent):
     global iROI, xlist, ylist, zlist
     iROI += 1
     canv = imp.getCanvas()
     p = canv.getCursorLoc()
     z = imp.getCurrentSlice()
     nCh = imp.getNChannels()
     if nCh > 1:
         z = (z + 1) / nCh
     roi = OvalRoi(p.x - radius, p.y - radius, radius * 2, radius * 2)
     roi.setName('z' + str(z) + 'cell' + str(iROI))
     roi.setPosition(z)
     xlist.append(p.x)
     ylist.append(p.y)
     zlist.append(z)
     imp.setRoi(roi)
     manager.addRoi(roi)
     manager.runCommand('Draw')
示例#8
0
                    if DoPearson_per_Spot:
                        ort.addValue("Pearson_Spot_C1", str(pearsons_spot1))
                        ort.addValue("Pearson_Spot_C2", str(pearsons_spot2))
                    if (distance_in_um > Filter_Distance_Min) and (
                            distance_in_um < Filter_Distance_Max):
                        HasFilteredSpots = True

    if points_C1 != []:
        for item1 in points_C1:
            item1counter = item1counter + 1
            pixels_Spots1_C1 = []
            pixels_Spots1_C2 = []
            imp.setC(1)
            roi1 = Roi(item1[0] - 2, item1[1] - 2, 5, 5)
            Intensity_ROI = OvalRoi(item1[0] - (Intensity_Roi_Size / 2),
                                    item1[1] - (Intensity_Roi_Size / 2),
                                    Intensity_Roi_Size, Intensity_Roi_Size)
            if DoPearson_per_Spot:
                imp.setRoi(roi1)
                pixels_Spots1_C1 = pixel_values_rect(roi1)
                imp.setC(2)
                imp.setRoi(roi1)
                pixels_Spots1_C2 = pixel_values_rect(roi1)
                pearsons_spot1 = (pearson_def(pixels_Spots1_C1,
                                              pixels_Spots1_C2))
            if Measure_Spot_Intensity:
                imp.setC(1)
                imp.setRoi(Intensity_ROI)
                stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA
                                          | Measurements.FERET
                                          | Measurements.CENTROID)
示例#9
0
    movietime.append(imp.getT())
    timer = timer + 1
 #  proi =  IJ.getImage().getRoi()
    px = roi.getXCoordinates()
    py = roi.getYCoordinates()
    bounds = roi.getBounds()
    #print bounds
    coord = (bounds.x, bounds.y)
    XYCoordinates.append(coord)
    if roi5 ==0:
        Distance.append(0.0)
    else:
        Distance.append(round(dist(Lastcoordinates, coord),3))    
    Lastcoordinates = coord
    #print coord
    roi2 = OvalRoi(coord[0]-(roisize/2), coord[1]-roisize/2, roisize,roisize)
    imp.setC(1)
    imp.setRoi(roi2)
    stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA | Measurements.FERET | Measurements.CENTROID)
    MeanChannel1.append(stats.mean)
    imp.setC(2)
    stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA | Measurements.FERET | Measurements.CENTROID)
    MeanChannel2.append(stats.mean)
    if channelnumber > 2:
       imp.setC(3)
       stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA | Measurements.FERET | Measurements.CENTROID)
       MeanChannel3.append(stats.mean)
       threecolour = True
    roi3 = Roi(coord[0]-(GalleryROI/2), coord[1]-GalleryROI/2, GalleryROI,GalleryROI)
    imp.setC(1)
    imp.setRoi(roi3)
示例#10
0
from ij import IJ, ImagePlus, WindowManager
from ij.process import FloatProcessor
from ij.gui import OvalRoi, Roi
from ij.plugin.filter import GaussianBlur
from java.util import Random

w, h = 128, 128
fp = FloatProcessor(w, h)
imp = ImagePlus("synth training", fp)

fp.setColor(150)  # background
fp.fill()

# neurites
rois = [
    OvalRoi(w / 2 - w / 4, h / 2 - h / 4, w / 4,
            h / 2),  # stretched vertically
    OvalRoi(w / 2, h / 2 - h / 8, w / 4, h / 4),
    OvalRoi(w / 2 - w / 18, h / 2 + h / 10, w / 6, h / 4),
    OvalRoi(w / 2 - w / 18, h / 8 + h / 16, w / 3, h / 5)
]

fp.setColor(50)  # membrane
fp.setLineWidth(3)

for roi in rois:
    fp.draw(roi)

fp.setColor(90)  # oblique membrane
fp.setLineWidth(5)
roi_oblique = OvalRoi(w / 2 + w / 8, h / 2 + h / 8, w / 4, h / 4)
fp.draw(roi_oblique)
from ij import IJ
from ij.gui import OvalRoi
from ij.plugin.frame import RoiManager

imp = IJ.getImage()
rm = RoiManager()  # instantiate manager # throws exception if it doesn't exist
#rm = RoiManager.getInstance() # if manager exists

roi = OvalRoi(75, 75, 50, 50)
# define and add ROI
imp.setRoi(roi)  # make active on image
rm.addRoi(roi)  # add
rm.select(0)  # select the zeroth ROI and rename it
rm.runCommand("Rename", "roi")
            tempvar = [j - i for i, j in zip(var[:(idx - 4)], var[4:])]
            if tempvar == []:
                continue
            idx = tempvar.index(max(tempvar))
            start = frame[0]
            metaphase = frame[idx + 3]

            if (division - start > 15 and division - start < 100):
                if start > 0:
                    for spot in sortedTrack:

                        # Fetch spot features directly from spot.
                        x = spot.getFeature('POSITION_X')
                        y = spot.getFeature('POSITION_Y')
                        t = spot.getFeature('FRAME')
                        roi2 = OvalRoi(x / dx - (6 * dx), y / dy - (6 * dy),
                                       12, 12)
                        roi2.setPosition(int(t))
                        rm.add(imp, roi2, nextRoi)
                        nextRoi = nextRoi + 1
                    resultstable.setValue("IMAGE_NAME", trackrowNumber,
                                          filename)
                    resultstable.setValue("TRACK_ID", trackrowNumber, id)
                    resultstable.setValue("START", trackrowNumber, start)
                    resultstable.setValue("METAPHASE", trackrowNumber,
                                          metaphase)
                    resultstable.setValue("END", trackrowNumber, division)

                    trackrowNumber = trackrowNumber + 1
#                    plot = Plot(str(id), "slice", "mean", frame, var)
#                    plot.show()
#                    break
    # function
    ER_points(all_x, all_y, overlay, ER_measurements)

    # set more variables
    ER = []

    # merges the x and y lists such that x,y are  pairs in a list
    x_y = list(zip(all_x, all_y))
    # loops through x,y coordinate pairs, draw a circle and measures the average intensity.
    for x, y in x_y:
        x = (int(x))
        y = (int(y))
        new_x = int(x) - radius
        new_y = int(y) - radius
        imp = IJ.getImage()
        roi = OvalRoi(new_x, new_y, radius*2, radius*2)
        imp.setRoi(roi)
        ER_mean = (selection_mean())
        ER.append(ER_mean)
        IJ.run(imp, "Draw", "slice")

    try:
        with open(Quant) as infile:
            reader = csv.reader(infile)
            row_count = sum(1 for row in reader)
            cell_number = row_count
    except:
        cell_number = 1

    gd = GenericDialog("Type cell number")
    gd.addStringField("Cell number", str(cell_number))
示例#14
0
cell_channel_2 = []
r0 = []
for x, y in x_y:
    x = int(x)
    y = int(y)
    new_x = int(x) - radius
    new_y = int(y) - radius
    cell_channel_1 = []
    cell_channel_2 = []
    for channel in channel_list:
        imp.setC(channel)
        for j in range(timepoint_list[0], timepoint_list[r_end]):
            imp.setT(j)
            imp = IJ.getImage()
            roi = OvalRoi(new_x, new_y, radius * 2, radius * 2)
            imp.setRoi(roi)
            cell_mean = (selection_mean())
            if channel == 1:
                cell_channel_1.append(cell_mean)
            if channel == 2:
                cell_channel_2.append(cell_mean)
            if len(cell_channel_1) == r_end:
                Tch1_8 = [
                    cell_channel_1[i] - bckc1[i]
                    for i in range(len(cell_channel_1))
                ]
                cell_channel_1 = []
            if len(cell_channel_2) == r_end:
                Tch2_8 = [
                    cell_channel_2[i] - bckc2[i]
#libs for csv reading
import csv
import os
#libs nec for ROI handling
from ij.plugin.frame import RoiManager
from ij.gui import OvalRoi
RoiManager()
b = RoiManager.getInstance()
#x = OvalRoi(322, 144, 108, 104)
#b.addRoi(x)
print(os.getcwd())

fn = 'C:/Users/tomjm/Documents/CellDetect/src/data31_postprocessed/data31_ROIsManual.csv'
# set radius
r=5

with open(fn) as csvfile:
	readCSV = csv.reader(csvfile,delimiter=',')
	for row in readCSV:
		xc = int(row[0])+10
		yc = int(row[1])+10
		
		x = OvalRoi(xc-r, yc-r, 2*r, 2*r)
		b.addRoi(x)
示例#16
0
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# #L%
###
# Create new ROI programmatically
from ij import IJ
from ij.gui import OvalRoi, Roi
# Get current ImagePlus
image = IJ.getImage()
# Enter ROI coordinates
width = 50
height = 50
x_ROI = 100  # ROI center
y_ROI = 100  # ROI center
oval = False  # Set to True to get an oval ROI
# Make it
x1 = int(x_ROI - (width / 2))
y1 = int(y_ROI - (height / 2))
if oval:
    roi = OvalRoi(x1, y1, width, height)
else:
    roi = Roi(x1, y1, width, height)
image.setRoi(roi)
示例#17
0
zero = img.randomAccess().get().createVariable()

# Run the difference of Gaussian
cell = 30.0  # microns in diameter
min_peak = 10.0  # min intensity for a peak to be considered
dog = DogDetection(
    Views.extendValue(img, zero),
    img,
    [cal.pixelWidth, cal.pixelHeight],
    cell / 2,
    cell,
    DogDetection.ExtremaType.MAXIMA,  #MAXIMA
    min_peak,
    False,
    DoubleType())

peaks = dog.getPeaks()
roi = OvalRoi(0, 0, cell / cal.pixelWidth, cell / cal.pixelHeight)
print('Number of cells = ', len(peaks))
p = zeros(img.numDimensions(), 'i')
overlay = Overlay()
imp.setOverlay(overlay)
for peak in peaks:
    # Read peak coordinates into an array of integers
    peak.localize(p)
    if (boundRect.contains(p[0], p[1])):
        oval = OvalRoi(p[0], p[1], cell / cal.pixelWidth,
                       cell / cal.pixelHeight)
        oval.setColor(Color.RED)
        overlay.add(oval)
示例#18
0
def tethered_cell(image_path, frame_number=100, frame_rate=100.0, CCW=1):
    """
    parameter setting; frame rate (frame/sec)

    CCW = 1 : the motor rotation direction and the cell rotation direction on the image are same
    CCW = -1: the motor rotation direction and the cell rotation direction on the image are different
    """
    opener = Opener()
    imp = opener.openImage(image_path)
    image_slice_number = imp.getNSlices()
    rm = RoiManager().getInstance()

    if image_slice_number < frame_number: # too short movie
        IJ.log('Number of frame of the movie is fewer than the number of frame that you selected')
        return False
    # create result directory
    result_path = image_path + '_tethered_cell_result'
    if os.path.lexists(result_path) is False:
        os.mkdir(result_path)

    #z projection; standard deviation, tethered cell shorws circle
    IJ.run(imp, 'Subtract Background...', 'rolling=5 light stack')
    IJ.run(imp, 'Median...', 'radius=2 stack')
    IJ.run(imp, 'Z Project...', 'stop=500 projection=[Standard Deviation]')
    zimp = IJ.getImage()
    IJ.saveAs(zimp, 'bmp', os.path.join(result_path,'STD_DEV.bmp'))
    # pick up tethered cell
    IJ.setAutoThreshold(zimp, 'MaxEntropy dark')
    IJ.run(zimp, 'Convert to Mask', '')
    IJ.run('Set Measurements...', "area centroid bounding shape feret's limit redirect=None decimal=3")
    IJ.run(zimp, 'Analyze Particles...', 'size=30-Infinity circularity=0.88-1.00 show=Nothing display exclude clear include')
    zrt = ResultsTable.getResultsTable()
    IJ.saveAs('Results', os.path.join(result_path,'RoiInfo.csv'))

    #tcX and tcY are xy coordinates of tethered cell, tcdia is outer diameter of rotating tethered cell
    #add ROI into stack image
    for i in range(zrt.getCounter()):
        tcX = zrt.getValue('X', i)
        tcY = zrt.getValue('Y', i)
        tcdia = zrt.getValue('Feret', i)
        rm.add(imp, OvalRoi(tcX - tcdia/2.0, tcY - tcdia/2.0, tcdia + 1, tcdia + 1), i)

    #calculate rotation speed by ellipse fitting
    IJ.setAutoThreshold(imp, 'Li')
    for roi_number in range(rm.getCount()):
        t = []
        XM = []
        YM = []
        theta = []
        rotation_speed = []
        area = []
        imp.setRoi(rm.getRoi(roi_number))
        cropped_imp = Duplicator().run(imp)
        IJ.run('Set Measurements...', 'area mean center fit limit redirect=None decimal=3')
        rm.select(roi_number)
        rt = rm.multiMeasure(imp)

        # check cell is present while analysis. Don't a cell gose anywhare?
        for i in range(frame_number):
            area.append(rt.getValue('Area1', i))
        if 0 in area:
            continue

        for i in range(frame_number):
            t.append((1/frame_rate)*i)
            XM.append(rt.getValue('XM1', i))
            YM.append(rt.getValue('YM1', i))
            theta.append(rt.getValue('Angle1', i)/180.0*math.pi)  # convert to radian
            if i == 0:
                rotation_speed.append(0)
            else:
                # phase treatment, theta should be -pi ~ pi
                temp_rotation_speed = [theta[i] - theta[i-1],
                          theta[i] - theta[i-1] + math.pi,
                          theta[i] - theta[i-1] - math.pi,
                          theta[i] - theta[i-1] + 2*math.pi,
                          theta[i] - theta[i-1] - 2*math.pi]
                temp_rotation_speed = sorted(temp_rotation_speed, key = lambda x :abs(x) )[0]
                rotation_speed.append(CCW*temp_rotation_speed/(2.0*math.pi)*frame_rate)

        # write csv
        # earch columns indicate 1:index, 2:time(sec), 3:X-coordinate of center of mass(pixel), 4:Y-coordinate of center of mass (pixel), 5:Angle(Radian), 6:Rotation Speed(Hz)
        with open(os.path.join(result_path,'Roi' + str(roi_number) + '.csv'), 'w') as f:
            writer = csv.writer(f)
            writer.writerow(['Index', 'time(s)', 'X', 'Y', 'Angle(rad)', 'Rotation Speed(Hz)'])
            for i in range(len(t)):
                writer.writerow([i, t[i], XM[i], YM[i], theta[i], rotation_speed[i]])
        # plot x-y, t-x, t-y, t-rotation speed, save plot as bmp
        plotRotation(roi_number, result_path, t, XM, YM, rotation_speed)
        IJ.saveAs(cropped_imp, 'tiff', os.path.join(result_path,'Roi' + str(roi_number) + '.tiff'))
        rt.reset()

    # get analysis date and time
    dt = datetime.datetime.today()
    dtstr = dt.strftime('%Y-%m-%d %H:%M:%S')

    # wtite analysis setting
    with open(os.path.join(result_path,'analysis_setting.csv'), 'w') as f:
        writer = csv.writer(f)
        writer.writerow(['Analysis Date','frame number','frame rate','CCW direction', 'Method','Auto threshold', 'Subtruct Background', 'Median filter'])
        writer.writerow([dtstr, frame_number, frame_rate, CCW, 'Ellipse', 'Li', '5.0', '2'])

    # save roi
    if rm.getCount() != 0:
        rm.runCommand('Save', os.path.join(result_path, 'Roi.zip'))

    zimp.close()
    imp.close()
    rm.close()
    zrt.reset()
示例#19
0
def track_cells(folder_w, filename, imp, correction):
    #imp = IJ.openImage(os.path.join(folder,filename))
    #imp.show()

    #get image dimensions, set ROI remove part of flouresncent ring
    x_size = ImagePlus.getDimensions(imp)[0]
    y_size = ImagePlus.getDimensions(imp)[1]
    x_start = 0
    y_start = 0
    #calculate alternative ROI
    if crop_ring:
        x_start = 170 / 2
        y_start = 170 / 2
        x_size = x_size - 170
        y_size = y_size - 170
    print(
        str(x_start) + ", " + str(y_start) + ", " + str(x_size) + ", " +
        str(y_size))
    imp.setRoi(OvalRoi(x_start, y_start, x_size, y_size))
    #imp_dup = imp.duplicate()
    #imp_dup.show()
    #red_corrected_img.show()

    IJ.run(imp, "Make Inverse", "")
    IJ.setForegroundColor(0, 0, 0)
    IJ.run(imp, "Fill", "stack")
    imp.killRoi()

    #imp.show()
    #sys.exit()

    #img_filename = filename+"_corrected_red_stack.tif"
    #folder_filename= os.path.join(well_folder,img_filename)
    #IJ.save(imp, folder_filename)

    #----------------------------
    # Create the model object now
    #----------------------------

    # Some of the parameters we configure below need to have
    # a reference to the model at creation. So we create an
    # empty model now.

    model = Model()

    # Send all messages to ImageJ log window.
    model.setLogger(Logger.IJ_LOGGER)

    #------------------------
    # Prepare settings object
    #------------------------

    settings = Settings()
    settings.setFrom(imp)

    # Configure detector - We use the Strings for the keys
    settings.detectorFactory = LogDetectorFactory()
    settings.detectorSettings = {
        'DO_SUBPIXEL_LOCALIZATION': SUBPIXEL_LOCALIZATION,
        'RADIUS': RADIUS,
        'TARGET_CHANNEL': TARGET_CHANNEL,
        'THRESHOLD': THRESHOLD,
        'DO_MEDIAN_FILTERING': MEDIAN_FILTERING,
    }

    # Configure spot filters - Classical filter on quality
    settings.initialSpotFilterValue = SPOT_FILTER
    settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotMorphologyAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotRadiusEstimatorFactory())

    filter1 = FeatureFilter('QUALITY', QUALITY, True)
    filter2 = FeatureFilter('CONTRAST', CONTRAST, True)
    filter2a = FeatureFilter('ESTIMATED_DIAMETER', MAX_ESTIMATED_DIAMETER,
                             False)
    filter2b = FeatureFilter('MEDIAN_INTENSITY', MAX_MEDIAN_INTENSITY, False)

    settings.addSpotFilter(filter1)
    settings.addSpotFilter(filter2)
    settings.addSpotFilter(filter2a)
    settings.addSpotFilter(filter2b)
    print(settings.spotFilters)

    # Configure tracker - We want to allow merges and fusions
    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap(
    )  # almost good enough

    ##adapted from https://forum.image.sc/t/trackmate-scripting-automatically-exporting-spots-in-tracks-links-in-tracks-tracks-statistics-and-branching-analysis-to-csv/6256
    #linking settings
    settings.trackerSettings['LINKING_MAX_DISTANCE'] = LINKING_MAX_DISTANCE
    if LINKING_FEATURE_PENALTIES == True:
        settings.trackerSettings['LINKING_FEATURE_PENALTIES'] = {
            LINKING_FEATURE_PENALTIES_TYPE: LINKING_FEATURE_PENALTIES_VALUE
        }
    else:
        settings.trackerSettings['LINKING_FEATURE_PENALTIES'] = {}

    #gap closing settings
    settings.trackerSettings['ALLOW_GAP_CLOSING'] = ALLOW_GAP_CLOSING
    if ALLOW_GAP_CLOSING == True:
        settings.trackerSettings[
            'GAP_CLOSING_MAX_DISTANCE'] = GAP_CLOSING_MAX_DISTANCE
        settings.trackerSettings['MAX_FRAME_GAP'] = MAX_FRAME_GAP
        if GAP_CLOSING_FEATURE_PENALTIES == True:
            settings.trackerSettings['GAP_CLOSING_FEATURE_PENALTIES'] = {
                GAP_CLOSING_FEATURE_PENALTIES_TYPE:
                GAP_CLOSING_FEATURE_PENALTIES_VALUE
            }
        else:
            settings.trackerSettings['GAP_CLOSING_FEATURE_PENALTIES'] = {}

    #splitting settings
    settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = ALLOW_TRACK_SPLITTING
    if ALLOW_TRACK_SPLITTING == True:
        settings.trackerSettings[
            'SPLITTING_MAX_DISTANCE'] = SPLITTING_MAX_DISTANCE
        if SPLITTING_FEATURE_PENALTIES == True:
            settings.trackerSettings['SPLITTING_FEATURE_PENALTIES'] = {
                SPLITTING_FEATURE_PENALTIES_TYPE:
                SPLITTING_FEATURE_PENALTIES_VALUE
            }
        else:
            settings.trackerSettings['SPLITTING_FEATURE_PENALTIES'] = {}

    #merging settings
    settings.trackerSettings['ALLOW_TRACK_MERGING'] = ALLOW_TRACK_MERGING
    if ALLOW_TRACK_MERGING == True:
        settings.trackerSettings['MERGING_MAX_DISTANCE'] = MERGING_MAX_DISTANCE
        if MERGING_FEATURE_PENALTIES == True:
            settings.trackerSettings['MERGING_FEATURE_PENALTIES'] = {
                MERGING_FEATURE_PENALTIES_TYPE: MERGING_FEATURE_PENALTIES_VALUE
            }
        else:
            settings.trackerSettings['MERGING_FEATURE_PENALTIES'] = {}

    print(settings.trackerSettings)

    # Configure track analyzers - Later on we want to filter out tracks
    # based on their displacement, so we need to state that we want
    # track displacement to be calculated. By default, out of the GUI,
    # not features are calculated.

    # The displacement feature is provided by the TrackDurationAnalyzer.

    settings.addTrackAnalyzer(TrackDurationAnalyzer())
    settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer())

    # Configure track filters - We want to get rid of the two immobile spots at
    # the bottom right of the image. Track displacement must be above 10 pixels.

    filter3 = FeatureFilter('TRACK_DISPLACEMENT', TRACK_DISPLACEMENT, True)
    filter4 = FeatureFilter('TRACK_START', TRACK_START, False)
    #filter5 = FeatureFilter('TRACK_STOP', float(imp.getStack().getSize())-1.1, True)

    settings.addTrackFilter(filter3)
    settings.addTrackFilter(filter4)
    #settings.addTrackFilter(filter5)

    #-------------------
    # Instantiate plugin
    #-------------------

    trackmate = TrackMate(model, settings)

    #--------
    # Process
    #--------

    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))

    ok = trackmate.process()

    #	if not ok:
    #sys.exit(str(trackmate.getErrorMessage()))

    #----------------
    # Display results
    #----------------

    #Set output folder and filename and create output folder
    well_folder = os.path.join(folder_w, filename)
    output_folder = os.path.join(well_folder, "Tracking")
    create_folder(output_folder)
    xml_file_name = filename + "_" + correction + "_trackmate_analysis.xml"
    folder_filename_xml = os.path.join(output_folder, xml_file_name)

    #ExportTracksToXML.export(model, settings, File(folder_filename_xml))
    outfile = TmXmlWriter(File(folder_filename_xml))
    outfile.appendSettings(settings)
    outfile.appendModel(model)
    outfile.writeToFile()

    # Echo results with the logger we set at start:
    #model.getLogger().log(str(model))

    #create araray of timepoint length with filled 0
    cell_counts = zerolistmaker(imp.getStack().getSize())
    if ok:
        for id in model.getTrackModel().trackIDs(True):
            # Fetch the track feature from the feature model.
            track = model.getTrackModel().trackSpots(id)
            for spot in track:
                # Fetch spot features directly from spot.
                t = spot.getFeature('FRAME')
                print(t)
                cell_counts[int(t)] = cell_counts[int(t)] + 1
    else:
        print("No spots detected!")

    if HEADLESS == False:
        selectionModel = SelectionModel(model)
        displayer = HyperStackDisplayer(model, selectionModel, imp)
        displayer.render()
        displayer.refresh()
    del imp
    return (cell_counts + [len(model.getTrackModel().trackIDs(True))])
示例#20
0
    if not rm:
        rm = RoiManager()

    # Loop through all the peak that were found
    for peak in peaks:
        # Print the current coordinates
        print "peaks", peak.getDoublePosition(0), peak.getDoublePosition(
            1), peak.getDoublePosition(2)
        # Add the current peak to the Roi manager
        roi = PointRoi(
            peak.getDoublePosition(0) / cal.pixelWidth,
            peak.getDoublePosition(1) / cal.pixelHeight)
        oval = OvalRoi(
            int(
                peak.getDoublePosition(0) / cal.pixelWidth -
                0.5 * radius / cal.pixelWidth),
            int(
                peak.getDoublePosition(1) / cal.pixelHeight -
                0.5 * radius / cal.pixelHeight), radius / cal.pixelWidth,
            radius / cal.pixelHeight)
        oval.setColor(Color.RED)
        # Set the Z position of the peak otherwise the peaks are all set on the same slice
        oval.setPosition(
            int(round(peak.getDoublePosition(2) / cal.pixelDepth)) + 1)
        roi.setPosition(
            int(round(peak.getDoublePosition(2) / cal.pixelDepth)) + 1)
        overlay.add(oval)
        imp.setOverlay(overlay)
        imp.updateAndDraw()

        rm.addRoi(roi)
示例#21
0
from ij import IJ
from ij.gui import OvalRoi
from ij.plugin.frame import RoiManager
from ij.plugin.filter import Analyzer
from ij.measure import Measurements, ResultsTable

imp = IJ.getImage()  
rm = RoiManager()  # instantiate manager # throws exception if it doesn't exist
#rm = RoiManager.getInstance() # if manager exists 
 
bright_roi = OvalRoi(118,94,12,12); # define and add ROI
imp.setRoi(bright_roi)  # make active on image
rm.addRoi(bright_roi)  # add
#rm.select(0) # select the ROI

dark_roi = OvalRoi(138,144,12,12)
imp.setRoi(dark_roi)  # make active on image
rm.addRoi(dark_roi)  # add

rm.runCommand(imp,"Measure")		# this will create a new results table
rm.runCommand(imp,"Show All")		# show all ROI
rt = Analyzer.getResultsTable()		

bright_mean = rt.getValueAsDouble(rt.getColumnIndex("Max"),0)
dark_mean = rt.getValueAsDouble(rt.getColumnIndex("Mean"),1)
print "Bright :" + str(bright_mean) + " Dark: " + str(dark_mean) +  "the contrast value is :" + str(bright_mean/dark_mean) #access table by col and row
示例#22
0
def merge_incorrect_splits_and_get_centroids(imp,
                                             centroid_distance_limit=100,
                                             size_limit=100):
    """if particles are found with centroids closer than centroid_distance_limit and both have size<size_limit, get average centroid"""
    imp.killRoi()
    rt = ResultsTable()
    out_imp = IJ.createImage("Nuclei centroids from {}".format(imp.getTitle()),
                             imp.getWidth(), imp.getHeight(), 1, 8)
    out_imp.show()
    IJ.run(out_imp, "Select All", "")
    IJ.run(out_imp, "Set...", "value=0 slice")
    out_imp.show()
    cal = imp.getCalibration()
    mxsz = imp.width * cal.pixelWidth * imp.height * cal.pixelHeight
    print("mxsz = {}".format(mxsz))
    roim = RoiManager()
    imp.show()
    pa = ParticleAnalyzer(
        ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA
        | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, rt, 0,
        size_limit)
    pa.setRoiManager(roim)
    roim.reset()
    rt.reset()
    pa.analyze(imp)
    MyWaitForUser("paise",
                  "pause post-merge incorrect splits particel analysis")
    rt_xs = rt.getColumn(rt.getColumnIndex("X")).tolist()
    rt_ys = rt.getColumn(rt.getColumnIndex("Y")).tolist()
    centroids = [(x, y) for x, y in zip(rt_xs, rt_ys)]
    print("centroids = {}".format(centroids))
    centroids_set = set()
    for c in centroids:
        ds = [
            math.sqrt((c[0] - cx)**2 + (c[1] - cy)**2)
            for (cx, cy) in centroids
        ]
        close_mask = [d < centroid_distance_limit for d in ds]
        # if no other centroids are within centroid_distance_limit, add this centroid to the output set
        # otherwise, add the average position of this centroid and those within centroid_distance_limit to the output set
        centroids_set.add(
            (sum([msk * b[0]
                  for msk, b in zip(close_mask, centroids)]) / sum(close_mask),
             sum([msk * b[1] for msk, b in zip(close_mask, centroids)]) /
             sum(close_mask)))
    roim.reset()
    rt.reset()
    pa = ParticleAnalyzer(
        ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA
        | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, rt, size_limit,
        mxsz)
    pa.setRoiManager(roim)
    pa.analyze(imp)
    MyWaitForUser("paise",
                  "pause post-merge incorrect splits particel analysis 2")
    if rt.columnExists("X"):
        rt_xs = rt.getColumn(rt.getColumnIndex("X")).tolist()
        rt_ys = rt.getColumn(rt.getColumnIndex("Y")).tolist()
    centroids = [(x, y) for x, y in zip(rt_xs, rt_ys)]
    for c in centroids:
        centroids_set.add(c)
    centroids = list(centroids_set)
    cal = imp.getCalibration()
    centroids = [(c[0] / cal.pixelWidth, c[1] / cal.pixelHeight)
                 for c in centroids]
    print("new number of nuclei identified = {}".format(len(centroids)))
    roim.reset()
    roim.close()
    for idx, c in enumerate(centroids):
        roi = OvalRoi(c[0], c[1], 10, 10)
        out_imp.setRoi(roi)
        IJ.run(out_imp, "Set...", "value={} slice".format(idx + 1))
    imp.changes = False
    #imp.close();
    return out_imp
            tempvar = [j-i for i, j in zip(var[:(idx-4)], var[4:])]
            if tempvar == []:
                continue
            idx = tempvar.index(max(tempvar))
            start = frame[0]
            metaphase = frame[idx+3]
            
            if (division - start > 15 and division - start < 100):
                if start>0:
                    for spot in sortedTrack:

                        # Fetch spot features directly from spot.
                        x=spot.getFeature('POSITION_X')
                        y=spot.getFeature('POSITION_Y')
                        t=spot.getFeature('FRAME')
                        roi2 = OvalRoi(x/dx - (6*dx), y/dy - (6*dy), 12, 12)
                        roi2.setPosition(int(t))
                        rm.add(imp, roi2, nextRoi)
                        nextRoi = nextRoi+1
                    resultstable.setValue("IMAGE_NAME", trackrowNumber, filename)
                    resultstable.setValue("TRACK_ID", trackrowNumber, id)
                    resultstable.setValue("START", trackrowNumber, start)
                    resultstable.setValue("METAPHASE", trackrowNumber, metaphase)
                    resultstable.setValue("END", trackrowNumber, division)

                    trackrowNumber = trackrowNumber + 1
#                    plot = Plot(str(id), "slice", "mean", frame, var) 
#                    plot.show()
#                    break

#        imp.close()
示例#24
0
#print fileSelection.getPath(), 
#print fileSelection.getFileName()
#Use names as labels in roiManager menu (more>>>)
#Save manually as well
imp = IJ.getImage()

rowIter = 0 

for row in dataRows:
	if len(row)>0:
		spotDataList = row.split("\t")
		spotData = [float(x) for x in spotDataList]
		topLeftX = spotData[1] - spotData[4]
		topLeftY = spotData[2] - spotData[4]
		diameter = 2*spotData[4]
		spotRoi = OvalRoi(topLeftX,topLeftY,diameter,diameter)
		roiManager.add(imp,spotRoi,rowIter)
		roiManager.rename(rowIter,"%4.0f"%spotData[0])
		rowIter = rowIter+1
	





#IJ.makeOval(900,900,50,80)
#a = OvalRoi(500,500,100,200)
#b = OvalRoi(200,200,300,100)

#roiManager.add(imp,a,0)
#roiManager.add(imp,b,0)
示例#25
0
#libs for csv reading
import csv
import os
#libs nec for ROI handling
from ij.plugin.frame import RoiManager
from ij.gui import OvalRoi
RoiManager()
b = RoiManager.getInstance()
#x = OvalRoi(322, 144, 108, 104)
#b.addRoi(x)
print(os.getcwd())

fn = 'C:/Users/tomjm/Desktop/test.csv'

with open(fn) as csvfile:
	readCSV = csv.reader(csvfile,delimiter=',')
	for row in readCSV:
			if row[3].isdigit():
				print(row[3])
				x = OvalRoi(int(row[3]), int(row[4]), int(row[5]), int(row[6]))
				b.addRoi(x)
示例#26
0
from ij.gui import OvalRoi;

from java.lang import Math;


IJ.run("Close All");

# load/create example images
imp = IJ.openImage("http://wsr.imagej.net/images/blobs.gif");
IJ.run(imp, "32-bit", "");
imp.show();

shiftX = NewImage.createFloatImage("", imp.getWidth(), imp.getHeight(), 1, NewImage.FILL_BLACK);
shiftY = NewImage.createFloatImage("", imp.getWidth(), imp.getHeight(), 1, NewImage.FILL_BLACK);

# define shift some of the pixels in X
shiftX.setRoi(OvalRoi(20, 98, 72, 68));
IJ.run(shiftX, "Add...", "value=25");
IJ.run(shiftX, "Select None", "");
IJ.run(shiftX, "Gaussian Blur...", "sigma=15");

# init GPU
clij = CLIJ.getInstance();

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

shiftXgpu = clij.push(shiftX);
rotatedShiftXgpu = clij.create(shiftXgpu);
shiftYgpu = clij.push(shiftY);
示例#27
0
def draw_nucleus(imp, value):
    imp.setRoi(OvalRoi(int(c), int(c), d, d))
    IJ.run(imp, "Add...", "value=" + str(value))