def measure_growth(imgDir, filename = "Fiji_Growth.txt"):
    """ Collects measurement data in pixels and writes to a file. Uses straightened binary images"""
    f = open(imgDir + filename, 'w')
    f.write("Img number\tEnd point (pixels)\n")
    IJ.run("Set Measurements...", "area mean min center redirect=None decimal=3")
    index = "000000000"
    filename = imgDir + "/binary" + "/img_" + index + "__000-padded.tif"
    while path.exists(filename):
		imp = IJ.openImage(filename)
		imp.show()
		IJ.run("Clear Results")
		for i in xrange(800): #hard coded to target length for now
			IJ.makeRectangle(i, 0, 1, 80)
			IJ.run("Measure")
			table = RT.getResultsTable()
			#print "i:", i, "counter:", table.getCounter()
			maxi = RT.getValue(table, "Max", i)
			if maxi == 0:
				f.write(str(int(index)) + "\t" + str(i) + "\n")
				break

		IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")
		index = to_9_Digits(str(int(index)+1))
		filename = imgDir + "/padded" + "/img_" + index + "__000-padded.tif"
    f.close()
def cropImage(imp, x0, y0, w, h, bTest=False):
	"""cropImage(imp, x0, y0, w, h, bTest=False)
	
	Crop an image from a duplicate and return the ImagePlus of the cropped image
	
	Parameters
	----------
	imp: ImagePlus
		The image to be cropped
	x0: number
		The x coordinate to begin drawing the crop rectangle
	y0: number
		The x coordinate to begin drawing the crop rectangle
	w: number
		The width in pixels for the box
	h: number
		The height in pixels for the box		
	bTest: Boolean (False)
		If True, just draw the rectangle

	Returns
	-------
	ret: ImagePlus
		The cropped image
	"""
	IJ.run("Colors...", "foreground=black background=black selection=green")
	IJ.makeRectangle(x0, y0, w, h)
	if(bTest==True):
		return
	else:
		ret = imp.crop()
		return ret
def measure_growth(imgDir, filename="Fiji_Growth.txt"):
    """ Collects measurement data in pixels and writes to a file. Uses straightened binary images"""
    f = open(imgDir + filename, 'w')
    f.write("Img number\tEnd point (pixels)\n")
    IJ.run("Set Measurements...",
           "area mean min center redirect=None decimal=3")
    index = "000000000"
    filename = imgDir + "/binary" + "/img_" + index + "__000-padded.tif"
    while path.exists(filename):
        imp = IJ.openImage(filename)
        imp.show()
        IJ.run("Clear Results")
        for i in xrange(800):  #hard coded to target length for now
            IJ.makeRectangle(i, 0, 1, 80)
            IJ.run("Measure")
            table = RT.getResultsTable()
            #print "i:", i, "counter:", table.getCounter()
            maxi = RT.getValue(table, "Max", i)
            if maxi == 0:
                f.write(str(int(index)) + "\t" + str(i) + "\n")
                break

        IJ.runMacro("while (nImages>0) {selectImage(nImages);close();}")
        index = to_9_Digits(str(int(index) + 1))
        filename = imgDir + "/padded" + "/img_" + index + "__000-padded.tif"
    f.close()
def run_straighten(roiWindowsize = 4):
    """ Original straightening function based on Nick's macro. Used in final version.
    Returns coordinate string used to make centerline. """
    IJ.run("Set Measurements...", "mean min center redirect=None decimal=3")
    IJ.runMacro("//setTool(\"freeline\");")
    IJ.run("Line Width...", "line=80");
    numPoints = 512/roiWindowsize
    xvals = []
    yvals = []
    maxvals = []
    counter = 0

    for i in range(0, 512, roiWindowsize):
        IJ.run("Clear Results")
        IJ.makeRectangle(i, 0, roiWindowsize, 512)
        IJ.run("Measure")
        table = RT.getResultsTable()
        xvals.append(i + roiWindowsize/2)
        yvals.append(RT.getValue(table, "YM", 0))
        maxvals.append((RT.getValue(table, "Max", 0)))

        if maxvals[counter] == 0 and counter > 0:
            yvals[counter] = yvals[counter - 1]

        counter += 1

    coords = ""
    for i in range(numPoints - 1):
        coords += str(xvals[i]) + ", " + str(yvals[i]) +", "
    coords += str(xvals[numPoints-1]) + ", " + str(yvals[numPoints-1])

    IJ.runMacro("makeLine("+coords+")")
    IJ.run("Straighten...", "line = 80")
    return coords
def run_straighten(roiWindowsize=4):
    """ Original straightening function based on Nick's macro. Used in final version.
    Returns coordinate string used to make centerline. """
    IJ.run("Set Measurements...", "mean min center redirect=None decimal=3")
    IJ.runMacro("//setTool(\"freeline\");")
    IJ.run("Line Width...", "line=80")
    numPoints = 512 / roiWindowsize
    xvals = []
    yvals = []
    maxvals = []
    counter = 0

    for i in range(0, 512, roiWindowsize):
        IJ.run("Clear Results")
        IJ.makeRectangle(i, 0, roiWindowsize, 512)
        IJ.run("Measure")
        table = RT.getResultsTable()
        xvals.append(i + roiWindowsize / 2)
        yvals.append(RT.getValue(table, "YM", 0))
        maxvals.append((RT.getValue(table, "Max", 0)))

        if maxvals[counter] == 0 and counter > 0:
            yvals[counter] = yvals[counter - 1]

        counter += 1

    coords = ""
    for i in range(numPoints - 1):
        coords += str(xvals[i]) + ", " + str(yvals[i]) + ", "
    coords += str(xvals[numPoints - 1]) + ", " + str(yvals[numPoints - 1])

    IJ.runMacro("makeLine(" + coords + ")")
    IJ.run("Straighten...", "line = 80")
    return coords
Example #6
0
def getFlipArray(maskPAImgPlus):
    """Given the PA-aligned mask image, return a list of booleans, indicating whether or not we should flip the corresponding index"""
    maskPAImgPlus.show()
    #	IJ.run(maskPAImgPlus, "Shape Smoothing", "relative_proportion_fds=15 absolute_number_fds=2 keep=[Relative_proportion of FDs] stack");

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

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

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

    IJ.resetThreshold(maskPAImgPlus)

    leftCirc = [tableLeft.getValue("Circ.", i) for i in range(stk.getSize())]
    rightCirc = [tableRight.getValue("Circ.", i) for i in range(stk.getSize())]
    return [leftCirc[i] < rightCirc[i] for i in range(len(leftCirc))]
def draw_bounding_boxes(objects,title,templateImage):
	drawnIp = ByteProcessor(templateImage.getWidth(),templateImage.getHeight())
	drawnImage = ImagePlus(title,drawnIp)
	drawnImage.show()
	IJ.selectWindow(title)
	for j in range(len(objects)):
		IJ.makeRectangle(objects[j][42],objects[j][43],objects[j][45]-objects[j][42],objects[j][46]-objects[j][43])
		IJ.run("Draw","stack")
	drawnImage.hide()
	return(drawnImage)
    def __init__(self, imp, center = (0,0), width = 0, height = 0, tilt = 0):
       	#self.RoiM = RoiManager()
        self.imp = imp
        self.center = center
        self.width = width
        self.height = height
        self.tilt = tilt
        self.dTheta = 0
        print self.center

        self.roi = IJ.makeRectangle(center[0] - width/2, center[1] - height/2, width, height)
    def __init__(self, imp, center=(0, 0), width=0, height=0, tilt=0):
        #self.RoiM = RoiManager()
        self.imp = imp
        self.center = center
        self.width = width
        self.height = height
        self.tilt = tilt
        self.dTheta = 0
        print self.center

        self.roi = IJ.makeRectangle(center[0] - width / 2,
                                    center[1] - height / 2, width, height)
Example #10
0
def prepareImage(passDir, passFile, passOutput, passPixels, passBlur, passThreshold):
	# Attempt to open as image, exit if not
	fullPath = os.path.join(passDir, passFile)
	retImage = IJ.openImage(fullPath)
	if not retImage: return None
	retImage.show()

	# Resize canvas to prepare for fast rotations, select original
	imgWidth = retImage.getWidth()
	imgHeight = retImage.getHeight()
	maxDim = math.sqrt(imgWidth ** 2 + imgHeight ** 2)
	borderX = (maxDim - imgWidth)/2
	borderY = (maxDim - imgHeight)/2
	
	IJ.run("Canvas Size...", "width={0} height={0} position=Center".format(maxDim))
	IJ.makeRectangle(borderX, borderY, imgWidth, imgHeight) 

	# Set scale to pixels (will manually calculate later)
	IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");

	# Blur "overhanging" projections
	IJ.run("Gaussian Blur...", "sigma={0}".format(passBlur))
	
	# Set threshold 
	IJ.setAutoThreshold(retImage, "{0} dark apply".format(passThreshold))
	IJ.makeRectangle(0, 0, retImage.getWidth(), retImage.getHeight()) 
		
	# Analyze particles and obtain outline image
	IJ.run("Analyze Particles...", "size={0}-Infinity show=Outlines pixel clear".format(passPixels));
	IJ.selectWindow("Drawing of {0}".format(retImage.getTitle()))
	
	fileParts = passFile.split(".")
	IJ.save(os.path.join(passOutput, "{0}-outline-{1}.{2}".format(fileParts[0], passThreshold, '.'.join(fileParts[1:]))))
	IJ.run("Close")

	return retImage
Example #11
0
for i in range(1, n_slicesa + 1):
    imp.setSlice(i)
    n = imp.getProcessor().getPixels()
    n2 = [int(val) for val in n]
    L.append(n2)
imp.changes = False
imp.close()

#get initial dictionary D and construct matrix
imp2 = IJ.getImage()
IJ.run("Enhance Contrast...", "saturated=0 normalize process_all use")
IJ.run("Multiply...", "value=" + str(500) + " stack")
#IJ.run("Add...", "value="+str(10)+" stack")
n_slices = imp2.getStack().getSize()
X = []
for i in range(1, n_slices + 1):
    imp2.setSlice(i)
    n = imp2.getProcessor().getPixels()
    n2 = [val for val in n]
    X.append(n2)

IJ.newImage("Untitled", "RGB white", 512, 512, 1)
IJ.run("Select All")
IJ.setForegroundColor(bc, bc, bc)
IJ.run("Fill", "slice")
imp3 = IJ.getImage()

for i in range(0, len(X[0])):
    IJ.makeRectangle(X[0][i] + 4, X[1][i] + 4, px, px)
    IJ.setForegroundColor(L[0][i], L[1][i], L[2][i])
    IJ.run("Fill", "slice")
Example #12
0
                  anno_width, anno_height, t_a + t_b + t_c)

# Add leading texts
labelTextAll(start=0, interval=1, x=10, y=40, fontsize=36,
             text='[Flow:L--->R]')

# Add timestamps for each segment
x_ts, y_ts, fs_ts = 325, 30, 36  # x, y, and font_size
labelTimestamps(start=0, interval=sample_rate,
                x=x_ts, y=y_ts, fontsize=fs_ts,
                range0=1, range1=t_a)
labelTimestamps(start=int(t0_b - t0_a), interval=sample_rate,
                x=x_ts, y=y_ts, fontsize=fs_ts,
                range0=(t_a + 1), range1=(t_a + t_b))
labelTimestamps(start=int(t0_c - t0_a), interval=sample_rate,
                x=x_ts, y=y_ts, fontsize=fs_ts,
                range0=(t_a + t_b + 1), range1=(t_a + t_b + t_c))

# Add scale bar
labelTextAll(start=0, interval=1, x=700, y=20, fontsize=36,
             text=(str(sbar_um) + um))
IJ.setBackgroundColor(255, 255, 255)
for i in range(1, t_a + t_b + t_c + 1):
    IJ.setSlice(i)
    IJ.makeRectangle(anno_width - 120 - sbar_px, 14, sbar_px, 16)
    IJ.run('Cut')

# Save annotation banner
path = SaveDialog(title, title, '.tif').getDirectory()
IJ.run('Save', 'save=[' + path + title + ']')
# makeBoxForCrop.py
# A script to crop a series of images
#  Modifications
#   Date      Who  Ver                       What
# ----------  --- ------  -------------------------------------------------
# 2015-09-03  JRM 0.1.00  Initial prototype

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

imp = IJ.getImage()

x0 = 0
y0 = 200
wd = imp.getWidth()
ht = 340;

IJ.run("Colors...", "foreground=black background=black selection=green");
IJ.makeRectangle(x0, y0, wd, ht);
Example #14
0
def makeRectangle(x, y, w, h, centered=True):
    if centered:
        x = x - w / 2
        y = y - h / 2
    IJ.makeRectangle(x, y, w, h)
Example #15
0
                 "Scale...", "x=0.1 y=0.1 width=" + str(im.width / 10) +
                 " height=" + str(im.width / 10) +
                 " interpolation=Bilinear average create")
             im_10 = IJ.getImage()
             savefile(im_10,
                      os.path.join(downsample_subdir, fileoutname),
                      plugin,
                      compress=compress)
             IJ.run("Close All")
             im = IJ.open(os.path.join(out_subdir, fileoutname))
             im = IJ.getImage()
             for eachxtile in range(tileperside):
                 for eachytile in range(tileperside):
                     each_tile_num = eachxtile * tileperside + eachytile + 1
                     IJ.makeRectangle(eachxtile * tilesize,
                                      eachytile * tilesize, tilesize,
                                      tilesize)
                     im_tile = im.crop()
                     savefile(im_tile,
                              os.path.join(
                                  tile_subdir_persuf, thissuffixnicename +
                                  '_Site_' + str(each_tile_num) + '.tiff'),
                              plugin,
                              compress=compress)
             IJ.run("Close All")
 elif round_or_square == 'round':
     if imperwell == '1364':
         row_widths = [
             8, 14, 18, 22, 26, 28, 30, 32, 34, 34, 36, 36, 38, 38, 40, 40,
             40, 42, 42, 42, 42, 42, 42, 42, 42, 40, 40, 40, 38, 38, 36, 36,
             34, 34, 32, 30, 28, 26, 22, 18, 14, 8
__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]
y1 = 0
y2 = 470
newPixels = map(lambda x: (x - stats.min)/delta, pixels)
ipSub = FloatProcessor(ip.width, ip.height, newPixels, None)
impSub = ImagePlus("Sub", ipSub)
impSub.show()
IJ.selectWindow("Result")
IJ.run("Close")
IJ.selectWindow("Sub")
imp=WM.getCurrentImage()
imp.setTitle(strName+"-acf")
imp.show()

centX = ip.width/2
centY = ip.height/2
top = centX-halfWidth
left = centY-halfWidth
IJ.makeRectangle(top,left,2*halfWidth,2*halfWidth)
IJ.run("Crop")
IJ.setThreshold(0.65, 1.00)
Analyzer.setOption("BlackBackground", False)
if bMakeBinary:
  IJ.run("Make Binary")
  IJ.run("Convert to Mask")
  IJ.run("Set Measurements...", "area centroid redirect=None decimal=3")
  IJ.run("Analyze Particles...", "display exclude clear include")
  rt = ResultsTable.getResultsTable()
  nMeas = rt.getCounter()
  print(nMeas)
  cntX  = rt.getColumn(ResultsTable.X_CENTROID)
  cntY  = rt.getColumn(ResultsTable.Y_CENTROID)
  cntA  = rt.getColumn(ResultsTable.AREA)
  # find the center - will be closest to half width
from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')

import os
import jmFijiGen as jmg
from ij import IJ
from ij import WindowManager

imgDir  = os.environ['IMG_ROOT']
relImg  = "/test/efi-test/bez-50X-1/out"
strImg = imgDir + relImg + "/bez-50X-1-ij-edf-sc.tif"

# 1. Open an image
impExp = IJ.openImage(strImg)
impExp.show()

# 2. Add a rectangle for white balance
IJ.makeRectangle(0, 190, 1600, 260)

# 3. Do the work
jmg.whiteBalance(impExp, bVerbose=True)

# 4. save the results
out = WindowManager.getCurrentImage()
name = out.getShortTitle()
strImg = imgDir + relImg + "/" + name + ".tif"
IJ.saveAs("Tiff", strImg)