Example #1
0
def keep_blobs_bigger_than(imp, min_size_pix=100):
    """remove all blobs other than the largest by area"""
    imp.killRoi()
    rt = ResultsTable()
    if "Size_filtered_" in imp.getTitle():
        title_addition = ""
    else:
        title_addition = "Size_filtered_"
    out_imp = IJ.createImage("{}{}".format(title_addition, 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")
    mxsz = imp.width * imp.height
    roim = RoiManager()
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                          ParticleAnalyzer.AREA | ParticleAnalyzer.SLICE, rt,
                          min_size_pix, mxsz)
    pa.setRoiManager(roim)
    roim.reset()
    rt.reset()
    pa.analyze(imp)
    rt_areas = rt.getColumn(rt.getColumnIndex("Area")).tolist()
    #	print("Number of cells identified: {}".format(len(rt_areas)));
    for idx in range(len(rt_areas)):
        roim.select(out_imp, idx)
        IJ.run(out_imp, "Set...", "value=255 slice")
    mx_ind = rt_areas.index(max(rt_areas))
    roim.reset()
    roim.close()
    imp.changes = False
    imp.close()
    return out_imp
import time
import gc
from ij.plugin.frame import RoiManager

from ij.gui import Roi




def segVOI_image_series(folder_in,folder_out,filepath_labels,x_len,y_len):
    """
    Segment VOIs of a 3D image where whole 3D image series and slices which contain VOIs are given
    """
	
	file_names,rows = getLabels(filepath_labels)
	for i in range(len(file_names)):
		imp = IJ.openImage(os.path.join(folder_in, file_names[i]))
		print(os.path.join(folder_in, file_names[i]))
		stack = imp.getImageStack()
		stack2 = ImageStack(imp.width,imp.height)
		blankim = IJ.createImage("blank", "8-bit black", imp.width, imp.height, 1)
		ipb= blankim.getProcessor()	
		for j in range(imp.getNSlices()):
			if rows[j][i]== '0':
				ip = stack.getProcessor(j+1)
				#NormalizeLocalContrast.run(ip, 341, 326, 4, True, True)
				imagep = ImagePlus("imp",ip)
				IJ.run(imagep, "Non-local Means Denoising", "sigma=10 smoothing_factor=1 slice")
				imagep.setRoi(1,1,x_len,y_len);
				IJ.run(imagep, "Level Sets", "method=[Active Contours] use_level_sets grey_value_threshold=50 distance_threshold=0.50 advection=2.20 propagation=1 curvature=1 grayscale=30 convergence=0.03 region=inside")
				fimp = IJ.getImage()
				#fip  = fimp.getProcessor()
				fimp = removeSmallCCs(fimp)
Example #3
0
def DrawLandmarks(imp, pos, img_type):
	cal = imp.getCalibration()
	pixel_width  = cal.pixelWidth
	pixel_height = cal.pixelHeight
	pixel_depth  = cal.pixelDepth
	bit_depth = imp.getBitDepth()
	(width,height,n_channels,n_slices,n_frames) = imp.getDimensions()

	radius = 1 # microns
#
	range_XY = radius / pixel_width
#	range_Z  = radius / pixel_depth
	on_val = 2**bit_depth - 1
	imp_landmarks = IJ.createImage("Landmarks",width,height,n_slices,bit_depth)
	imp_landmarks.setCalibration(cal)
	stack = imp_landmarks.getImageStack()

	for landmark in range(len(pos)):
		# Get x,y,z in pixels
		pX = int(round(pos[landmark][0]/pixel_width))
		pY = int(round(pos[landmark][1]/pixel_height))
		pZ = int(round(pos[landmark][2]/pixel_depth))

		print(pX,pY,pZ)
		ip = stack.getProcessor(pZ+1)
		for x in range(pX-radius,pX+radius+1):
			for y in range(pY-radius,pY+radius+1):
#				print("Putting %d at (%d,%d,%d)"%(on_val,x,y,pZ))
#				if (((x-pX)**2 + (y-pY)**2) <= radius**2):
				ip.putPixel(x,y,on_val)
	imp_landmarks.setTitle(img_type)
	imp_landmarks.updateAndDraw()
	imp_landmarks.show()
def run():
    roidir = '/Volumes/TRANSCEND/LauraLeopold/Rois/'
    maskdir = '/Volumes/TRANSCEND/LauraLeopold/Mask/'
    originaldir = '/Volumes/TRANSCEND/LauraLeopold/Original/'
    Raw_path = os.path.join(originaldir, '*tif')
    X = glob.glob(Raw_path)
    axes = 'YX'
    for fname in X:
        print(fname)
        IJ.open(fname)
        imp = IJ.getImage()
        Name = os.path.basename(os.path.splitext(fname)[0])
        RoiName = roidir + Name + '.roi'
        Roi = IJ.open(RoiName)
        rm = RoiManager.getInstance()
        if (rm == None):
            rm = RoiManager()
        rm.addRoi(Roi)
        print(fname, RoiName)
        if not rm:
            print "Please first add some ROIs to the ROI Manager"
            return
        impMask = IJ.createImage("Mask", "8-bit grayscale-mode",
                                 imp.getWidth(), imp.getHeight(),
                                 imp.getNChannels(), imp.getNSlices(),
                                 imp.getNFrames())
        IJ.setForegroundColor(255, 255, 255)
        rm.runCommand(impMask, "Deselect")
        rm.runCommand(impMask, "Fill")
        rm.runCommand('Delete')
        IJ.saveAs(impMask, '.tif', maskdir + Name)
        imp.close()
def generateModel(stk, R, val):
    """ Generation optical model
	"""
    (sx, sy, sz) = stackSize(stk)
    # Initialize correction output and temporary OPL
    cor = IJ.createImage("Correction", "32-bit black", sx, sy, sz)
    corstk = cor.getStack()
    OPL = 0 * [len(val)]
    OPL = [0 for i in range(len(val))]

    lastOPL = OPL

    for xx in range(sx):
        for yy in range(sy):
            sub = stk.getVoxels(xx, yy, 0, 1, 1, sz, [])
            for zz in range(sz):
                for ii in range(len(val)):
                    if sub[zz] == val[ii]:
                        if zz >= 1:
                            OPL[ii] = lastOPL[ii] + 1
                        else:
                            OPL[ii] = 1
                    else:
                        if zz >= 1:
                            OPL[ii] = lastOPL[ii]
                        else:
                            OPL[ii] = 0
                    lastOPL[ii] = OPL[ii]
                vv = f(OPL, R)
                corstk.setVoxel(xx, yy, zz, vv)
        IJ.showProgress(xx, sx)

    return cor
Example #6
0
 def _create_simple_images(self, count):
     width, height = self.dim_simple
     ref = IJ.createImage('Ref', '32-bit black', width, height, 1)
     self._create_rect_and_noise(ref, self.roi_simple)
     self.images.append(ref)
     IJ.showProgress(1 / count)
     from random import randint
     for i in range(2, count + 1):
         roi_off = list(self.roi_simple[:])
         roi_off[0] = randint(0.5 * self.roi_simple[0], 1.5 * self.roi_simple[0])
         roi_off[1] = randint(0.5 * self.roi_simple[0], 1.5 * self.roi_simple[0])
         imp = IJ.createImage('Img', '32-bit black', width, height, 1)
         self._create_rect_and_noise(imp, roi_off)
         imp.setTitle('%d,%d' % (roi_off[0] - self.roi_simple[0],
                                 roi_off[1] - self.roi_simple[1]
                                ))
         self.images.append(imp)
         IJ.showProgress(i / count)
Example #7
0
def run_script():
    # We can use import inside of code blocks to limit the scope.
    import math
    from ij import IJ, ImagePlus
    from ij.process import FloatProcessor
    blank = IJ.createImage("Blank", "32-bit black", img_size, img_size, 1)
    # This create a list of lists. Each inner list represents a line.
    # pixel_matrix[0] is the first line where y=0.
    pixel_matrix = split_list(blank.getProcessor().getPixels(),
                              wanted_parts=img_size)
    # This swaps x and y coordinates.
    # http://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python
    # As zip() creates tuples, we have to convert each one by using list().
    pixel_matrix = [list(x) for x in zip(*pixel_matrix)]
    for y in range(img_size):
        for x in range(img_size):
            # This function oszillates between 0 and 1.
            # The distance of 2 maxima in a row/column is given by spacing.
            val = (0.5 * (math.cos(2 * math.pi / spacing * x) +
                          math.sin(2 * math.pi / spacing * y)))**2
            # When assigning, we multiply the value by the amplitude.
            pixel_matrix[x][y] = amplitude * val
    # The constructor of FloatProcessor works fine with a 2D Python list.
    crystal = ImagePlus("Crystal", FloatProcessor(pixel_matrix))
    # Crop without selection is used to duplicate an image.
    crystal_with_noise = crystal.crop()
    crystal_with_noise.setTitle("Crystal with noise")
    IJ.run(crystal_with_noise, "Add Specified Noise...",
           "standard=%d" % int(amplitude / math.sqrt(2)))
    # As this is a demo, we don't want to be ask to save an image on closing it.
    # In Python True and False start with capital letters.
    crystal_with_noise.changes = False
    crystal.show()
    crystal_with_noise.show()
    filtered = fft_filter(crystal_with_noise)
    # We create a lambda function to be used as a parameter of img_calc().
    subtract = lambda values: values[0] - values[1]
    # This is a short form for:
    # def subtract(values):
    #   return values[0] - values[1]

    # The first time we call img_calc with 2 images.
    difference = img_calc(subtract, crystal, filtered, title="Difference of 2")
    difference.show()
    # The first time we call img_calc with 3 images.
    minimum = img_calc(min,
                       crystal,
                       filtered,
                       crystal_with_noise,
                       title="Minimum of 3")
    minimum.show()
    for imp in (crystal, crystal_with_noise, filtered, difference, minimum):
        IJ.run(imp, "Measure", "")
Example #8
0
def run():
    rm = RoiManager.getInstance()
    if not rm:
        print "Please first add some ROIs to the ROI Manager"
        return
    impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(),
                             imp.getHeight(), imp.getNChannels(),
                             imp.getNSlices(), imp.getNFrames())
    IJ.setForegroundColor(255, 255, 255)
    rm.runCommand(impMask, "Deselect")
    rm.runCommand(impMask, "Fill")
    impMask.show()
Example #9
0
def create_test_image():
    # Python uses indentation to create code blocks

    # Local variables are assigned.
    # We can assign the same value to more than one variable.
    image_width = image_height = 512
    box_width = box_height = 128
    offset_x = offset_y = 192
    counts = 64
    stdv = 16
    # The build in function int() is used to convert float to int.
    # The variable random contains a function that is called by adding parentheses.
    offset_x = int(2 * random() * offset_x)
    offset_y = int(2 * random() * offset_y)

    # We can define a function inside a function.
    # Outside of create_test_image() this function is not available.
    # By adding an asterisk to a parameter, all given parameters are combined to a tuple.
    def make_title(*to_concat):
        prefix = 'TestImage'
        # To create a tuple with a single entry the comma is necessary.
        # The 2 tuples are concatenated by using the + operator.
        to_join = (prefix, ) + to_concat
        # We create a generator that converts every singe entry of the tuple to a string.
        strings_to_join = (str(arg) for arg in to_join)
        # The string ',' has a join method to concatenate values of a tuple with the string as seperator.
        # The result is a string.
        return ','.join(strings_to_join)

    def check_existence(title):
        if WindowManager.getIDList() is None:
            return False
        image_titles = (WindowManager.getImage(id).getTitle()
                        for id in WindowManager.getIDList())
        return title in image_titles

    # To negate an expression put not in front of it.
    if not check_existence(make_title(offset_x, offset_y)):
        # The following code has been created by using the Recorder of ImageJ, set to output Java code.
        # By removing the semicolons, the code can be used in Jython.
        # The parameters can be modified by using variables and string concatenation.
        imp = IJ.createImage(make_title(offset_x, offset_y), "8-bit black",
                             image_width, image_height, 1)
        # The build in function str() is used to convert int to string.
        IJ.run(imp, "Add...", "value=" + str(counts))
        imp.setRoi(offset_x, offset_y, box_width, box_height)
        IJ.run(imp, "Add...", "value=" + str(counts))
        IJ.run(imp, "Select None", "")
        IJ.run(imp, "Add Specified Noise...", "standard=" + str(stdv))
        # We don't want to confirm when closing one of the newly created images.
        imp.changes = False
        imp.show()
Example #10
0
def extend_image(image):
    IJ.run(image, "Select All", "")
    IJ.run(image, "Copy", "")
    width = image.getWidth()
    height = int(image.getHeight() + extend)
    image_new = IJ.createImage(imp.getTitle(), "32-bit black", width, height, 1)
    image_new.setRoi(0, 0, image.getWidth(), image.getHeight())
    IJ.run(image_new, "Paste", "")
    IJ.run(image_new, "Enhance Contrast", "saturated=0.35")
    IJ.run(image_new, "Select None", "")
    cal = Calibration(image)
    cal.pixelWidth = dispersion
    cal.xOrigin = offset
    image_new.setCalibration(cal)
    return image_new
Example #11
0
 def do_ellipse_testing(self, imw, imh, centre, angle, axl):
     """Utility function to provide test ellipse data"""
     imp = IJ.createImage("test", imw, imh, 1, 8)
     imp.show()
     roi = ellipse_fitting.generate_ellipse_roi(centre, angle, axl)
     imp.setRoi(roi)
     IJ.run(imp, "Set...", "value=128")
     IJ.setThreshold(imp, 1, 255)
     IJ.run(imp, "Convert to Mask", "method=Default background=Dark list")
     IJ.run(imp, "Outline", "stack")
     IJ.run(imp, "Create Selection", "")
     roi = imp.getRoi()
     pts = [(pt.x, pt.y) for pt in roi.getContainedPoints()]
     imp.changes = False
     imp.close()
     return pts
Example #12
0
def stack(img1_path, img2_path):
	imp = IJ.createImage("A Random Image", "8-bit", 512, 512, 0) 
	'''IJ.run(img2,"MultiStackReg", "stack_1=["+img2_path+"]"
	+" action_1=[Use as Reference] file_1=["+img2_path+"]"+
	" stack_2=["+img1_path+"]"
	" action_2=[Align to First Stack]"+
	" file_2=["+img1_path+"] transformation=[Rigid Body]");
	'''
	IJ.run(img1,"MultiStackReg", 
	"stack_1=["+img2_path+"]"
	+ " action_1=[Use as Reference]"
	+ " file_1=["+img2_path+"]"
	+ " stack_2=["+img1_path+"]"
	+ " action_2=[Align to First Stack]"
	+ " file_2=["+img1_path+"]"
	+ " transformation=[Rigid Body]");
def create_test_image():
    # Python uses indentation to create code blocks
 
    # Local variables are assigned.
    # We can assign the same value to more than one variable.
    image_width = image_height = 512
    box_width = box_height = 128
    offset_x = offset_y = 192
    counts = 64
    stdv = 16 
    # The build in function int() is used to convert float to int.
    # The variable random contains a function that is called by adding parentheses.
    offset_x = int(2 * random() * offset_x)
    offset_y = int(2 * random() * offset_y)
    # We can define a function inside a function.
    # Outside of create_test_image() this function is not available.
    # By adding an asterisk to a parameter, all given parameters are combined to a tuple.
    def make_title(*to_concat):
        prefix = 'TestImage'
        # To create a tuple with a single entry the comma is necessary.
        # The 2 tuples are concatenated by using the + operator.
        to_join = (prefix,) + to_concat
        # We create a generator that converts every singe entry of the tuple to a string.
        strings_to_join = (str(arg) for arg in to_join)
        # The string ',' has a join method to concatenate values of a tuple with the string as seperator. 
        # The result is a string.
        return ','.join(strings_to_join)
    def check_existence(title):
        if WindowManager.getIDList() is None:
            return False
        image_titles = (WindowManager.getImage(id).getTitle() for id in WindowManager.getIDList())
        return title in image_titles
    # To negate an expression put not in front of it.
    if not check_existence(make_title(offset_x, offset_y)):
        # The following code has been created by using the Recorder of ImageJ, set to output Java code.
        # By removing the semicolons, the code can be used in Jython.
        # The parameters can be modified by using variables and string concatenation.
        imp = IJ.createImage(make_title(offset_x, offset_y), "8-bit black", image_width, image_height, 1)
        # The build in function str() is used to convert int to string.
        IJ.run(imp, "Add...", "value=" + str(counts))
        imp.setRoi(offset_x , offset_y, box_width, box_height)
        IJ.run(imp, "Add...", "value=" + str(counts))
        IJ.run(imp, "Select None", "")
        IJ.run(imp, "Add Specified Noise...", "standard=" + str(stdv));
        # We don't want to confirm when closing one of the newly created images.
        imp.changes = False
        imp.show()
Example #14
0
def get_no_nuclei_fully_enclosed(roi, full_nuclei_imp, overlap_threshold=0.65):
    """for a given cell roi and ImagePlus with binary nuclei, return how many nuclei lie ENTIRELY within the cell"""
    bbox = roi.getBounds()
    full_nuclei_imp.setRoi(roi)
    cropped_nuc_imp = full_nuclei_imp.crop()
    roi.setLocation(0, 0)
    cropped_nuc_imp.setRoi(roi)
    cropped_nuc_imp.killRoi()
    roim = RoiManager(False)
    mxsz = cropped_nuc_imp.getWidth() * cropped_nuc_imp.getHeight()
    pa = ParticleAnalyzer(
        ParticleAnalyzer.ADD_TO_MANAGER, ParticleAnalyzer.AREA
        | ParticleAnalyzer.SLICE | ParticleAnalyzer.CENTROID, None, 0, mxsz)
    pa.setRoiManager(roim)
    pa.analyze(cropped_nuc_imp)
    cell_imp = IJ.createImage("Cell binary", cropped_nuc_imp.getWidth(),
                              cropped_nuc_imp.getHeight(), 1, 8)
    IJ.run(cell_imp, "Select All", "")
    IJ.run(cell_imp, "Set...", "value=0 slice")
    cell_imp.setRoi(roi)
    IJ.run(cell_imp, "Set...", "value=255 slice")
    no_enclosed_nuclei = 0
    for idx, nuc_roi in enumerate(roim.getRoisAsArray()):
        test_imp = Duplicator().run(cell_imp)
        test_imp.setRoi(nuc_roi)
        IJ.run(test_imp, "Set...", "value=255 slice")
        test_imp.killRoi()
        IJ.run(test_imp, "Create Selection", "")
        IJ.run(test_imp, "Make Inverse", "")
        test_roi = test_imp.getRoi()
        test_roi_stats = test_roi.getStatistics()
        cell_roi_stats = roi.getStatistics()
        nuc_roi_stats = nuc_roi.getStatistics()
        if test_roi_stats.area < (
                cell_roi_stats.area +
            (1 - overlap_threshold) * nuc_roi_stats.area
        ):  # i.e. if more than (100*overlap_threshold)% of nucleus is inside cell...
            no_enclosed_nuclei += 1
        test_imp.changes = False
        test_imp.close()
    roi.setLocation(bbox.getX(), bbox.getY())
    cropped_nuc_imp.changes = False
    cropped_nuc_imp.close()
    cell_imp.changes = False
    cell_imp.close()
    return no_enclosed_nuclei
def run_script():
    # We can use import inside of code blocks to limit the scope.
    import math
    from ij import IJ, ImagePlus
    from ij.process import FloatProcessor
    blank = IJ.createImage("Blank", "32-bit black", img_size, img_size, 1)
    # This create a list of lists. Each inner list represents a line.
    # pixel_matrix[0] is the first line where y=0.
    pixel_matrix = split_list(blank.getProcessor().getPixels(), wanted_parts=img_size)
    # This swaps x and y coordinates.
    # http://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python
    # As zip() creates tuples, we have to convert each one by using list().
    pixel_matrix = [list(x) for x in zip(*pixel_matrix)]
    for y in range(img_size):
        for x in range(img_size):
            # This function oszillates between 0 and 1.
            # The distance of 2 maxima in a row/column is given by spacing.
            val = (0.5 * (math.cos(2*math.pi/spacing*x) + math.sin(2*math.pi/spacing*y)))**2
            # When assigning, we multiply the value by the amplitude.
            pixel_matrix[x][y] = amplitude * val
    # The constructor of FloatProcessor works fine with a 2D Python list.
    crystal = ImagePlus("Crystal", FloatProcessor(pixel_matrix))
    # Crop without selection is used to duplicate an image.
    crystal_with_noise = crystal.crop()
    crystal_with_noise.setTitle("Crystal with noise")
    IJ.run(crystal_with_noise, "Add Specified Noise...", "standard=%d" % int(amplitude/math.sqrt(2)))
    # As this is a demo, we don't want to be ask to save an image on closing it.
    # In Python True and False start with capital letters.
    crystal_with_noise.changes = False
    crystal.show()
    crystal_with_noise.show()
    filtered = fft_filter(crystal_with_noise)
    # We create a lambda function to be used as a parameter of img_calc().
    subtract = lambda values: values[0] - values[1]
    """ This is a short form for:
    def subtract(values):
        return values[0] - values[1]
    """
    # The first time we call img_calc with 2 images.
    difference = img_calc(subtract, crystal, filtered, title="Difference of 2")
    difference.show()
    # The first time we call img_calc with 3 images.
    minimum = img_calc(min, crystal, filtered, crystal_with_noise, title="Minimum of 3")
    minimum.show()
    for imp in (crystal, crystal_with_noise, filtered, difference, minimum):
        IJ.run(imp, "Measure", "")
	def testRectangle(self):
		image = IJ.createImage("test", "8-bit black", 255, 255, 1)
		image.show()
		IJ.setForegroundColor(255,255,255);
		image.getProcessor().fillRect(10, 10, 100, 100)
		
		findEdges(image);

		v1 = image.getPixel(8,8)[0]
		v2 = image.getPixel(9,9)[0]
		v3 = image.getPixel(10,10)[0]
		v4 = image.getPixel(11,11)[0]
	
		self.assertEquals(v1, 0)
		self.assertEquals(v2, 255)
		self.assertEquals(v3, 255)
		self.assertEquals(v4, 0)
def shading_correction(infile, threshold):
    # Create artificial shading for stiching collection optimisation
    default_options = "stack_order=XYCZT color_mode=Grayscale view=Hyperstack"
    IJ.run("Bio-Formats Importer", default_options + " open=[" + infile + "]")
    imp = IJ.getImage()
    cal = imp.getCalibration()
    current = ChannelSplitter.split(imp)
    for c in xrange(0, len(current)):
        results = []
        for i in xrange(0, imp.getWidth()):
            roi = Line(0, i, imp.getWidth(), i)
            current[c].show()
            current[c].setRoi(roi)
            temp = IJ.run(current[c], "Reslice [/]...",
                          "output=0.054 slice_count=1 rotate avoid")
            temp = IJ.getImage()
            ip = temp.getProcessor().convertToShort(True)
            pixels = ip.getPixels()
            w = ip.getWidth()
            h = ip.getHeight()
            row = []
            for j in xrange(len(pixels)):
                row.append(pixels[j])
                if j % w == w - 1:
                    results.append(int(percentile(sorted(row), threshold)))
                    row = []
            reslice_names = "Reslice of C" + str(c + 1) + "-" + imp.getTitle()
            reslice_names = re.sub(".ids", "", reslice_names)
            IJ.selectWindow(reslice_names)
            IJ.run("Close")
        imp2 = IJ.createImage("shading_ch" + str(c + 1),
                              "16-bit black", imp.getHeight(), imp.getWidth(), 1)
        pix = imp2.getProcessor().getPixels()
        for i in range(len(pix)):
            pix[i] = results[i]
        imp2.show()
        name = 'ch' + str(c + 1) + imp.getTitle()
        IJ.run(imp2, "Bio-Formats Exporter",
               "save=" + os.path.join(folder10, name))
        IJ.selectWindow("shading_ch" + str(c + 1))
        IJ.run('Close')
        IJ.selectWindow("C" + str(c + 1) + "-" + imp.getTitle())
        IJ.run('Close')
def reduceZ():
    imp = IJ.getImage()  #get the standardtack
    title_1 = imp.getTitle()
    title = title_1.split(' - ')[1]
    print(title)
    dimentions = imp.getDimensions()
    numZ, numChannels, numframes = dimentions[3], dimentions[2], dimentions[4]
    print(numChannels)

    IJ.run(imp, "Set Measurements...", "kurtosis redirect=None decimal=3")

    kurtTotal = []
    for time in range(numframes):
        print(time)
        time = time + 1
        imp.setPosition(1, 1, time)
        kurt = []
        for z in range(numZ):
            z = z + 1
            imp.setPosition(1, z, time)
            imp.setRoi(70, 40, 437, 459)
            IJ.setAutoThreshold(imp, "MaxEntropy dark")
            IJ.run(imp, "Measure", "")
            IJ.resetThreshold(imp)
            rt = ResultsTable()
            t = rt.getResultsTable()
            kurt.append(t.getValueAsDouble(23, z - 1))  # 23 = kurtosis
        kurtTotal.append(kurt.index(max(kurt)) + 1)
        IJ.run(imp, "Clear Results", "")
    print(kurtTotal)

    IJ.run(imp, "Select All", "")

    imp2 = IJ.createImage("GFP", "16-bit black", dimentions[0], dimentions[1],
                          numframes)
    imp2 = HyperStackConverter.toHyperStack(imp2, 1, 1, numframes, "Color")
    print(' ------------')
    print(numframes)
    channel = 1
    i = 0
    for time in range(numframes):
        time = time + 1
        imp.setPosition(channel, kurtTotal[i], time)
        imp.copy()
        imp2.setPosition(channel, 1, time)
        imp2.paste()
        print(time)
        i = i + 1
    IJ.run(imp2, "Delete Slice", "delete=slice")
    imp2.show()

    imp4 = IJ.createImage("RFP", "16-bit black", dimentions[0], dimentions[1],
                          numframes)
    imp4 = HyperStackConverter.toHyperStack(imp4, 1, 1, numframes, "Color")
    print(' ------------')
    channel = 2
    i = 0
    for time in range(numframes):
        time = time + 1
        imp.setPosition(channel, kurtTotal[i], time)
        imp.copy()
        print(imp.title)
        imp4.setPosition(channel, 1, time)
        imp4.paste()
        i = i + 1
    IJ.run(imp4, "Delete Slice", "delete=slice")
    imp4.show()

    IJ.selectWindow(title_1)
    IJ.run("Close")

    imp5 = ImagePlus()
    IJ.run(imp5, "Merge Channels...", "c1=RFP c2=GFP create")
    imp5 = IJ.getImage()
    IJ.run(
        imp5, "Bio-Formats Exporter",
        "save=/home/rickettsia/Desktop/data/Clamydial_Image_Analysis/EMS_BMEC_20X_01192020/Zreduced/"
        + title + ".ome.tif export compression=LZW")
    IJ.selectWindow('Merged')
    IJ.run("Close")
from ij import IJ
from ij.gui import ShapeRoi
from java.awt import Color, Polygon
from java.awt.geom import PathIterator

w = int(36)
h = int(42)
lineWidth = 2
arrowWidth = 16

image = IJ.createImage('Download arrow', 'rgb', w, h, 1)
ip = image.getProcessor()
ip.setLineWidth(lineWidth)
ip.setColor(Color(0x65a4e3))
roi = ShapeRoi([PathIterator.SEG_MOVETO, 0, 0,
	PathIterator.SEG_LINETO, w, 0,
	PathIterator.SEG_LINETO, w, w,
	PathIterator.SEG_LINETO, 0, w,
	PathIterator.SEG_CLOSE])
lw = lineWidth
roi = roi.not(ShapeRoi([PathIterator.SEG_MOVETO, lw, lw,
	PathIterator.SEG_LINETO, w - lw, lw,
	PathIterator.SEG_LINETO, w - lw, w - lw,
	PathIterator.SEG_LINETO, lw, w - lw,
	PathIterator.SEG_CLOSE]))
x1 = (w - arrowWidth) / 2
x2 = (w + arrowWidth) / 2
y1 = w * 2 / 3
roi = roi.or(ShapeRoi([PathIterator.SEG_MOVETO, x1, 0,
	PathIterator.SEG_LINETO, x1, y1,
	PathIterator.SEG_LINETO, 0, y1,
Example #20
0
print "finished clustering"

print len(clusters)

allClusters = []

for c in clusters:
    tupelCluster = set()
    for dp in c.getPoints():
        p = dp.getPoint()
        rgb = p[0], p[1], p[2]
        tupelCluster.add(rgb)
    allClusters.append(tupelCluster)

greyPixels = []
for i in range(0, len(bluePixels)):
    vec = redPixels[i], greenPixels[i], bluePixels[i]
    clusterNr = 0
    for c in allClusters:
        if vec in c:
            break
        clusterNr = clusterNr + 1
    greyPixels.append(clusterNr)

jArray = jarray.array(greyPixels, 'h')
indexedMask = IJ.createImage("Indexed mask of " + title, "16-bit white", width,
                             height, 1)
indexedMask.getProcessor().setPixels(jArray)
indexedMask.show()
IJ.run(indexedMask, "Rainbow RGB", "")
IJ.run(indexedMask, "Enhance Contrast", "saturated=0.35")
Example #21
0
# Create a random 8-bit image the hard way...
width = 512
height = 512
  
pix = zeros(width * height, 'b')
Random().nextBytes(pix)

channel = zeros(256, 'b')
for i in range(256):
    channel[i] = (i -128) 
cm = LUT(channel, channel, channel)
imp_rand_hard = ImagePlus("Random", ByteProcessor(width, height, pix, cm))
imp_rand_hard.show()

# random 16 bit the hard way...
imp = IJ.createImage("An Easy Random Image 8 bit image", "8-bit", 512, 512, 1)
Random().nextBytes(imp.getProcessor().getPixels())
imp.show()

print(sys.getsizeof(int))
print(sys.getsizeof(bytes))

# 1 - Obtain an image
blobs = IJ.openImage("http://imagej.net/images/blobs.gif")
blobs.setTitle("blobs")
blobs.show()
# Make a copy with the same properties as blobs image:
imp = blobs.createImagePlus()
ip = blobs.getProcessor().duplicate()
imp.setProcessor("blobs binary", ip)
 
Example #22
0
#channelImageRGBstack = ImageStack(grayLevelImagePlus.getWidth(), grayLevelImagePlus.getHeight())
channelImageRGBstack_1st_try = ImageStack(grayLevelImagePlus.getHeight(),
                                          grayLevelImagePlus.getWidth())
print("testUnsignedIntegerMatrixBuffer dimensions: " +
      str(clij2_instance.getDimensions(testUnsignedIntegerMatrixBuffer)) +
      ", " + str(testUnsignedIntegerMatrixBuffer.getDimension()))
colouredChannelMatrix = clij2_instance.pullMatXYZ(
    testUnsignedIntegerMatrixBuffer)
#colouredChannelMatrix = clij2_instance.pullMat(testUnsignedIntegerMatrixBuffer)
list_of_matrixes_1st_try = []
for zNumber in range(0, grayLevelImagePlus.getNSlices()):
    sliceMatrix = []
    #sliceImage = IJ.createImage("RGB Channel "+str(0)+" slice"+str(zNumber), "RGB Black", grayLevelImagePlus.getWidth(), grayLevelImagePlus.getHeight(), 1)
    sliceImage = IJ.createImage(
        "RGB Channel " + str(0) + " slice" + str(zNumber), "RGB Black",
        grayLevelImagePlus.getHeight(), grayLevelImagePlus.getWidth(), 1)
    sliceProcessor = sliceImage.getProcessor()
    for xNumber in range(len(colouredChannelMatrix)):
        for yNumber in range(len(colouredChannelMatrix[xNumber])):
            sliceMatrix.append(
                int(colouredChannelMatrix[xNumber][yNumber][zNumber]))
    javaSliceMatrix = array.array('i', sliceMatrix)
    list_of_matrixes_1st_try.append(javaSliceMatrix)
    sliceProcessor.setPixels(javaSliceMatrix)
    channelImageRGBstack_1st_try.addSlice(sliceProcessor)

print("list_of_matrixes_1st_try: ", str(list_of_matrixes_1st_try))
#Convert stack to ImagePlus
colouredChannelImage_1st_try = ImagePlus(String("Processed image with loops"),
                                         channelImageRGBstack_1st_try)
Example #23
0
def do_angular_projection(imp,
                          max_r_pix=60,
                          min_r_pix=10,
                          generate_roi_stack=True):
    """perform ray-based projection of vessel wall, c.f. ICY TubeSkinner (Lancino 2018)"""
    Prefs.blackBackground = True
    print("do angular projection input imp = " + str(imp))
    split_chs = ChannelSplitter().split(imp)
    mch_imp = split_chs[0]
    IJ.setAutoThreshold(mch_imp, "IsoData dark stack")
    egfp_imp = split_chs[1]
    proj_imp = Duplicator().run(egfp_imp)
    cl_imp = split_chs[2]
    if generate_roi_stack:
        egfp_imp_disp = Duplicator().run(egfp_imp)
        roi_stack = IJ.createImage("rois", egfp_imp.getWidth(),
                                   egfp_imp.getHeight(), egfp_imp.getNSlices(),
                                   16)

    centres = []
    projected_im_pix = []
    ring_rois = []
    for zidx in range(cl_imp.getNSlices()):
        if ((zidx + 1) % 100) == 0:
            print("Progress = " +
                  str(round(100 * (float(zidx + 1) / cl_imp.getNSlices()))))
        projected_im_row = []
        proj_imp.setZ(zidx + 1)
        mch_imp.setZ(zidx + 1)
        bp = mch_imp.createThresholdMask()
        bp.dilate()
        bp.erode()
        bp.erode()
        bp.erode()
        mask_imp = ImagePlus("mask", bp)
        IJ.run(mask_imp, "Create Selection", "")
        roi = mask_imp.getRoi()
        proj_imp.setRoi(roi)
        IJ.run(proj_imp, "Set...", "value=0 slice")
        IJ.run(proj_imp, "Make Inverse", "")
        roi = proj_imp.getRoi()
        centre = (roi.getStatistics().xCentroid, roi.getStatistics().yCentroid)
        centres.append(centre)
        ring_roi_xs = []
        ring_roi_ys = []
        for theta in range(360):
            pt1 = (centre[0] + min_r_pix * math.cos(math.radians(theta)),
                   centre[1] + min_r_pix * math.sin(math.radians(theta)))
            pt2 = (centre[0] + max_r_pix * math.cos(math.radians(theta)),
                   centre[1] + max_r_pix * math.sin(math.radians(theta)))
            roi = Line(pt1[0], pt1[1], pt2[0], pt2[1])
            proj_imp.setRoi(roi)
            profile = roi.getPixels()
            projected_im_row.append(max(profile))
            try:
                ring_roi_xs.append(roi.getContainedPoints()[profile.index(
                    max(profile))].x)
            except IndexError:
                ring_roi_xs.append(pt2[0])
            try:
                ring_roi_ys.append(roi.getContainedPoints()[profile.index(
                    max(profile))].y)
            except IndexError:
                ring_roi_ys.append(pt2[1])
            proj_imp.killRoi()
        ring_roi = PolygonRoi(ring_roi_xs, ring_roi_ys, Roi.FREELINE)
        ring_rois.append(ring_roi)
        if generate_roi_stack:
            roi_stack.setZ(zidx + 1)
            roi_stack.setRoi(ring_roi)
            IJ.run(roi_stack, "Line to Area", "")
            IJ.run(
                roi_stack, "Set...",
                "value=" + str(roi_stack.getProcessor().maxValue()) + " slice")
        #egfp_imp.setRoi(ring_roi);
        projected_im_pix.append(projected_im_row)


#	for ch in split_chs:
#		ch.close();

    out_imp = ImagePlus(
        "projected", FloatProcessor([list(x) for x in zip(*projected_im_pix)]))

    if generate_roi_stack:
        roi_stack.show()
        egfp_imp_disp.show()
        # merge?
    else:
        roi_stack = None
    return out_imp, roi_stack, ring_rois, centres
Example #24
0
			k= str(j)
			if os.path.isfile((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/488storm_" + "%03d" % i + "_" + "%02d" % j + "_0.tif")):
				imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/488storm_" + "%03d" % i + "_" + "%02d" % j + "_0.tif"))
				imp.show()
				IJ.run(imp, "Canvas Size...", "width=2350 height=2350 position=Center zero");
				IJ.run(imp, "Canvas Size...", "width=2560 height=2560 position=Center zero");
				imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/488storm_" + "%03d" % i + "_" + "%02d" % j + "_1.tif"))
				imp.show()
				IJ.run(imp, "Canvas Size...", "width=2350 height=2350 position=Center zero");
				IJ.run(imp, "Canvas Size...", "width=2560 height=2560 position=Center zero");
				IJ.run(imp, "Images to Stack", "name=Stack title=[] use");
				imp = IJ.getImage()  
				IJ.run(imp, "Z Project...", "start=1 stop=2 projection=[Average Intensity]");
				imp = IJ.getImage()  
			else:
				imp = IJ.createImage("Untitled", "8-bit Black", 2560, 2560, 1);
			IJ.saveAs(imp, "Tiff", (ISanalysisfolder + "%04d" % i + "/aligned/488storm_" + "%03d" % i + "_" + "%02d" % j + ".tif"));
			IJ.run("Close All", "");
			
			#if os.path.isfile((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/561storm_" + "%02d" % i + "_" + "%02d" % j + "_0.tif")):
			#	imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/561storm_" + "%02d" % i + "_" + "%02d" % j + "_0.tif"))
			#	imp.show()
			#	IJ.run(imp, "Canvas Size...", "width=2350 height=2350 position=Center zero");
			#	IJ.run(imp, "Canvas Size...", "width=2560 height=2560 position=Center zero");
			#	imp = IJ.openImage((ISanalysisfolder + "%04d" % i + "/aligned/after_dist_corr/561storm_" + "%02d" % i + "_" + "%02d" % j + "_1.tif"))
			#	imp.show()
			#	IJ.run(imp, "Canvas Size...", "width=2350 height=2350 position=Center zero");
			#	IJ.run(imp, "Canvas Size...", "width=2560 height=2560 position=Center zero");
			#	IJ.run(imp, "Images to Stack", "name=Stack title=[] use");
			#	imp = IJ.getImage()  
			#	IJ.run(imp, "Z Project...", "start=1 stop=2 projection=[Average Intensity]");
Example #25
0
# angle method
max_r_pix = 60
min_r_pix = 10

split_chs = ChannelSplitter().split(imp)
mch_imp = split_chs[0]
egfp_imp = split_chs[1]
egfp_imp_disp = Duplicator().run(egfp_imp)
cl_imp = split_chs[2]
#egfp_imp.show();

centres = []
projected_im_pix = []
ring_rois = []
unzip_axis = []
roi_stack = IJ.createImage("rois", egfp_imp.getWidth(), egfp_imp.getHeight(),
                           egfp_imp.getNSlices(), 16)
#roi_stack.show();

for zidx in range(cl_imp.getNSlices()):
    #for zidx in range(200,350):
    #for zidx in range(200,202):
    if ((zidx + 1) % 100) == 0:
        print("Z = " + str(zidx + 1))
    projected_im_row = []
    egfp_imp.setZ(zidx + 1)
    cl_imp.setZ(zidx + 1)
    ip = cl_imp.getProcessor()
    out = MaximumFinder().getMaxima(ip, 10, True)
    centres.append((out.xpoints[0], out.ypoints[0]))
    centre = (out.xpoints[0], out.ypoints[0])
    ring_roi_xs = []
Example #26
0

def draw_cell(imp, i, nucleus_total, damage_total, title, noise):
    imp.append(impBG.duplicate())
    draw_nucleus(imp[i], nucleus_total / nucleus_area)
    draw_damage(imp[i], damage_total / damage_area)
    imp[i] = blur_and_noise(imp[i], 2, noise)
    imp[i].show()
    imp[i].setTitle(title)
    return (imp)


# Main

# Create background image
impBG = IJ.createImage("Untitled", "16-bit black", 512, 512, 1)
#IJ.run(imp, "RGB Color", "");
#IJ.run(imp, "Radial Gradient", "");
#IJ.run(imp, "16-bit", "");
#IJ.run(imp, "Multiply...", "value="+str(255));
#IJ.run(imp, "Gaussian Blur...", "sigma=30");
#IJ.run(imp, "Divide...", "value="+str(65535/background));
IJ.run(impBG, "Add...", "value=" + str(background))

# Intensities
nucleus_total = 1000000

imps = []
i = -1

# No damage
def reListImagePluses(fileList, imageTitle, valeurSelectionDisplayMode, valeurSelectionTypeFichier):
    listOfOrderedImagePluses = []
    hyperStackList = []
    print("reListImagePluses - fileList: "+str(fileList))
    if valeurSelectionTypeFichier == "1 fichier par canal (NOM_FICHIER_chXX.tif)":
        channelsList = []
        channelNumber = 0
        for channelImagePlus in fileList:
            imageWidth = channelImagePlus.getWidth(); #Largeur de l'image
            imageHeight = channelImagePlus.getHeight(); #Hauteur de l'image
            zDepthByChannel = channelImagePlus.getNSlices() #Profondeur Z
            bitDepth = channelImagePlus.getBitDepth() #Type de l'image en bits - Returns the bit depth, 8, 16, 24 (RGB) or 32, or 0 if the bit depth is unknown. RGB images actually use 32 bits per pixel.
            stackedImages = channelImagePlus.getStack()
            arrayOfImages = []
            for zNumber in range(1,zDepthByChannel+1):
                currentImageProcessor = stackedImages.getProcessor(zNumber)
                timeArray = []
                for timeNumber in range(1):
                    if bitDepth == 8:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber), "8-bit Black", imageWidth, imageHeight, 1)
                    if bitDepth == 16:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber), "16-bit Black", imageWidth, imageHeight, 1)
                    if bitDepth == 24: #RGB[img["Channel 1, Z-Depth 1" (-658), 16-bit, 840x840x1x1x1]]
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber), "RGB Black", imageWidth, imageHeight, 1)
                    if bitDepth == 32:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber), "32-bit Black", imageWidth, imageHeight, 1)
                    newImage.setProcessor(currentImageProcessor)
                    timeArray.append(newImage)
                arrayOfImages.append(timeArray)
            channelsList.append(arrayOfImages)
            channelNumber+=1
        hyperStackImagePlus = assembleChannelImagesInStacks(imageTitle, channelsList, valeurSelectionDisplayMode, valeurSelectionTypeFichier)
        hyperStackList.append(hyperStackImagePlus)
    if valeurSelectionTypeFichier == "1 fichier par canal + temps (NOM_FICHIER_tXX_chXX.tif)":
        channelsList = []
        channelNumber = 0
        for channelList in fileList:
            timeArray = []
            timeNumber = 0
            for timeImagePlus in channelList:
                imageWidth = timeImagePlus.getWidth(); #Largeur de l'image
                imageHeight = timeImagePlus.getHeight(); #Hauteur de l'image
                zDepthByChannel = timeImagePlus.getNSlices() #Profondeur Z
                bitDepth = timeImagePlus.getBitDepth() #Type de l'image en bits - Returns the bit depth, 8, 16, 24 (RGB) or 32, or 0 if the bit depth is unknown. RGB images actually use 32 bits per pixel.
                stackedImages = timeImagePlus.getStack()
                arrayOfZDepths = []
                for zNumber in range(1,zDepthByChannel+1):
                    currentImageProcessor = stackedImages.getProcessor(zNumber)
                    if bitDepth == 8:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber)+", T-time "+str(timeNumber), "8-bit Black", imageWidth, imageHeight, 1)
                    if bitDepth == 16:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber)+", T-time "+str(timeNumber), "16-bit Black", imageWidth, imageHeight, 1)
                    if bitDepth == 24: #RGB[img["Channel 1, Z-Depth 1" (-658), 16-bit, 840x840x1x1x1]]
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber)+", T-time "+str(timeNumber), "RGB Black", imageWidth, imageHeight, 1)
                    if bitDepth == 32:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber)+", T-time "+str(timeNumber), "32-bit Black", imageWidth, imageHeight, 1)
                    newImage.setProcessor(currentImageProcessor)
                    arrayOfZDepths.append(newImage)
                timeNumber+=1
                timeArray.append(arrayOfZDepths)
            channelNumber+=1
            channelsList.append(timeArray)
        hyperStackImagePlus = assembleChannelImagesInStacks(imageTitle, channelsList, valeurSelectionDisplayMode, valeurSelectionTypeFichier)
        hyperStackList.append(hyperStackImagePlus)
    if valeurSelectionTypeFichier == "1 fichier par canal et par profondeur (NOM_FICHIER_zXX_chXX.tif)":
        channelNumber = 0
        channelsList = []
        for channelList in fileList:
            zDepthArray = []
            zNumber = 1
            for zDepthImagePlus in channelList:
                timeArray = []
                for timeNumber in range(1):
                    imageWidth = zDepthImagePlus.getWidth(); #Largeur de l'image
                    imageHeight = zDepthImagePlus.getHeight(); #Hauteur de l'image
                    bitDepth = zDepthImagePlus.getBitDepth() #Type de l'image en bits - Returns the bit depth, 8, 16, 24 (RGB) or 32, or 0 if the bit depth is unknown. RGB images actually use 32 bits per pixel.
                    currentImageProcessor = zDepthImagePlus.getProcessor()
                    if bitDepth == 8:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber), "8-bit Black", imageWidth, imageHeight, 1)
                    if bitDepth == 16:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber), "16-bit Black", imageWidth, imageHeight, 1)
                    if bitDepth == 24: #RGB[img["Channel 1, Z-Depth 1" (-658), 16-bit, 840x840x1x1x1]]
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber), "RGB Black", imageWidth, imageHeight, 1)
                    if bitDepth == 32:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber), "32-bit Black", imageWidth, imageHeight, 1)
                    newImage.setProcessor(currentImageProcessor)
                    timeArray.append(newImage)
                zNumber+=1
                zDepthArray.append(timeArray)
            channelNumber+=1
            channelsList.append(zDepthArray)
        hyperStackImagePlus = assembleChannelImagesInStacks(imageTitle, channelsList, valeurSelectionDisplayMode, valeurSelectionTypeFichier)
        hyperStackList.append(hyperStackImagePlus)
    if valeurSelectionTypeFichier == "1 fichier par canal et par profondeur + temps (NOM_FICHIER_tXX_zXX_chXX.tif)":
        channelNumber = 0
        channelsList = []
        for channelList in fileList:
            zDepthArray = []
            zNumber = 1
            for zDepthList in channelList:
                timeArray = []
                tTime = 1
                for timeImagePlus in zDepthList:
                    imageWidth = timeImagePlus.getWidth(); #Largeur de l'image
                    imageHeight = timeImagePlus.getHeight(); #Hauteur de l'image
                    bitDepth = timeImagePlus.getBitDepth() #Type de l'image en bits - Returns the bit depth, 8, 16, 24 (RGB) or 32, or 0 if the bit depth is unknown. RGB images actually use 32 bits per pixel.
                    currentImageProcessor = timeImagePlus.getProcessor()
                    if bitDepth == 8:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber)+", T-time "+str(tTime), "8-bit Black", imageWidth, imageHeight, 1)
                    if bitDepth == 16:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber)+", T-time "+str(tTime), "16-bit Black", imageWidth, imageHeight, 1)
                    if bitDepth == 24: #RGB[img["Channel 1, Z-Depth 1" (-658), 16-bit, 840x840x1x1x1]]
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber)+", T-time "+str(tTime), "RGB Black", imageWidth, imageHeight, 1)
                    if bitDepth == 32:
                        newImage = IJ.createImage(str(imageTitle)+" | Channel "+str(channelNumber)+", Z-Depth "+str(zNumber)+", T-time "+str(tTime), "32-bit Black", imageWidth, imageHeight, 1)
                    tTime+=1
                    newImage.setProcessor(currentImageProcessor)
                    timeArray.append(newImage)
                zNumber+=1
                zDepthArray.append(timeArray)
            channelNumber+=1
            channelsList.append(zDepthArray)
        hyperStackImagePlus = assembleChannelImagesInStacks(imageTitle, channelsList, valeurSelectionDisplayMode, valeurSelectionTypeFichier)
        hyperStackList.append(hyperStackImagePlus)
    return hyperStackList
	pa=ParticleAnalyzer(EXCLUDE_EDGE_PARTICLES | ADD_TO_MANAGER,
                        0,
                        rt,
                        112/4,
                        200,
                        0.0,
                        1.0)

	pa.analyze(imp)
	# time.sleep(2)
	print 'Size of results: ',rt.size()
	# rm.runCommand("select","all")
	# rm.runCommand("Fill","3")
	save_path=saving_dir+"\\mask_%s" % (image[image.rindex('\\')+1:])
	# print(save_path)
	impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(), imp.getHeight(), imp.getNChannels(), imp.getNSlices(), imp.getNFrames())
	impMask.show()
	IJ.setForegroundColor(255, 255, 255)
	
	rm.runCommand(impMask,"Deselect")
	rm.runCommand(impMask,"Draw")
	

	if doFileSave and FileSaver(impMask).saveAsTiff(save_path):
		print 'Saved Image ',image
	else:
		print '!!! Not saved Image',image
	
	if not leaveMasks and img_ind<len(proc_images)-1:
		impMask.changes=False
		impMask.close()	
def do_tubefitting(im_path=im_test_path,
                   metadata_path=metadata_test_path,
                   output_path=output_path,
                   save_output=False):
    # todo: fix things so that all operations use a consistent definition of background rather than changing Prefs on the fly...
    Prefs.blackBackground = False
    info = PrescreenInfo()
    info.load_info_from_json(metadata_path)
    z_xy_ratio = abs(
        info.get_z_plane_spacing_um()) / info.get_xy_pixel_size_um()
    #z_xy_ratio = 1.0;
    bfimp = bf.openImagePlus(im_path)
    imp = bfimp[0]
    imp.show()
    IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel")
    imp = utils.downsample_for_isotropy(imp,
                                        extra_downsample_factor=1.0,
                                        info=info)
    rot_seg_imp, rot_proj_imp, egfp_mch_imps = split_and_rotate(imp, info)
    depth = rot_seg_imp.getNSlices() if rot_seg_imp.getNSlices(
    ) > rot_seg_imp.getNFrames() else rot_seg_imp.getNFrames()
    width = rot_seg_imp.getWidth()
    height = int(round(rot_seg_imp.getHeight() * z_xy_ratio))

    # Apply 3d MEDIAN FILTER to denoise and emphasise vessel-associated voxels
    fit_basis_imp = threshold_and_binarise(rot_seg_imp, z_xy_ratio)
    fit_basis_imp.setTitle("fit_basis_imp")
    fit_basis_imp.show()

    # plane-wise, use binary-outline
    # say the non-zero points then make up basis for fitting to be performed per http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
    rois = []
    centres = []
    major_axes = []
    roi_imp = IJ.createImage("rois", width, height, depth, 32)
    pts_stack = ImageStack(width, height + 1)
    IJ.run(imp, "Line Width...", "line=3")
    for zidx in range(fit_basis_imp.getNSlices()):
        fit_basis_imp.setZ(zidx + 1)
        IJ.run(fit_basis_imp, "Outline", "slice")
        IJ.run(fit_basis_imp, "Create Selection", "")
        roi = fit_basis_imp.getRoi()
        fit_basis_imp.killRoi()
        pts = [(pt.x, pt.y) for pt in roi.getContainedPoints()]
        clean_pts = convex_hull_pts(pts)
        clean_pts = [(x, z_xy_ratio * y) for (x, y) in clean_pts]
        # make a stack of clean points...
        ip = FloatProcessor(width, height + 1)
        pix = ip.getPixels()
        for pt in clean_pts:
            pix[int(pt[1]) * width + int(pt[0])] = 128
        pts_stack.addSlice(ip)
        centre, angle, axl = ellipse_fitting.fit_ellipse(clean_pts)
        major_axes.append(max(axl))
        centres.append(centre)
        rot_seg_imp.setZ(zidx + 1)
        ellipse_roi = ellipse_fitting.generate_ellipse_roi(centre, angle, axl)
        rois.append(ellipse_roi)
    IJ.run(imp, "Line Width...", "line=1")
    cal = imp.getCalibration()
    smooth_centres, tangent_vecs = generate_smoothed_vessel_axis(
        centres, pixel_size_um=cal.pixelDepth)
    for zidx in range(fit_basis_imp.getNSlices()):
        centre = smooth_centres[zidx]
        major_axis = major_axes[zidx]
        ellipse_roi = EllipseRoi(centre[0] - 2, centre[1], centre[0] + 2,
                                 centre[1], 1.0)
        roi_imp.setZ(zidx + 1)
        roi_imp.setRoi(ellipse_roi)
        IJ.run(roi_imp, "Set...",
               "value=" + str(roi_imp.getProcessor().maxValue()) + " slice")

    pts_stack_imp = ImagePlus("Cleaned points", pts_stack)
    pts_stack_imp.setTitle("pts_stack_imp")
    pts_stack_imp.show()

    rot_seg_imp.changes = False
    rot_seg_imp.close()
    egfp_imp = egfp_mch_imps[0]
    mch_imp = egfp_mch_imps[1]
    imps_to_combine = [egfp_mch_imps[1], egfp_mch_imps[0], roi_imp]
    egfp_imp.show()
    mch_imp.show()
    roi_imp.show()
    print("box height um = " +
          str(roi_imp.getNSlices() * info.get_xy_pixel_size_um()))
    IJ.run(
        egfp_imp, "Size...", "width=" + str(width) + " height=" + str(height) +
        " depth=" + str(depth) + " average interpolation=Bilinear")
    IJ.run(
        mch_imp, "Size...", "width=" + str(width) + " height=" + str(height) +
        " depth=" + str(depth) + " average interpolation=Bilinear")
    #IJ.run("Merge Channels...", "c1=[" + mch_imp.getTitle() +
    #								"] c2=[" + egfp_imp.getTitle() +
    #								"] c7=[" + roi_imp.getTitle() + "] create keep");
    composite_imp = RGBStackMerge().mergeChannels(imps_to_combine, False)
    print(composite_imp)
    composite_imp.show()
    print("end of vessel centerline id step, image dims = ({}x{}x{})".format(
        composite_imp.getWidth(), composite_imp.getHeight(),
        composite_imp.getNSlices()))
    WaitForUserDialog("pause").show()
    # do qc here?

    #WM.getImage("Composite").addImageListener(UpdateRoiImageListener(rois));
    IJ.run(roi_imp, "8-bit", "")

    if save_output:
        FileSaver(composite_imp).saveAsTiffStack(
            os.path.join(output_path, "segmentation result.tif"))
        print(roi_imp)
        FileSaver(roi_imp).saveAsTiff(
            os.path.join(output_path, "vessel axis.tif"))

    egfp_imp.changes = False
    mch_imp.changes = False
    roi_imp.changes = False
    fit_basis_imp.changes = False
    pts_stack_imp.changes = False
    egfp_imp.close()
    mch_imp.close()
    #roi_imp.close();
    fit_basis_imp.close()
    pts_stack_imp.close()

    zcoords = [i for i in range(composite_imp.getNSlices())]
    xyz_smooth_centres = [(x, y, z)
                          for ((x, y), z) in zip(smooth_centres, zcoords)]

    composite_imp2 = straighten_vessel(composite_imp,
                                       xyz_smooth_centres,
                                       save_output=True)
    composite_imp3 = straighten_vessel(composite_imp2,
                                       xyz_smooth_centres,
                                       it=2,
                                       save_output=True)
    return composite_imp3
from ij import IJ, ImagePlus
from ij.gui import Toolbar, Roi
from ij.process import Blitter
from java.awt import Color, Font, Polygon, Rectangle

w = 472
h = 354
xOffset = 59
yOffset = 120
radius = 20
arrowThickness = 14
fontName = 'Arial'
upperFontSize = 18
lowerFontSize = 10

image = IJ.createImage("MacOSX background picture", "rgb", w, h, 1)

# background
Toolbar.setForegroundColor(Color(0x5886ea))
Toolbar.setBackgroundColor(Color(0x3464c9))
IJ.run(image, "Radial Gradient", "")

# rounded rectangle
# correct for MacOSX bug: do the rounded rectangle in another image
image2 = image
image = IJ.createImage("MacOSX background picture", "rgb", w, h, 1)
image.setRoi(Roi(xOffset, yOffset, w - 2 * xOffset, h - 2 * yOffset))
IJ.run(image, "Make rectangular selection rounded", "radius=" + str(radius))
Toolbar.setForegroundColor(Color(0x435a96))
Toolbar.setBackgroundColor(Color(0x294482))
IJ.run(image, "Radial Gradient", "")
from ij import IJ
import random
import string

imp = IJ.createImage("Drift-Stack_max64px", "32-bit black", 256, 256, 10)
width, height = 32, 32
x, y, x_start, y_start = 112, 112, 128, 128
imp.setRoi(x,y,width,height)
IJ.run(imp, "Set...", "value=255 slice")
imp.getStack().setSliceLabel(str(x) + ',' + str(y), 1)
for i in range(2,11):
	imp.setSlice(i)
	x = x_start + random.randint(-32.0,32.0) - width/2
	y = y_start + random.randint(-32.0,32.0) - height/2
	print x, y
	imp.setRoi(x,y,width,height)
	IJ.run(imp, "Set...", "value=255 slice")
	imp.getStack().setSliceLabel(str(x) + ',' + str(y), i)
imp.setRoi(80,80,96,96)
imp.show()
IJ.run("Start Animation [\\]")
def main():

    Interpreter.batchMode = True

    if (lambda_flat == 0) ^ (lambda_dark == 0):
        print ("ERROR: Both of lambda_flat and lambda_dark must be zero,"
               " or both non-zero.")
        return
    lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual"

    print "Loading images..."

    options = ImporterOptions()
    options.setId(str(filename))
    options.setOpenAllSeries(True)
    options.setConcatenate(True)
    options.setSplitChannels(True)
    imps = BF.openImagePlus(options)

    num_channels = len(imps)
    w = imps[0].getWidth()
    h = imps[0].getHeight()
    ff_imp = IJ.createImage("Flat-field", w, h, num_channels, 32);
    df_imp = IJ.createImage("Dark-field", w, h, num_channels, 32);

    basic = Basic()
    Basic_noOfSlices = Basic.getDeclaredField('noOfSlices')
    Basic_noOfSlices.setAccessible(True)

    for channel, imp in enumerate(imps):
        title = imp.getTitle()
        print "Processing:", title
        x, y, c, z, t = imp.getDimensions()
        assert z == 1 and c == 1
        imp.setDimensions(1, t, 1)

        WindowManager.setTempCurrentImage(imp)
        Basic_noOfSlices.setInt(basic, t)
        basic.exec(
            imp, None, None,
            "Estimate shading profiles", "Estimate both flat-field and dark-field",
            lambda_estimate, lambda_flat, lambda_dark,
            "Ignore", "Compute shading only"
        )
        ff_channel = WindowManager.getImage('Flat-field:' + title)
        ff_channel.copy()
        ff_imp.setSlice(channel + 1)
        ff_imp.paste()
        ff_channel.close()

        df_channel = WindowManager.getImage('Dark-field:' + title)
        df_channel.copy()
        df_imp.setSlice(channel + 1)
        df_imp.paste()
        df_channel.close()

        imp.close()

    # Setting the active slice back to 1 seems to fix an issue where
    # the last slice was empty in the saved TIFFs. Not sure why.
    ff_imp.setSlice(1)
    df_imp.setSlice(1)

    ff_filename = '%s/%s-ffp-basic.tif' % (output_dir, experiment_name)
    IJ.saveAsTiff(ff_imp, ff_filename)
    ff_imp.show()
    ff_imp.close()

    df_filename = '%s/%s-dfp-basic.tif' % (output_dir, experiment_name)
    IJ.saveAsTiff(df_imp, df_filename)
    df_imp.show()
    df_imp.close()

    print "Done!"
Example #33
0
def batch_open_images(pathImage, pathRoi, pathMask, file_typeImage=None,  name_filterImage=None,  recursive=False):
    '''Open all files in the given folder.
    :param path: The path from were to open the images. String and java.io.File are allowed.
    :param file_type: Only accept files with the given extension (default: None).
    :param name_filter: Only accept files that contain the given string (default: None).
    :param recursive: Process directories recursively (default: False).
    '''
    # Converting a File object to a string.
    if isinstance(pathImage, File):
        pathImage = pathImage.getAbsolutePath()

    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



    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

   

    # 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().
    if not recursive:
        for file_name in os.listdir(pathImage):
            full_path = os.path.join(pathImage, file_name)
            if os.path.isfile(full_path):
                if check_type(file_name):
                    if check_filter(file_name):
                        path_to_Image.append(full_path)
    # For a recursive search os.walk() is used.
    else:
        # os.walk() is iterable.
        # Each iteration of the for loop processes a different directory.
        # the first return value represents the current directory.
        # The second return value is a list of included directories.
        # The third return value is a list of included files.
        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])])
    # Create the list that will be returned by this function.
    Images = []
    Rois = []
    for img_path, file_name in path_to_Image:
        # IJ.openImage() returns an ImagePlus object or None.
        imp = IJ.openImage(img_path)
        print(img_path)
        if check_filter(file_name):
         continue;
        else: 
         print(file_name  ,  pathRoi)
         RoiName = str(pathRoi) + '/'+ file_name + '.roi'
         Roi = IJ.open(RoiName)
         # An object equals True and None equals False.
         rm = RoiManager.getInstance()
         if (rm==None):
            rm = RoiManager()
         rm.addRoi(Roi)
         
         impMask = IJ.createImage("Mask", "8-bit grayscale-mode", imp.getWidth(), imp.getHeight(), imp.getNChannels(), imp.getNSlices(), imp.getNFrames())
         IJ.setForegroundColor(255, 255, 255)
         rm.runCommand(impMask,"Deselect")
         rm.runCommand(impMask,"Fill")
         rm.runCommand('Delete')
         IJ.saveAs(impMask, '.tif', str(pathMask) + "/"  +  file_name);
         imp.close();
        
         #print(img_path, RoiName)
         Images.append(imp)
         Rois.append(Roi)    
    return Images, Rois
Example #34
0
	def __displayCells(self, nameimage, methodeleon=False):
		"""
		Displays all the ROIs of the cells with different colors
		
		"""
		# we define a list of colors that will be used.

		colors = []
		ncells= len(self.__dict[nameimage])
		if ncells > 0 :
			step=200/ncells
			if step<1 : step=1
			for i in range(ncells) : 
				r = random.randrange(5,205,step)
				g = random.randrange(10,210,step)
				b = random.randrange(30,230,step)
				#r = int(0+i*step)
				#g = random.randrange(10, 190, 30)
				#b = int(250-i*step)
				
				colors.append(Color(r, g, b))

		else : 	colors=[Color.blue, Color.green, Color.magenta, Color.orange, Color.yellow]
		tempcolors=list(colors)
		# we try to have random and different colors for each cell.
		for cellname in self.__dict[nameimage].keys() :
			if len(tempcolors)>0 : 
				self.__dict[nameimage][cellname].setColor(tempcolors.pop(0))
			else :
				tempcolors=list(colors)
				self.__dict[nameimage][cellname].setColor(tempcolors.pop(0))
		

		self.__SaveCells(nameimage)
		
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")

		# if the user wants to save files, .zip for the ROIs are saved.
		#if self.__optionSave == True : 
		#os.mkdir(self.__pathdir+"ROIs/", mode=0777)
		os.makedirs(self.__pathdir+"ROIs/", mode=0777)
		tempimp = IJ.createImage("tempimp", "8-bit Black", self.__dictImages[nameimage].getWidth(), self.__dictImages[nameimage].getHeight(), 1)
		tempimp.show()
		for cellname in self.__dict[nameimage].keys() :
			for numslice in range(self.__dictImages[nameimage].getImageStackSize()) :
				r = self.__dict[nameimage][cellname].getRoi(numslice)
				try : 
					name=r.getName()
				
				except AttributeError : continue

				else :
					s = "%04i" % (numslice+1)
					#name=s+"-"+name.split("-", 1)[1]
					name=s+"-cell"+name.split("cell")[1]
					r.setName(name)
					try :
						rm.addRoi(r)
						rname=rm.getName(rm.getCount()-1)
						#rm.select(self.__dictImages[nameimage], rm.getCount()-1)
						rm.select(tempimp, rm.getCount()-1)
						rm.runCommand("Rename", name)
					except TypeError : continue
					
					
				#if isinstance(self.__dict[nameimage][cellname].getRoi(numslice),Roi) == True :
				#	s = "%04i" % (numslice)
				#	#rm.add(self.__dictImages[nameimage], self.__dict[nameimage][cellname].getRoi(numslice)  ,  numslice)
				#	name=self.__dict[nameimage][cellname].getRoi(numslice).getName()
				#	name=s+name
				#	self.__dict[nameimage][cellname].getRoi(numslice).setName(name)
				#	rm.addRoi(self.__dict[nameimage][cellname].getRoi(numslice))
			rm.runCommand("Save", self.__pathdir+"ROIs/"+cellname+".zip")
			rm.runCommand("reset")
		
		tempimp.close()
Example #35
0
def hello():  
   IJ.showMessage("Hello World!")
   imp = IJ.createImage("A Random Image", "8-bit", 512, 512, 1)
   Random().nextBytes(imp.getProcessor().getPixels())
   imp.show()
   return 'Hello World!'     
from ij import IJ
from ij.gui import OvalRoi, Line

# Requirements
# - RandomJ: RandomJ is available from the ImageScience update site.

r = 3
c = 256
dc = 30
n = 8
SNR = 3
blur = 1 

imp = IJ.createImage("Untitled", "8-bit black", 512, 512, 1);
IJ.run(imp, "RGB Color", "");
IJ.run(imp, "Radial Gradient", "");
IJ.run(imp, "8-bit", "");
IJ.run(imp, "Divide...", "value="+str(SNR));

for i in range(n):
  imp.setRoi(OvalRoi(c-i*dc,c-i*dc,r,r));
  IJ.run(imp, "Multiply...", "value="+str(SNR));


# Line with dots
for i in range(n):
  imp.setRoi(OvalRoi(80+i*dc,50,r,r));
  IJ.run(imp, "Multiply...", "value="+str(SNR));
imp.setRoi(80,50,int(3/2*c),r);
IJ.run(imp, "Add...", "value=80");
  
Example #37
0
def main():

    Interpreter.batchMode = True

    if (lambda_flat == 0) ^ (lambda_dark == 0):
        print ("ERROR: Both of lambda_flat and lambda_dark must be zero,"
               " or both non-zero.")
        return
    lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual"

    print "Loading images..."

    # Use BioFormats reader directly to determine dataset dimensions without
    # reading every single image. The series count (num_images) is the one value
    # we can't easily get any other way, but we might as well grab the others
    # while we have the reader available.
    bfreader = ImageReader()
    bfreader.id = str(filename)
    num_images = bfreader.seriesCount
    num_channels = bfreader.sizeC
    width = bfreader.sizeX
    height = bfreader.sizeY
    bfreader.close()

    # The internal initialization of the BaSiC code fails when we invoke it via
    # scripting, unless we explicitly set a the private 'noOfSlices' field.
    # Since it's private, we need to use Java reflection to access it.
    Basic_noOfSlices = Basic.getDeclaredField('noOfSlices')
    Basic_noOfSlices.setAccessible(True)
    basic = Basic()
    Basic_noOfSlices.setInt(basic, num_images)

    # Pre-allocate the output profile images, since we have all the dimensions.
    ff_image = IJ.createImage("Flat-field", width, height, num_channels, 32);
    df_image = IJ.createImage("Dark-field", width, height, num_channels, 32);

    print("\n\n")

    # BaSiC works on one channel at a time, so we only read the images from one
    # channel at a time to limit memory usage.
    for channel in range(num_channels):
        print "Processing channel %d/%d..." % (channel + 1, num_channels)
        print "==========================="

        options = ImporterOptions()
        options.id = str(filename)
        options.setOpenAllSeries(True)
        # concatenate=True gives us a single stack rather than a list of
        # separate images.
        options.setConcatenate(True)
        # Limit the reader to the channel we're currently working on. This loop
        # is mainly why we need to know num_images before opening anything.
        for i in range(num_images):
            options.setCBegin(i, channel)
            options.setCEnd(i, channel)
        # openImagePlus returns a list of images, but we expect just one (a
        # stack).
        input_image = BF.openImagePlus(options)[0]

        # BaSiC seems to require the input image is actually the ImageJ
        # "current" image, otherwise it prints an error and aborts.
        WindowManager.setTempCurrentImage(input_image)
        basic.exec(
            input_image, None, None,
            "Estimate shading profiles", "Estimate both flat-field and dark-field",
            lambda_estimate, lambda_flat, lambda_dark,
            "Ignore", "Compute shading only"
        )
        input_image.close()

        # Copy the pixels from the BaSiC-generated profile images to the
        # corresponding channel of our output images.
        ff_channel = WindowManager.getImage("Flat-field:%s" % input_image.title)
        ff_image.slice = channel + 1
        ff_image.getProcessor().insert(ff_channel.getProcessor(), 0, 0)
        ff_channel.close()
        df_channel = WindowManager.getImage("Dark-field:%s" % input_image.title)
        df_image.slice = channel + 1
        df_image.getProcessor().insert(df_channel.getProcessor(), 0, 0)
        df_channel.close()

        print("\n\n")

    template = '%s/%s-%%s.tif' % (output_dir, experiment_name)
    ff_filename = template % 'ffp'
    IJ.saveAsTiff(ff_image, ff_filename)
    ff_image.close()
    df_filename = template % 'dfp'
    IJ.saveAsTiff(df_image, df_filename)
    df_image.close()

    print "Done!"
Example #38
0
mroi = mask.getRoi()
mask.deleteRoi()
rm.reset()
rm.addRoi(mroi)
IJ.run("Clear Results")
dist_folder = folder+"\\distances"


# zapisywanie odległości w obrębie segmentu
if not os.path.exists(dist_folder):
    os.mkdir(dist_folder)

IJ.run(mask, "Analyze Particles...", "display add")
IJ.run("Clear Results")
dimentions = mask.getDimensions()
marker = IJ.createImage("marker", dimentions[0], dimentions[1], 1, 8)
marker.show()
rm = RoiManager.getInstance()
length = rm.getCount()

s = "marker=marker_c mask=mask_c distances=[Chessknight (5,7,11)] output=[16 bits]"
start_time = time.time()
for i in range(1, length):
    rm.setSelectedIndexes([0, i])
    rm.runCommand("AND")
    IJ.run("Measure")
    table = rstable.getResultsTable()
    X = table.getColumn(6)
    if X is None:
        IJ.run("Clear Results")
        continue
Example #39
0
width = 512
height = 512
  
pix = zeros(width * height, 'b')
Random().nextBytes(pix)

channel = zeros(256, 'b')
for i in range(256):
    channel[i] = (i -128) 
cm = LUT(channel, channel, channel)
imp = ImagePlus("Random", ByteProcessor(width, height, pix, cm))
imp.show()

# easy Random
imp = IJ.createImage("Easy Random Image", "8-bit", 512, 512, 1)
Random().nextBytes(imp.getProcessor().getPixels())
imp.show()

# Example watershed
# 1 - Obtain an image
blobs = IJ.openImage("http://imagej.net/images/blobs.gif")
# IJ.run(blobs, "Histogram", "")

# Make a copy with the same properties as blobs image:
imp = blobs.createImagePlus()
hwin = HistogramWindow(blobs)
plotimage = hwin.getImagePlus()


ip = blobs.getProcessor().duplicate()
from ij import IJ, ImagePlus
from ij.gui import Toolbar, Roi
from ij.process import Blitter
from java.awt import Color, Font, Polygon, Rectangle

w = 472
h = 354
xOffset = 59
yOffset = 120
radius = 20
arrowThickness = 14
fontName = 'Arial'
upperFontSize = 18
lowerFontSize = 10

image = IJ.createImage("MacOSX background picture", "rgb", w, h, 1)

# background
Toolbar.setForegroundColor(Color(0x5886ea))
Toolbar.setBackgroundColor(Color(0x3464c9))
IJ.run(image, "Radial Gradient", "")

# rounded rectangle
# correct for MacOSX bug: do the rounded rectangle in another image
image2 = image
image = IJ.createImage("MacOSX background picture", "rgb", w, h, 1)
image.setRoi(Roi(xOffset, yOffset, w - 2 * xOffset, h - 2 * yOffset))
IJ.run(image, "Make rectangular selection rounded", "radius=" + str(radius))
Toolbar.setForegroundColor(Color(0x435a96))
Toolbar.setBackgroundColor(Color(0x294482))
IJ.run(image, "Radial Gradient", "")
Example #41
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
Example #42
0
def merge(img1, img2, thresh1, thresh2):

    width1, height1 = img1.getWidth(), img1.getHeight()
    width2, height2 = img2.getWidth(), img2.getHeight()

    output = IJ.createImage("T_image", "16-bit", width1, height1, 1)
    output = output.getProcessor()

    alt_output_1 = IJ.createImage("T_image", "16-bit", width1, height1, 1)
    alt_output_1 = alt_output_1.getProcessor()

    alt_output_2 = IJ.createImage("T_image", "16-bit", width1, height1, 1)
    alt_output_2 = alt_output_2.getProcessor()

    img1_output = IJ.createImage("T_image", "16-bit", width1, height1, 1)
    img1_output = img1_output.getProcessor()

    img2_output = IJ.createImage("T_image", "16-bit", width2, height2, 1)
    img2_output = img2_output.getProcessor()

    composite_pixels = []
    img1_info = img1.getProcessor().convertToFloat()
    img2_info = img2.getProcessor().convertToFloat()

    thresh_val1 = max(img1_info.getPixels()) * (thresh1 / 100)
    thresh_val2 = max(img2_info.getPixels()) * (thresh2 / 100)

    for row in range(height1):
        for column in range(width1):
            img1_pixel = img1_info.getPixelValue(
                column,
                row,
            )
            if img1_pixel < thresh_val1:
                img1_pixel = 0
            else:
                img1_pixel = 255

            img2_pixel = img2_info.getPixelValue(
                column,
                row,
            )
            if img2_pixel < thresh_val2:
                img2_pixel = 0
            else:
                img2_pixel = 255

            min_pixel = int(min(img1_pixel, img2_pixel))
            alt_pixel_1 = get_alt_pixel(img1_pixel, img2_pixel)
            alt_pixel_2 = get_alt_pixel(img1_pixel, img2_pixel, variant=False)

            output.putPixel(column, row, min_pixel)
            alt_output_1.putPixel(column, row, alt_pixel_1)
            alt_output_2.putPixel(column, row, alt_pixel_2)

            img1_output.putPixel(column, row, img1_pixel)
            img2_output.putPixel(column, row, img2_pixel)

    output = ImagePlus("my_image", output.convertToFloat())
    alt_output_1 = ImagePlus("my_image", alt_output_1.convertToFloat())
    alt_output_2 = ImagePlus("my_image", alt_output_2.convertToFloat())

    img1_output = ImagePlus("my_image", img1_output.convertToFloat())
    img2_output = ImagePlus("my_image", img2_output.convertToFloat())

    return (output, alt_output_1, alt_output_2, img1_output, img2_output)
  return(imp)


def draw_cell(imp, i, nucleus_total, damage_total, title, noise):
  imp.append(impBG.duplicate()); 
  draw_nucleus( imp[i], nucleus_total / nucleus_area )
  draw_damage( imp[i], damage_total / damage_area )
  imp[i] = blur_and_noise(imp[i], 2, noise)
  imp[i].show()
  imp[i].setTitle(title)
  return(imp)

# Main

# Create background image
impBG = IJ.createImage("Untitled", "16-bit black", 512, 512, 1);
#IJ.run(imp, "RGB Color", "");
#IJ.run(imp, "Radial Gradient", "");
#IJ.run(imp, "16-bit", "");
#IJ.run(imp, "Multiply...", "value="+str(255));
#IJ.run(imp, "Gaussian Blur...", "sigma=30");
#IJ.run(imp, "Divide...", "value="+str(65535/background));
IJ.run(impBG, "Add...", "value="+str(background));



# Intensities
nucleus_total = 1000000

imps = []; 
i = -1;