Exemple #1
0
def plot2DRoiOverZ(imp,
                   roi=None,
                   show=True,
                   XaxisLabel='Z',
                   YaxisLabel='I',
                   Zscale='1.0'):
    """
  Take an ImagePlus and a 2D ROI (optional, can be read from the ImagePlus)
  and plot the average value of the 2D ROI in each Z slice.

  Return 4 elements: the two lists of values for the Y (intensity) and X (slice index),
  and the Plot and PlotWindow instances.
  """
    roi = roi if roi else imp.getRoi()
    if not roi:
        syncPrint("Set a ROI first.")
        return
    # List of 2D points from where pixel values are to be read
    points = roiPoints(roi)
    stack = imp.getStack()
    intensity = [
        sum(stack.getProcessor(slice_index).getf(p.x, p.y)
            for p in points) / len(points)
        for slice_index in xrange(1,
                                  imp.getNSlices() + 1)
    ]
    xaxis = [z * Zscale for z in range(1, imp.getNSlices() + 1)]
    plot = Plot("Intensity", XaxisLabel, YaxisLabel, xaxis, intensity)
    if show:
        win = plot.show()
    else:
        win = None
    return intensity, xaxis, plot, win
Exemple #2
0
def plot_bleb_evolution(ts, prop_to_plots, title):
    """Plot evolution of a given bleb property over time"""
    title = title.replace("\u00B5", "u")
    plt = Plot((title + " against time"), "Time", title)
    plt.add("line", ts, prop_to_plots)
    plt.show()
    plot_data = [(t, d) for t, d in zip(ts, prop_to_plots)]
    return plt.getImagePlus(), plot_data
def plotRotation(roi_number, result_path, t, x, y, rotation_speed):
    # plot t-x, t-y, x-y, t-rotation_speed and save plot+roi_number.bmp
    txplot = Plot('x-t plot','time (s)', 'x (pixel)', t, x)
    typlot = Plot('y-t plot','time (s)', 'y (pixel)', t, y)
    xyplot = Plot('x-y plot', 'x (pixel)', 'y (pixel)', x, y)
    tspeedplot = Plot('Rotation speed-t plot','time (s)', 'Rotaion Speed (Hz)', t, rotation_speed)

    graphW = 1000
    graphH = 500
    txplot.setFrameSize(graphW, graphH)
    typlot.setFrameSize(graphW, graphH)
    xyplot.setFrameSize(graphW, graphH)
    tspeedplot.setFrameSize(graphW, graphH)

    #make plots as stack image
    tximp = txplot.getImagePlus()
    xyimp = xyplot.getImagePlus()
    tyimp = typlot.getImagePlus()
    tsimp = tspeedplot.getImagePlus()

    pstack = ImageStack(tximp.width,tximp.height)
    pstack.addSlice(tximp.getProcessor())
    pstack.addSlice(tyimp.getProcessor())
    pstack.addSlice(xyimp.getProcessor())
    pstack.addSlice(tsimp.getProcessor())
    pstackimp = ImagePlus('plots', pstack)

    pstackM = MontageMaker().makeMontage2(pstackimp, 2, 2, 2, 1, 4, 1, 0, False)
    #pstackM.show()
    IJ.saveAs(pstackM, 'BMP', os.path.join(result_path,'Plot' + str(roi_number) + '.bmp'))

    tximp.close()
    xyimp.close()
    tyimp.close()
    tsimp.close()
    pstackM.close()
Exemple #4
0
    def createAngleTable(self, roi):
        polygon = roi.getPolygon()
        xPoints = polygon.xpoints
        yPoints = polygon.ypoints

        nPoints = polygon.npoints
        table = ResultsTable()
        firstAngle = Math.atan2(yPoints[0], xPoints[0])
        plot = Plot(str(roi.getName()) + " Angle", "--", "angle")

        angles = []
        derivative = []
        derivativeSign = []
        posDerivative = 0
        negDerivative = 0

        for i in range(nPoints):
            x = xPoints[i]
            y = yPoints[i]
            angle = Math.atan2(y, x)

            angles.append(angle - firstAngle)
            if i == 0:
                continue

            derivative.append(angle - angles[-2])
            derivativeSign.append(Math.signum(derivative[-1]))
            if derivativeSign[-1] > 0:
                posDerivative = posDerivative + 1
            else:
                negDerivative = negDerivative + 1

        maxSign = max(posDerivative, negDerivative)
        minSign = min(posDerivative, negDerivative)

        print("--" + str(roi.getName()))
        signRatio = float(minSign) / float(maxSign)
        print("Min Sign = " + str(minSign))
        print("Max Sign = " + str(maxSign))
        print("Sign Ratio = " + str(signRatio))
        plot.add("filled", derivativeSign)
        plot.show()

        if signRatio < 1.1:
            # table.show(str( roi.getName())+" Angle")
            return True
        return False
Exemple #5
0
def fit_gauss(lroi, imp, p, peak_id, id_, type_, rm):
	lroi.setName("{}_{}_{}".format(str(id_), peak_id, type_))
	imp.setRoi(lroi)
	rm.addRoi(lroi)
	
	prof = ProfilePlot(imp)
	y = prof.getProfile()
	x = xrange(len(y))
	
	fitter = CurveFitter(x, y)
	fitter.doFit(CurveFitter.GAUSSIAN)
	param_values = fitter.getParams()
	std = param_values[3]
	fwhm = 2.3548 * std
	r2 = fitter.getFitGoodness()

	y_ = [fitter.f(x_) for x_ in x]
	
	area_profile = sum(y)  - len(y) *min(y)
	area_gauss   = sum(y_) - len(y_)*min(y_)
	
	output = {}
	output["x_pos"] = p.x
	output["y_pos"] = p.y
	output["fwhm"] = fwhm
	output["fwhm_nm"] = pixel_size_nm * fwhm
	output["r2_GoF"] = r2
	output["id"] = id_
	output["peak_id"] = peak_id
	output["type"] = type_
	# yai, excel maagic :-)
	output["avg_fwhm"] = '=AVERAGEIFS(F:F,B:B,B{},F:F,"<>"&"")'.format(id_+2)
	output["area_profile"] = area_profile
	output["area_gauss"] = area_gauss

	if peak_id == DEBUG:		
		plot = Plot("ROI peak {} type {}".format(peak_id, type_), "X (gray)", "Y (fit window)")
		plot.setLineWidth(2)
		plot.setColor(Color.RED)
		plot.addPoints(x, y, Plot.LINE)
		plot.setColor(Color.BLUE)
		plot.addPoints(x, y_, Plot.LINE)
		plot.show()
		
	return  output
Exemple #6
0
		
	# Means per frame and then mean of mean
		listmeans = ImagesMean(dataset, z)
		stackmeans = computeMean(listmeans)
		filemeans.append(stackmeans)
		
	# Stds per frame.
		liststds = ImagesStd(dataset,listmeans, z)
		grouped = group_stds(liststds)
		#std the std.
		filestds.append(grouped)
	
	return filemeans, filestds



# MAIN CODE
srcDir = DirectoryChooser("Choose").getDirectory()
filelist = get_file_list(srcDir, '.tif')
means, stds = main(filelist)


# PLOTTING
plot = Plot("PTC", "Mean", "Std")
plot.setLimits(0.00, 200.0, 0.00, 100.0)
plot.setColor(Color.BLUE)
plot.addPoints(means, stds, Plot.CROSS)
plot.show()
print means, stds

Exemple #7
0
def plot(data, center):
    T = list(range(0, len(data)))
    plot = Plot("radial velocity in (" + str(center[0]) + ", "+ str(center[1])+")", "time[1]", "radial velocity", T, data)
    plot.show()
from ij.gui import Plot
from java.awt import Color
import jarray
import os

# start clean
IJ.run("Close All")

# create example data arrays
xa = [1, 2, 3, 4]
ya = [3, 3.5, 4, 4.5]

# convert to java array
jxa = jarray.array(xa, 'd')
jya = jarray.array(ya, 'd')

# Create filled plot
plt = Plot("Line plot", "X", "Y")
plt.setLimits(0, 5, 0, 5)
plt.setFrameSize(600, 300)
plt.setColor("blue", "#ccccff")

# the circles are small. Can't figure out how to make
# them larger... These 2 calls are equivalent...
# plt.addPoints(jxa,jya, Plot.CIRCLE)
plt.add("circles", jxa, jya)
plt.setColor(Color.RED)
plt.setLineWidth(1)
plt.drawLine(0.0, 2.5, 4.0, 4.5)
plt.setXYLabels("X", "Y")
plt.show()
Exemple #9
0
mx1 = []
mx2 = []
my1 = []
my2 = []
for i in range(0, len(x1)):
    mx1.append(x1[i] - dx[i] / 2)
    my1.append(y1[i] - dy[i] / 2)
    mx2.append(x2[i] - dx[i] / 2)
    my2.append(y2[i] - dy[i] / 2)

#plt = Plot(fName, "degrees","degrees")
#plt.setLimits(-10,10, -10, 10)
##plt.setAxes(False,False,True, True,False, False, 1, 10);
#plt.setFrameSize(500,500);
#plt.draw()
#plt.addPoints(cx,cy,Plot.CIRCLE);
#plt.drawVectors(x1,y1,x2,y2)
#plt.show()

plt2 = Plot(fName, "degrees", "degrees")
plt2.setLimits(-10, 10, -10, 10)
plt2.setAxes(False, False, True, True, False, False, 1, 10)
plt2.setFrameSize(500, 500)
plt2.draw()
plt2.addPoints(cx, cy, Plot.CIRCLE)
plt2.drawVectors(mx1, my1, mx2, my2)
plt2.setColor(java.awt.Color.RED)
plt2.setLineWidth(2)
plt2.addPoints(x1, y1, Plot.CIRCLE)
plt2.show()
Exemple #10
0
stack_crop = stack.crop(x_val, y_val, 0, width, height, NSlices)

time1 = timeit.default_timer()
print roi
print stack
print stack_crop

modal_vals = []

for idx in range(0, stack_crop.size()):
    #Determine Mode of each Slice
    sel_frame = stack_crop.getProcessor(idx + 1)  #1-based indexing
    frame_hist = sel_frame.getHistogram()
    hist_set = sorted(set(frame_hist))
    modal_count = hist_set[-1]
    modal_val = frame_hist.index(modal_count)
    if modal_val == 0:
        modal_count = hist_set[-2]
        modal_val = frame_hist.index(modal_count)
    modal_vals.append(modal_val)
    if idx % 1000 == 0:
        print(idx, timeit.default_timer() - time1)

print sorted(set(modal_vals))
print timeit.default_timer() - time1

final_plot = Plot("Modal Values", "Stack", "Value")
final_plot.add("line", modal_vals)
final_plot.show()

print timeit.default_timer() - time1
    for filename, row, row_value in all_ydata:
        table.set(filename, row, row_value)
    uiservice.show("MergedFiles_%s" % data_identifier, table)

    log("Retrieving statistics for merged Y-data...")
    list_of_rows = defaultdict(list)
    for data in all_ydata:
        list_of_rows[data[1]].append(data[2])

    row_stats = {}
    for row_key, row_values in list_of_rows.iteritems():
        row_stats[row_key] = (mean(row_values), stdev(row_values), len(row_values))

    table = newtable(xcolumn_header, xvalues)
    for key, value in row_stats.iteritems():
        table.set("Mean", int(key), value[0])
        table.set("StdDev", int(key), value[1])
        table.set("N", int(key), value[2])
    uiservice.show("Stats_%s" % data_identifier, table)

    plot = Plot("Mean Sholl Plot [%s]" % ycolumn_header, xcolumn_header, "N. of intersections")
    plot.setLegend("Mean"+ u'\u00B1' +"SD", Plot.LEGEND_TRANSPARENT + Plot.AUTO_POSITION)
    plot.setColor("cyan", "blue")
    plot.addPoints(table.get(0), table.get(1), table.get(2), Plot.CONNECTED_CIRCLES, data_identifier)
    plot.show()

    log("Parsing concluded.")


main()
Exemple #12
0
    # Make a measurement in it
    stats = ImageStatistics.getStatistics(ip, Measurements.MEAN, calibration)
    mean = stats.mean

    # Store the measurement in the list
    intensities.append(mean)

IJ.log('For image ' + current_imp.getTitle())
IJ.log('Time interval is ' + str(frame_interval) + ' ' + time_units)

# Build plot
x = [i * frame_interval for i in range(n_slices)]
y = intensities

plot = Plot("Backgrouncurve " + current_imp.getTitle(),
            "Time (" + time_units + ')', "NU", [], [])
plot.setLimits(0, max(x), 0, max(y))
plot.setLineWidth(2)

plot.setColor(Color.BLACK)
plot.addPoints(x, y, Plot.LINE)
plot.addPoints(x, y, PlotWindow.X)

plot.setColor(Color.black)
plot_window = plot.show()

###############################

# Save data as a json file

###############################
Exemple #13
0
def plot_rad3d(tab):
    r = len(tab) - 1
    idx = list(range(-r, r + 1))
    val = tab[::-1] + tab[1:]

    return Plot("3D radial distribution", "rad", "mean", idx, val)
        else:
            sliceAvgInt[currentSlice - 1] = 0
            sliceAboveZeroNorm[currentSlice - 1] = 0
            sliceExpectedRadNorm[currentSlice - 1] = 0

print("writing to file...")

# Find
thisStr = IJ.getDirectory("image")
upStr = thisStr[:thisStr.find("merged_videos/")]
rezPath = upStr + "blink_files/result_new.txt"

myfile = open(rezPath, 'w')
for i in range(len(slicesIdx)):
    myfile.write(
        str(slicesIdx[i]) + " " + str(sliceAvgInt[i]) + " " +
        str(sliceAboveZeroNorm[i]) + " " + str(sliceExpectedRadNorm[i]) + "\n")
myfile.close()

print("plotting...")

plot = Plot("Title", "X", "Y")
plot.setLimits(1.0, img2.getNSlices(), 0.0, 1.0)
plot.setColor(Color.RED)
plot.addPoints(slicesIdx, sliceAvgInt, Plot.CROSS)
plot.setColor(Color.BLUE)
plot.addPoints(slicesIdx, sliceAboveZeroNorm, Plot.CROSS)
plot.setColor(Color.GREEN)
plot.addPoints(slicesIdx, sliceExpectedRadNorm, Plot.CROSS)
plot.show()
Exemple #15
0
from ij.gui import Plot
from math import sin, cos, radians

# title, X label, Y label
plot = Plot("My data", "time", "value")

# Series 1
plot.setColor("blue")
plot.add("circle", [50 + sin(radians(i * 5)) * 50 for i in xrange(100)])

# Series 2
plot.setColor("magenta")
plot.add("diamond", [50 + cos(radians(i * 5)) * 50 for i in xrange(100)])

# Series 3
plot.setColor("black")
plot.add("line", [50 + cos(-1.0 + radians(i * 5)) * 50 for i in xrange(100)])

plot.show()
def plots(values, timelist, Cell_number, value_type, Stim_List, dirs, parameters):
    """ Plots all calculated values, saves plots to generated directory, returns plot scale. """

    Mean_plot = 0
    # Flatten nested lists (normalized lists are not nested).
    if value_type == "Normalized aFRET mean":    
        values_concat = [ values[i:i+Cell_number] for i in range(0, (len(values)), Cell_number) ]
        Mean_sd = [ standard_deviation(values_concat[i]) for i in range(len(values_concat)) ]
        Mean_sd = [item for sublist in Mean_sd for item in sublist]
        Mean_plot = 1
    elif value_type == "Normalized dFRET mean":
        values_concat = [ values[i:i+Cell_number] for i in range(0, (len(values)), Cell_number) ]
        Mean_sd = [ standard_deviation(values_concat[i]) for i in range(len(values_concat)) ]
        Mean_sd = [item for sublist in Mean_sd for item in sublist]
        Mean_plot = 1

    else:
        if "Normalized" not in value_type:
            values = [item for sublist in values for item in sublist]

    #Repeats list items x cell_number (match timepoints with # of cells).
    timelist = [x for item in timelist for x in repeat(item, Cell_number)]

    # Scaling of plots.
    max_Y = 1
    if max(values) > 3:
        if not isinstance(values[0], list):
            max_Y = max(values)*1.3
    elif max(values) > 2.5:
        max_Y = 3.3
    elif max(values) > 2:
        max_Y = 2.7
    elif max(values) > 1.5:
        max_Y = 2.2
    elif max(values) > 1.3:
        max_Y = 1.7
    elif max(values) > 1:
        max_Y = 1.4


    min_Y = 0
    if min(values) > 2:
        min_Y = min(values)*0.8
    elif min(values) > 1.5:
        min_Y = 1.5
    elif min(values) > 1:
        min_Y = 1
    elif min(values) > 0.5: 
        min_Y = 0.2
                    
    elif min(values) < -0.5:
        min_Y = min(values)*1.3
    elif min(values) < -0.2:
        min_Y = -0.3
    elif min(values) < -0.1:
        min_Y = -0.15
    elif min(values) < -0.08:
        min_Y = -0.1
    elif min(values) < -0.05:
        min_Y = -0.08
    elif min(values) < -0.01:
        min_Y = -0.06

    # Scaling of normalized plots..
    if "Normalized" in value_type:
        min_Y, max_Y = float(parameters["p_min_n"]), float(parameters["p_max_n"])

    if value_type == "dFRET":
        max_Y = float(parameters["p_max"])
        min_y = float(parameters["p_min"])
    elif value_type =="aFRET":
        max_Y = float(parameters["p_max"])
        min_y = float(parameters["p_min"])

    # Call plot, set scale.
    plot = Plot(Title, "Time (minutes)", value_type)
    if len(timelist) > 1:      
        plot.setLimits(min(timelist), max(timelist), min_Y, max_Y)
    else:
        plot.setLimits(-1, 1, min_Y, max_Y)
    # Retrieve colors.
    Colors, Colors_old = colorlist()

    # Set colors, plot points.
    if Mean_plot == 0:
        for i in range(Cell_number):
            if i < 19:
                plot.setColor(Color(*Colors[i][0:3]))
            elif i >= 19:
                plot.setColor(eval(Colors_old[i]))
                print "Out of fancy colors, using java.awt.color defaults"
            elif i > 28:
                print "29 color limit exceeded"
                return
                    
            plot.setLineWidth(1.5)
            plot.addPoints(timelist[i :: Cell_number], values[i :: Cell_number], Plot.LINE)
            plot.setLineWidth(1)

            # Comment in to define color + fillcolor for circles.
            plot.setColor(Color(*Colors[i][0:3]), Color(*Colors[i][0:3]))
            #plot.addPoints(timelist[i :: Cell_number], values[i :: Cell_number], Plot.CIRCLE)
    else:
        min_Y, max_Y = 0.6, 1.6
        if len(timelist) > 1:
            plot.setLimits(min(timelist), max(timelist), min_Y, max_Y)
        else: 
            plot.setLimits(-1, 1, min_Y, max_Y)
        plot.setColor("Color.BLACK")
        plot.setLineWidth(1.5)
        plot.addPoints(timelist[0 :: Cell_number], Mean_sd[0::2], Plot.LINE)
        plot.setLineWidth(1)
        plot.setColor("Color.BLACK", "Color.BLACK")
        plot.addPoints(timelist[0 :: Cell_number], Mean_sd[0::2], Plot.CIRCLE)
        plot.setColor(Color(*Colors[6][0:3]))
        plot.addErrorBars(Mean_sd[1::2])

    # Get's stim name from input.
    if not Stim_List == False:
        text = [ sublist[i] for sublist in Stim_List for i in range(len(Stim_List)) ]
        Stim_List = [ sublist[1:] for sublist in Stim_List ]

        # Plot stimulation markers. 
        plot.setLineWidth(2)
        for sublist in Stim_List:
           plot.setColor("Color.GRAY")
           plot.drawLine(sublist[0], min_Y+((max_Y-min_Y) * 0.82), sublist[1], min_Y+((max_Y-min_Y) * 0.82))
           plot.drawDottedLine(sublist[0], min_Y+((max_Y-min_Y) * 0.82), sublist[0], -1, 4)
           plot.drawDottedLine(sublist[1], min_Y+((max_Y-min_Y) * 0.82), sublist[1], -1, 4)
           plot.setFont(Font.BOLD, 16)
           plot.addText(text[0], sublist[0], min_Y+((max_Y-min_Y) * 0.82))

    cell_num = 0
    if "concentration" not in value_type:
        testfile = open(os.path.join(dirs["Tables"], value_type + ".txt"), "w")
        data = plot.getResultsTable()
        headings = data.getHeadings()
        datadict = {}
        for heading in headings:         
            index = data.getColumnIndex(heading)
            if "Y" in heading:
                column = { "Cell "+str(cell_num).zfill(2) : [round(float(i), 4) for i in data.getColumn(index)] }
            elif "X" in heading:
                column = {"X" : [round(float(i), 4) for i in data.getColumn(index)] }
            cell_num += 1
            datadict.update(column)

        sorted_data = []
        for row in zip(*([key] + value for key, value in sorted(datadict.items()))):
            sorted_data.append(row)

        testfile.write("\t\t".join(sorted_data[0]))

        # Prints output in columns, copy paste directly to sigma/prisma/excel etc.
        for cell in range (1, len(sorted_data), 1):
            testfile.write("\n")
            for times in range(len(sorted_data[cell])):
                testfile.write(str(sorted_data[cell][times]) + "\t\t")  

        # Dumps sorted data to JSON format, for use in eg. matplotlib.
        with open(os.path.join(dirs["Tables"], value_type + ".json"), "w") as outfile:
            datadict["Stim"] = Stim_List
            json.dump(datadict, outfile, sort_keys=True)
        
        testfile.close()


    # Generate High-res plot with anti-aliasing (Scale x 1). 
    plot = plot.makeHighResolution(Title, 1, True, True)    
    #PlotWindow.noGridLines = True

    # Save plot with appropriate title.
    IJ.saveAs(plot, "PNG", os.path.join(dirs["Plots"], str(Title)+str(value_type)))

    # (For ratiometric image-generator)
    return max_Y, min_Y
Exemple #17
0
		if (amplificacion > MaxAmplificacion) :
			MaxAmplificacion=amplificacion
			ROptima=LogFilterSigma
		if amplificacion <=ValuePrev :
			RepCounter+=1	
		else:
			RepCounter=0
		ValuePrev=amplificacion
		#Break if the value decreases for 3 consecutive values
		if(RepCounter==3):
			break

	return MaxAmplificacion,ROptima


#Main Method


image = IJ.getImage()
Moment3=CheckMoment(image)
Mom3Norm=[i/Moment3[0]-1.0 for i in Moment3]

NFrames= image.getNFrames()
xArr = array(range(1,NFrames+1), 'd')
plot = Plot("Title", "Time", "Delta m ",xArr,Mom3Norm)
plot.setLimits(1, NFrames, min(Mom3Norm), max(Mom3Norm))
plot.setColor(Color.BLUE)
plot.addPoints(xArr,Mom3Norm,Plot.CROSS)
plot.show()

  
# Fitter
fitter = CurveFitter(xtofit, ytofit)
fitter.doFit(CurveFitter.EXP_RECOVERY_NOOFFSET)
IJ.log("Fit FRAP curve by " + fitter.getFormula() )
param_values = fitter.getParams()
IJ.log( fitter.getResultString() )
  
# Overlay fit curve, with oversampling (for plot)
xfit = [ (t / 10.0  + bleach_frame) * frame_interval for t in range(10 * len(xtofit) ) ]
yfit = []
for xt in xfit:
    yfit.append( fitter.f( fitter.getParams(), xt - xfit[0]) )
 
  
plot = Plot("Normalized FRAP curve for " + current_imp.getTitle(), "Time ("+time_units+')', "NU", [], [])
plot.setLimits(0, max(x), 0, 1.5 );
plot.setLineWidth(2)
 
 
plot.setColor(Color.BLACK)
plot.addPoints(x, y, Plot.LINE)
plot.addPoints(x,y,PlotWindow.X);
 
  
plot.setColor(Color.RED)
plot.addPoints(xfit, yfit, Plot.LINE)
 
plot.setColor(Color.black);
plot_window =  plot.show()
 
Exemple #19
0
def create_plot(imp, method, average, threshold=0.1):
	intensity = cross_section_intensity(imp, method)
	cal = imp.getCalibration()
	x_inc = cal.pixelWidth;
	units = cal.getUnits();
	x_label = "Distance (%s)" % units
	y_label = 'Intensity' # cal.getValueUnit()
	x_values = [i*x_inc for i in range(len(intensity))]

	lastindex = len(x_values)-1
	for i in range(1, len(x_values)+1):
		index = len(x_values)-i
		if intensity[index] == 0:
			lastindex = index-1
		else:
			break
	ax = [x_values[i] for i in range(lastindex)]
	ay = [intensity[i] for i in range(lastindex)]
	average_x, average_y = rolling_average(ax, ay, average)

	firstidx, lastidx, threshold_intensity = get_thresholded_idx(average_y, threshold=threshold)
	perform_trim = firstidx!=-1 and lastidx!=-1
	if perform_trim:
	    trim_x = [average_x[i] for i in range(firstidx, lastidx+1)]
	    trim_y = [average_y[i] for i in range(firstidx, lastidx+1)]

	# raw data
	flags = Plot.getDefaultFlags()
	flags = flags - Plot.Y_GRID - Plot.X_GRID
	plot = Plot("%s-Plot" % imp.getTitle(), x_label, y_label, flags)
	plot.setLineWidth(1)
	plot.setColor(Color.BLACK)
	plot.addPoints(x_values, intensity,Plot.LINE)

	# threshold line
	plot.setLineWidth(2)
	plot.setColor(Color.BLACK)
	plot.addPoints([0,x_inc * imp.getWidth()], [threshold_intensity,threshold_intensity],Plot.LINE)

	# rolling average
	plot.setLineWidth(2)
	plot.setColor(Color.MAGENTA)
	plot.addPoints(average_x,average_y,Plot.LINE)

	# standard legend labels
	labels = "\t".join(['Raw Data (%s)' % method, 'Intensity threshold (%d%s)' % (100*threshold, '%'), 'Rolling Average (n=%d)' % average])

	# trimmed rolling average
	if perform_trim:
	    plot.setLineWidth(2)
	    plot.setColor(Color.GREEN)
	    plot.addPoints(trim_x,trim_y,Plot.LINE)
	    labels+='\tTrimmed Rolling Average (n=%d)' % average

	plot.setColor(Color.BLACK)
	plot.setLimitsToFit(False)
	plot.addLegend(labels)

	rt = ResultsTable()
	for row,x in enumerate(x_values):
		rt.setValue(DIST_RAW_COL, row, x)
		rt.setValue(INT_RAW_COL, row, intensity[row])
	for row,x in enumerate(average_x):
		rt.setValue(DIST_AVG_COL, row, x)
		rt.setValue(INT_AVG_COL, row, average_y[row])
	if perform_trim:
	    for row,x in enumerate(trim_x):
		    rt.setValue(DIST_TRIM_COL, row, x)
		    rt.setValue(INT_TRIM_COL, row, trim_y[row])
    
	return plot, rt
Exemple #20
0
# exp = zPlot.getXValues()
levels = zPlot.getYValues()

# Find the best linear fit of mean gray level vs camera exposure
cf = CurveFitter(exposures, list(levels))
cf.doFit(CurveFitter.STRAIGHT_LINE)
fitParams = cf.getParams()
slope = fitParams[1]
intercept = fitParams[0]
rSqr = cf.getRSquared()

print("slope=", slope, " ; intercept=", intercept, " ; rSquared=", rSqr)

# Plot the data and the regression line
newPlotFlags = Plot.TRIANGLE + Plot.X_GRID + Plot.X_NUMBERS + Plot.Y_GRID + Plot.Y_NUMBERS
newPlot = Plot("DARK NOISE", "EXPOSURE, ms", "MEAN GRAY LEVEL", newPlotFlags)
newPlot.setLineWidth(2)
newPlot.setColor("red")
newPlot.add("triangle", exposures, list(levels))
newPlot.setLineWidth(1)
newPlot.setColor("black")
newPlot.drawLine(exposures[0], cf.f(exposures[0]), exposures[-1],
                 cf.f(exposures[-1]))
newPlot.setColor("blue")
newPlot.setFontSize(20)
newPlot.addText("y = a+bx", 100.0, 13000.0)
newPlot.addText("a = " + str(round(intercept, 2)), 100.0, 12250.0)
newPlot.addText("b = " + str(round(slope, 2)), 100.0, 11500.0)
newPlot.addText("R squared = " + str(round(rSqr, 3)), 100.0, 10750.0)
newPlot.show()
Exemple #21
0
# Save the CSV
if doSaveCSV:
	filename = file.absolutePath + "_compensations.csv"
	with open(filename,'w') as f:
		f.write(",".join(names)+"\n")
		for i in range(len(profiles[0])):
			row=[ str(p[i]) for p in profiles ]
			row=",".join(row)
			f.write(row+"\n")

# Generate a plot
if doPlot:
	from ij.gui import Plot
	from java.awt import Color
	p = Plot('Profiles','Channel #','Intensity')
	p.setSize(640,480)
	maxP = len(profiles)
	maxV = 0
	for iprofile,profile in enumerate(profiles):
		h = 0.66-(float(iprofile)/maxP)
		if h<0:
			h=h+1
		p.setColor(Color.getHSBColor( h,.8,1))
		p.addPoints(range(len(profile)),profile,p.LINE)
	
		maxV_=max(profile)
		if maxV < maxV_:
			maxV = maxV_
	p.setLimits(0,len(profile)-1,0,maxV*1.2)
	p.setLegend("\n".join(names),p.TOP_LEFT|p.LEGEND_TRANSPARENT)
def plot(dataX, dataY, center):
    plot = Plot("augmentation of distance from c=(" + str(center[0]) + ", "+ str(center[1])+")", "distance start to end", "augmentation of distance from c", dataX, dataY)
    plot.setStyle(0, "blue,none,1.2,X");
    plot.show()