def getWidthAt(x, imp):
  ip = imp.getProcessor()
  calibration = imp.getCalibration()
  height = ip.getHeight()
  lastValue = 0
  numberOfTimesValueChanged = 0;
  startY = 0;
  endY = 0
  xUnscaled = int(round(calibration.getRawX(x),0))
  for i in range(0, height-1):
    newValue = ip.get(xUnscaled, i)
    if lastValue!=newValue:
        if numberOfTimesValueChanged==0: 
          startY = i
          numberOfTimesValueChanged = numberOfTimesValueChanged + 1
        endY = i
    lastValue = newValue;
  calibration = imp.getCalibration()
  yS = calibration.getY(startY)
  yE = calibration.getY(endY)
  IJ.makeLine(xUnscaled, startY, xUnscaled, endY)
  IJ.run("Add Selection...")
  return yE-yS
Esempio n. 2
0
def duty_cycle(i, horizontal):
	IJ.open(i)
	IJ.run("Enhance Contrast...", "saturated=0.3 equalize")
	IJ.run("Smooth", "")
	'IJ.run("Anisotropic Diffusion 2D", "number=20 smoothings=1 keep=20 a1=0.50 a2=0.90 dt=20 edge=5")     # use instead of smooth for better results, slower
	imp = IJ.getImage()
	ImageConverter(imp).convertToGray8()
	file_base = str(imp.title)								# convert name into string
	file_base = file_base.split('.', 1)[0]					# remove all characters including and after .
	sample_id = file_base.split('_', 1)[0]
	height = imp.height
	width = imp.width
	IJ.run(imp, "Set Scale...", "distance=5000 known=1 pixel=1 unit=cm")
	IJ.setTool("line")
	for scan in range(1, num_scans):
		row_count = 0
		data=[]
		data2=[]
		last = 0
		filename = file_base + "_" + str(scan)
		
		if not horizontal:
			IJ.makeLine(0, scan*height/num_scans, width, scan*height/num_scans)				# horizontal line to measure vertical grating profile		
		else:
			IJ.makeLine(width*scan/num_scans, 9*height/10, width*scan/num_scans, 0)			# vertical line to measure horizontal grating profile
		
		IJ.run(imp, "Plot Profile", "")
		imp_plot = IJ.getImage()
		IJ.run(imp, "Find Peaks", setting)	# nw07 params: min._peak_amplitude=60 min._peak_distance=0 min._value=100 max._value=0 exclude list
		IJ.saveAs("Results", csvpath + filename + "_raw.csv")
		imp_plot.close()
		imp_plot = IJ.getImage()
		IJ.saveAs("Png", csvpath + "Peaks in Plot of " + filename + ".png")
		imp_plot.close()
		IJ.selectWindow(filename + "_raw.csv")
		IJ.run("Close")
		
		with open(csvpath + filename + "_raw.csv", "rb") as fin, open(csvpath + filename + "_peaks.csv", "wb") as fout:  
		    writer = csv.writer(fout)            
		    for row in csv.reader(fin):
		        if not row[2] == '':
		             writer.writerow(row)

		with open(csvpath + filename + "_peaks.csv", "rb") as File:
		    reader = csv.reader(File)
		    for row in reader:
		        row_count += 1
			if row_count == 1:
				continue
			data.append(tuple(row))								# Append all non-header rows into a list of data as a tuple of cells
		for row in sort_table(data, 2):
			data2.append(tuple(row))
		if len(data2) < 3:
			IJ.log(filename + " no peaks detected, skipping...")
			continue
		else:
			peaks = len(data2)
			last = data2[0]
			last = last[2]
			
			row_count = 0
			diff = 0
			colG = []
			blank = ""
			duty = zip(*data2)
			for row in data2:
				row_count += 1
				if row_count == 1:
					continue
				else:
					print row[2]
					print last
					diff = float(row[2]) - float(last)
					colG.append(diff)
					last = row[2]
			a, b = colG[::2], colG[1::2]
			avga = sum(a)/len(a)
			avgb = sum(b)/len(b)
			a_len_dev = len(a) - 1
			b_len_dev = len(b) - 1
			if b_len_dev > 1:
				a_stdev = sqrt(sum((x - avga)**2 for x in a) / a_len_dev)
				b_stdev = sqrt(sum((x - avgb)**2 for x in b) / b_len_dev)
			else:
				a_stdev = 1
				b_stdev = 1
			
			duty_cyc = avga/(avga+avgb)
			perc = duty_cyc*100
			invperc = 100 - perc
			inv_duty = 1 - duty_cyc
			duty_max = max(duty_cyc, inv_duty)
			duty_min = min(duty_cyc, inv_duty)
			percs = round(perc)
			percs = int(percs)
			percs = str(percs)
			invpercs = round(invperc)
			invpercs = int(invpercs)
			invpercs = str(invpercs)
		
			colG.insert(0, blank)
			a.insert(0, blank)
			b.insert(0, blank)
			b.insert(1, blank)
			
			i = 0
			while i < len(a):
					i += 2
					a.insert(i, blank)
			
			i = 1
			while i < len(b):
					i += 2
					b.insert(i, blank)
			
			duty.append(colG)
			duty.append(a)
			duty.append(b)	
			duty = zip(*duty)
			result = [sample_id, file_base, scan, duty_cyc, inv_duty, a_stdev, b_stdev, peaks, duty_max, duty_min]
			header = ["X0", "Y0", "X1", "Y1", "X2", "Y2", "diff", "a", "b"]
			results.append(result)
			with open(csvpath + filename + "_duty.csv", 'wb') as myfile:
				wr = csv.writer(myfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
				wr.writerow(header)
				wr.writerows(duty)
			print(filename + " duty cycle is " + percs + "/" + invpercs + "%.")
			IJ.log(filename + " duty cycle is " + percs + "/" + invpercs + "% (" + str(peaks) + " peaks found)")
			with open(csvpath + "results.csv", 'wb') as myfile:
				wr = csv.writer(myfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
				wr.writerows(results)		# Write the result data from all images into a single csv file
IJ.log("Results for " + path.basename(stackpath) + ":")    
IJ.log("Average intensity: " + str(average(means))) 
IJ.log("Standard deviation: " + str(stdev(means)))

# now, use the subtracted image to output the flat field image and plot

# get the plot out of the way to bring back the stack
WM.putBehind()
#average all frames
IJ.run("Z Project...", "projection=[Average Intensity]")

# plot the diagonal profile
imp = IJ.getImage()
IJ.run("Line Width...", "line=3")
IJ.makeLine(0, 0, imp.width, imp.height)
IJ.run("Plot Profile")

# bring back the projection, run Measure to get max and min
WM.putBehind()
IJ.run("Measure")  #this method reports the actual max and min, not averaged across 3 px...
rt = ResultsTable.getResultsTable()
max = rt.getValue("Max", 0)
min = rt.getValue("Min", 0)
rolloff = (min*1.0/max)*100

IJ.run("Fire")

IJ.log("Percent illumination roll-off: " + str(rolloff))

# close the annoying results window
IJ.run("Colors...","foreground=cyan background=cyan selection=yellow")
colDim = theImage.getWidth() / (xtiles)
rowDim = theImage.getHeight() / (ytiles)
rowStarts = range(rowDim,theImage.getHeight()-xtiles,rowDim)
colStarts = range(colDim,theImage.getWidth()-ytiles,colDim)
rowCenters = list(rowStarts)
rowCenters.insert(0,0)
colCenters = list(colStarts)
colCenters.insert(0,0)
for i in range(0,len(rowCenters)):
	rowCenters[i] = rowCenters[i] + rowDim - rowDim/8
for i in range(0,len(colCenters)):
	colCenters[i] = colCenters[i] + colDim/2

for i in rowStarts:
	IJ.makeLine(0,i,theImage.getWidth(),i)
	IJ.run("Draw","stack")
for i in colStarts:
	IJ.makeLine(i,0,i,theImage.getHeight())
	IJ.run("Draw","stack")

numSlices = theImage.getNSlices() * theImage.getNChannels() * theImage.getNFrames()
for zslice in range(1,numSlices+1):
	theImage.setSliceWithoutUpdate(zslice)
	ip = theImage.getProcessor()
	ip.setColor(255*255)
	for i in range(0,len(colCenters)):
		for j in range(0,len(rowCenters)):
			theString = str(int(j*xtiles+i+1))
			ip.drawString(theString,int(colCenters[i]),int(rowCenters[j]))
theImage.updateAndDraw()
Esempio n. 5
0
def makeLine(x1, y1, x2, y2):
    IJ.makeLine(x1, y1, x2, y2)
Esempio n. 6
0
def batch_open_images(pathImage, file_typeImage, name_filterImage=None):

    if isinstance(pathImage, File):
        pathImage = pathImage.getAbsolutePath()

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

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

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

    # We collect all files to open in a list.
    path_to_Image = []
    # Replacing some abbreviations (e.g. $HOME on Linux).
    path = os.path.expanduser(pathImage)
    path = os.path.expandvars(pathImage)
    # If we don't want a recursive search, we can use os.listdir().

    for directory, dir_names, file_names in os.walk(pathImage):
        # We are only interested in files.
        for file_name in file_names:
            # The list contains only the file names.
            # The full path needs to be reconstructed.
            full_path = os.path.join(directory, file_name)
            # Both checks are performed to filter the files.
            if check_type(file_name):
                if check_filter(file_name) is False:
                    # Add the file to the list of images to open.
                    path_to_Image.append([
                        full_path,
                        os.path.basename(os.path.splitext(full_path)[0])
                    ])
    Images = []

    for img_path, file_name in path_to_Image:

        imp = IJ.openImage(img_path)
        maskimage = ops.run("create.img", imp)
        cursor = maskimage.localizingCursor()
        imp.show()
        IJ.run("Select None")
        overlay = imp.getOverlay()
        if overlay == None:

            overlay = Overlay()
            imp.setOverlay(overlay)
        else:

            overlay.clear()

        imp.updateAndDraw()
        impY = imp.getHeight()
        impX = imp.getWidth()
        print(impY, impX)
        rm = RoiManager.getInstance()
        if not rm:
            rm = RoiManager()

        rm.runCommand("reset")
        WaitForUserDialog("Select the landmark and the second point").show()
        rm.runCommand("Add")
        roi_points = rm.getRoisAsArray()
        for Roi in roi_points:

            xpoints = Roi.getPolygon().xpoints
            ypoints = Roi.getPolygon().ypoints
            print(xpoints, ypoints)

        print('Start Landmark', xpoints[0], ypoints[0])
        fixedpointX = xpoints[0]
        fixedpointY = ypoints[0]
        print('End Landmark', xpoints[1], ypoints[1])
        IJ.makeLine(xpoints[0], ypoints[0], xpoints[1], ypoints[1])
        gui = GenericDialog("Rotation Angle")
        gui.addNumericField("Choose Angle", 15, 0)
        gui.showDialog()
        if gui.wasOKed():

            rotateangle = gui.getNextNumber()
            IJ.run("Rotate...", "angle=" + str(int(float(rotateangle))))

        rm.runCommand("reset")
        overlay = imp.getOverlay()
        rm.runCommand("Add")
        roi_points = rm.getRoisAsArray()

        for Roi in roi_points:
            xpoints = Roi.getPolygon().xpoints
            ypoints = Roi.getPolygon().ypoints
            print(xpoints, ypoints)

        print('Rotated Start Landmark', xpoints[0], ypoints[0])
        print('Rotated End Landmark', xpoints[1], ypoints[1])
        slope = (ypoints[1] - ypoints[0]) / (xpoints[1] - xpoints[0] + 1.0E-20)
        intercept = fixedpointY - slope * fixedpointX
        print(fixedpointX, fixedpointY)
        print('Slope', slope, 'Intercept', intercept)
        XwY0 = -intercept / slope
        YxwY0 = slope * XwY0 + intercept

        XwYmax = (impY - intercept) / slope
        YxwYmax = slope * XwYmax + intercept

        YwX0 = intercept
        XywX0 = (YwX0 - intercept) / slope
        YwXmax = impX * slope + intercept
        XxwXmax = (YwXmax - intercept) / slope
        rm.runCommand("reset")

        if XwY0 > 0:
            lineROIA = Line(fixedpointX, fixedpointY, XwY0, YxwY0)
            lineROIB = Line(fixedpointX, fixedpointY, XwYmax, YxwYmax)
            overlay.add(lineROIA)

            overlay.add(lineROIB)

        if XwY0 < 0:
            lineROIA = Line(fixedpointX, fixedpointY, XywX0, YwX0)
            lineROIB = Line(fixedpointX, fixedpointY, XxwXmax, YwXmax)
            overlay.add(lineROIA)

            overlay.add(lineROIB)

        while cursor.hasNext():
            cursor.fwd()
            X = cursor.getDoublePosition(0)
            Y = cursor.getDoublePosition(1)
            if abs(Y - slope * X - intercept) <= 4:
                cursor.get().set(0)
            else:
                cursor.get().set(1)
        labeling = ops.labeling().cca(maskimage,
                                      StructuringElement.EIGHT_CONNECTED)

        # get the index image (each object will have a unique gray level)
        labelingIndex = labeling.getIndexImg()
        dataImg = ds.create(labelingIndex)
        location = ls.resolve(
            str(savedir) + '/' + file_name + '.' + file_type_image)
        dio.save(dataImg, location)
        imp.close()
Esempio n. 7
0
from ij import IJ
from ij.plugin.frame import RoiManager

RM = RoiManager()
rm = RM.getRoiManager()

with open(
        "C:/Users/emlh1n13/Downloads/Coronary Sinus/Case2_View2_F15/ROIs.csv",
        "r") as roiFile:
    next(roiFile)  # skip header
    for line in roiFile:
        elements = line.rstrip().split(',')
        x, y, w, h = elements[4], elements[5], elements[6], elements[7]
        x1 = int(x)
        y1 = int(y)
        x2 = x1 + int(w)
        y2 = y1 + int(h)
        roi = IJ.makeLine(x1, y1, x2, y2)
        rm.addRoi(roi)
	gd.addCheckbox("First segment is injury?",injuryfirst)
	gd.showDialog()

	if (gd.wasOKed()):
		roi = theImage.getRoi()
		if roi is None:
			IJ.error("No ROI selected")
		else:		
			polygon = roi.getFloatPolygon()

			# if len(polygon.xpoints) % 2 == 0 and is_monotonic_increasing(polygon.ypoints):
			if is_monotonic_increasing(polygon.ypoints):
				xset = average(polygon.xpoints)
				IJ.setForegroundColor(255,255,0)
				IJ.run("Draw","stack")
				IJ.makeLine(xset,0,xset,theImage.getHeight())
				IJ.setForegroundColor(0,255,255)
				IJ.run("Draw","stack")

				injuryfirst = gd.getNextBoolean()
				if injuryfirst:
					countidx = range(0,len(polygon.xpoints)-1,2)
				else:
					countidx = range(1,len(polygon.xpoints)-1,2)

				injuryLength = 0.0
				for idx in countidx:
					injuryLength = injuryLength + (polygon.ypoints[idx+1]-polygon.ypoints[idx])
				totalLength = polygon.ypoints[-1]-polygon.ypoints[0]
				injuryRatio = injuryLength / totalLength