コード例 #1
1
def main():
    # Open a .ome.tif image from the Flexoscope.
    impath = IJ.getFilePath("Choose .ome.tiff file")
    channels = Opener.openUsingBioFormats(impath)

    # Show image
    # imp.show() # straight to channels object sames memory.

    # Split channels.
    channels = ChannelSplitter().split(channels)

    # Process channel 1.
    # subtractzproject(imp, projectionMethod="Median")
    channels[1] = ImagePlus()
    channels.append(ImagePlus())
    channels[1] = subtractzproject(channels[0])
    IJ.run(channels[0], "Enhance Contrast...", "saturated=0.3 normalize process_all use")
    IJ.run(channels[0], "8-bit", "") 
    IJ.run(channels[1], "Square", "stack")
    IJ.run(channels[1], "Enhance Contrast...", "saturated=0.3 normalize process_all use")
    IJ.run(channels[1], "8-bit", "") 

    # Merge channels.
    merge = RGBStackMerge().mergeChannels(channels, True) # boolean keep
    merge.show()
コード例 #2
0
def rot3d(imp, axis='x'):
	"""pare back Slicer to implement whole-image, +90* rotations that return ImagePlus"""
	if imp.getType()==ImagePlus.COLOR_256 or imp.getType()==ImagePlus.COLOR_RGB:
		raise NotImplementedError("Handling of colour images isn't implemented yet");
	IJ.showStatus("Rotating around {}-axis...".format(axis))
	title = imp.getTitle();
	original_cal = imp.getCalibration();
	new_cal = original_cal;
	
	if imp.getNChannels > 1:
		split_ch = ChannelSplitter().split(imp);
	else:
		split_ch = [imp];

	out_imps = [];
	if axis=='x':
		for ch_imp in split_ch:
			input_stack = ch_imp.getStack();
			output_stack = rot_around_x(input_stack);
			out_imps.append(ImagePlus(title, output_stack));
			new_cal.pixelHeight = original_cal.pixelDepth;
			new_cal.pixelDepth = original_cal.pixelHeight;
	elif axis=='y' or axis=='-y':
		for ch_imp in split_ch:
			if axis[0]=='-':
				input_stack = StackProcessor(ch_imp.getStack()).rotateLeft();
			else:
				input_stack = StackProcessor(ch_imp.getStack()).rotateRight();
			output_stack = rot_around_x(input_stack);
			if axis[0]=='-':
				final_stack = StackProcessor(output_stack).rotateLeft();
			else:
				final_stack = StackProcessor(output_stack).rotateRight();
			out_imps.append(ImagePlus(title, final_stack));
			new_cal.pixelWidth = original_cal.pixelDepth;
			new_cal.pixelDepth = original_cal.pixelWidth;
	elif axis=='z' or axis=='-z':
		for ch_imp in split_ch:
			if axis[0]=='-':
				output_stack = StackProcessor(ch_imp.getStack()).rotateLeft();
			else:
				output_stack = StackProcessor(ch_imp.getStack()).rotateRight();
			out_imps.append(ImagePlus(title, output_stack));
			new_cal.pixelWidth = original_cal.pixelHeight;
			new_cal.pixelHeight = original_cal.pixelWidth;
	else:
		raise NotImplementedError("Please check which axis you've chosen - if not (x, +/-y, +/-z) then it's not implemented...");
	imp.changes = False;
	imp.close();
	if len(out_imps) > 1:
		out_imp = RGBStackMerge().mergeChannels(out_imps, False);
	else:
		out_imp = out_imps[0];
	out_imp.setCalibration(new_cal);
	return out_imp;
コード例 #3
0
ファイル: impActions.py プロジェクト: jrijn/FijiTools
def makemontage(imp, hsize=5, vsize=5, increment=1):
    """Makes a montage of a multichannel ImagePlus object.

    Args:
        imp (ImagePlus): An ImagePlus object.
        hsize (int, optional): Size of the horizontal axis. Defaults to 5.
        vsize (int, optional): Size of the vertical axis. Defaults to 5.
        increment (int, optional): The increment between images. Allows for dropping of e.g. every second frame. Defaults to 1.

    Returns:
        ImagePlus: The montage as ImagePlus object.
    """
    gridsize = hsize * vsize

    def _listProduct(inlist):
        """Calculates the product of all elements in a list.

        Args:
            inlist (list): A list of numbers.

        Returns:
            int or double: The product of all list elements.
        """
        product = 1

        for element in inlist:
            if isinstance(element, (int, float)):
                product = element * product

        return product

    def _channelmontage(_imp):
        """Makes a montage of a single channel ImagePlus object.

        Args:
            _imp (ImagePlus): A single channel ImagePlus object.

        Returns:
            ImagePlus: A montage of the one input channel.
        """
        dims = _imp.getDimensions(
        )  # width, height, nChannels, nSlices, nFrames
        frames = _listProduct(dims[2:])
        if frames > gridsize: frames = gridsize
        _montage = MontageMaker().makeMontage2(_imp, hsize, vsize, 1.00, 1,
                                               frames, increment, 0, True)
        return _montage

    name = imp.getTitle()
    channels = ChannelSplitter().split(imp)
    montages = [_channelmontage(channel) for channel in channels]
    montage = RGBStackMerge().mergeChannels(montages, False)
    montage.setTitle(name)
    return montage
コード例 #4
0
def open_images(in_folder):
    #open Red folder
    for i in os.listdir(os.path.join(in_folder, "Red")):
        file_path = os.path.join(in_folder, "Red", i)

        if os.path.isfile(file_path) and i.endswith(".tif"):
            print(i)
            cur_img_red = IJ.openImage(file_path)
            nslices_red = cur_img_red.getStack().getSize(
            )  # get the number slices in stack within the ImagePlus

    #open phase folder
    for i in os.listdir(os.path.join(in_folder, "Phase")):
        file_path = os.path.join(in_folder, "Phase", i)

        if os.path.isfile(file_path) and i.endswith(".tif"):
            print(i)
            cur_img_phase = IJ.openImage(file_path)
            nslices_phase = cur_img_phase.getStack().getSize(
            )  # get the number slices in stack within the ImagePlus

    if nslices_red != nslices_phase:
        sys.exit("Red and phase channel have unequal number of images!")

    timepoints = nslices_red

    ImageConverter(cur_img_phase).convertToGray16()

    comp_stack_img = RGBStackMerge.mergeChannels(
        [cur_img_red, None, None, cur_img_phase, None, None, None], True)

    return (comp_stack_img, timepoints)
コード例 #5
0
ファイル: impActions.py プロジェクト: jrijn/FijiTools
def _horcombine(imp_collection):
    """Combine a list of stacks with the same dimensions horizontally.

    Args:
        imp_collection: A list of stacks.

    Returns:
        A horizontally combined stack of the input images.
    """
    comb = imp_collection[0]
    comb_channels = ChannelSplitter().split(comb)
    comb_channels = [i.getImageStack() for i in comb_channels]

    for imp in imp_collection:

        if imp == imp_collection[0]:
            continue

        imp_channels = ChannelSplitter().split(imp)
        imp_channels = [i.getImageStack() for i in imp_channels]
        comb_channels = [
            StackCombiner().combineHorizontally(i, j)
            for i, j in zip(comb_channels, imp_channels)
        ]

    comb_channels = [
        ImagePlus("C{}".format(i + 1), channel)
        for i, channel in enumerate(comb_channels)
    ]
    impout = RGBStackMerge().mergeChannels(comb_channels,
                                           False)  # boolean keep
    return impout
コード例 #6
0
ファイル: tau_analysis.py プロジェクト: ksiller/axonanalyzer
def analyze(imagefile, outdir, size=10000):
	"""Opens a file and creates masks."""
	masks = []
	image = IJ.openImage(imagefile)
	imagetitle = image.getTitle().split(".")[0]

	# close existing Summary window
	rtframe = WindowManager.getFrame("Summary")
	if rtframe is not None:
	    rtframe.close()
	
	# segmentation
	IJ.setAutoThreshold(image, "Default dark");
	IJ.run(image, "Options...", "iterations=1 count=1 do=Nothing");
	#IJ.run(mask, "Convert to Mask", "");
	IJ.run(image, "Analyze Particles...", "size=0-"+str(size)+" show=Masks summarize");
	masks.append(IJ.getImage())
	IJ.run(image, "Analyze Particles...", "size="+str(size)+"-infinity show=Masks summarize");
	masks.append(IJ.getImage())
	
	# get ResultsTable object and save it
	rt = WindowManager.getFrame("Summary").getTextPanel().getResultsTable()
	rtfile = path.join(outdir, str(size)+"Summary_" + imagetitle + ".csv")
	rt.save(rtfile)

	# create multi-color merged mask
	mergedmask = RGBStackMerge.mergeChannels(masks, False)
	for m in masks:
	    m.close()
	mergedmask.setTitle(imagetitle + "-mask.tif")
	outputfile = path.join(outdir, mergedmask.getTitle())
	IJ.saveAs(mergedmask, "TIFF", outputfile)
コード例 #7
0
def analyse(imp, root, filename):
  imp.show()
  print ""
  print(imp.getTitle())
  print "**********************************"
  
  channels=(1,2,3)
  thresholds=(3000,1000,8000)  # day...
  backgrounds=thresholds #(175,0,275)

  #IJ.run(imp, "Gaussian Blur...", "sigma=1 stack");
  
  impA = []
  sumIntensities = []
  sumIntensitiesBW = []
  
  for iChannel in channels:

  	# general issues:
  	# - intensity decreases along z
  	
    # measure total intensity
    # - bg subtraction?
    impc = extractChannel(imp, iChannel, 1)
    impbw = threshold(impc, thresholds[iChannel-1]) 
    
    impcBGcorr = Duplicator().run(impc)
    IJ.run(impcBGcorr, "Subtract...", "value="+str(backgrounds[iChannel-1])+" stack");
    sumIntensities.append(measureSumIntensity3D(impcBGcorr))

    # measure number of pixels containing a signification signal
    # - what is good here for thresholding and preprocessing?
    #impbw = autoThreshold(impc, "Default")
    
    #impbw.setTitle("bw"+str(iChannel))
    #impbw.show()
    impA.append(impbw)
    sumIntensitiesBW.append(measureSumIntensity3D(impbw)/255)
    
  print "intensities,",str(sumIntensities)[1:-1]
  print "volumes,",str(sumIntensitiesBW)[1:-1] 

  sumIntensitiesNorm = [x / sumIntensitiesBW[1] for x in sumIntensities]
  sumIntensitiesBWNorm = [x / sumIntensitiesBW[1] for x in sumIntensitiesBW]
 
  print "intensities normalised,",str(sumIntensitiesNorm)[1:-1] 
  print "volumes normalised,",str(sumIntensitiesBWNorm)[1:-1] 

  impMerge = RGBStackMerge.mergeChannels(array(impA, ImagePlus), False)
  impMerge.setDisplayMode(IJ.COLOR);
  impMerge.setC(1);
  IJ.run(impMerge, "Green", "");
  impMerge.setC(2);
  IJ.run(impMerge, "Grays", "");
  impMerge.setC(3);
  IJ.run(impMerge, "Blue", "");
  impMerge.show()
  IJ.saveAs(impMerge, "Tiff", os.path.join(root, filename + "--segmented.tif"));
コード例 #8
0
    def mergechannels(self, root, sortedchannels, onGPU=False):
        '''
		Merge sorted channels(list of titles) under a given root title.
		If ColorMerger was initialized with a savefolder it will try to save img in savefolder
		else will merge channels, close original images and show the resulting composite.
		'''
        IJ.log("\n## Merging <{0}>".format(root))
        imgpaths = [
            os.path.join(self.imgfolder, title) if title else None
            for title in sortedchannels
        ]
        imps = [imageloader(path) if path else None for path in imgpaths]
        for img in imps:
            if img:
                calibration = img.getCalibration()
                break
        merger = RGBStackMerge()

        try:
            composite = merger.mergeChannels(imps, False)
        except (Exception, java.lang.Exception):
            t_name = current_thread().name
            IJ.log(
                "# {0}\t{1} images skipped as channels have different dimensions"
                .format(t_name, root))
            return

        composite.setCalibration(calibration)
        if self.savefolder:
            save_string = os.path.join(self.savefolder, root)
            try:
                FileSaver(composite).saveAsTiff(save_string)
                IJ.log("{0}".format(save_string))
            except (Exception, java.lang.Exception) as e:
                IJ.log(
                    "ij.io.FileSaver raised an {0} exception while trying to save img '{1}' as '{2}'. Skipping image."
                    .format(e, root, save_string))
        else:
            composite.setTitle(root)
            [imp.close() for imp in imps if imp]
            composite.show()
コード例 #9
0
def main():
    # Open a .ome.tif image from the Flexoscope.
    impath = IJ.getFilePath("Choose .ome.tiff file")
    channels = Opener.openUsingBioFormats(impath)
    cal = channels.getCalibration()

    # Show image
    # imp.show() # straight to channels object sames memory.

    # Split channels.
    channels = ChannelSplitter().split(channels)

    # Process channel 1.
    # subtractzproject(imp, projectionMethod="Median")
    channels[0] = subtractzproject(channels[0])
    IJ.run(channels[0], "8-bit", "") 

    # Process channel 2.
    # glidingprojection(imp, startframe=1, stopframe=None, glidingFlag=True, no_frames_per_integral=3, projectionmethod="Median")
    channels[1] = glidingprojection(channels[1]) 
    IJ.run(channels[1], "8-bit", "") 

    # [Optional] Process channel 3, 4, etc.
    # subtractzproject(channels[3], projectionMethod="Median")
    # glidingprojection(channels[3], startframe=1, stopframe=None, glidingFlag=True, no_frames_per_integral=3, projectionmethod="Median")
    # IJ.run(channels[3], "8-bit", "") 

    # Merge channels.
    merge = RGBStackMerge().mergeChannels(channels, True) # boolean keep
    merge.setCalibration(cal)
    merge.show()
コード例 #10
0
def merge_kymographs(kym1_imp, kym2_imp, params):
    """Merge two kymographs"""
    mrg_imp = RGBStackMerge().mergeChannels([kym1_imp, kym2_imp], True)
    mrg_imp.setTitle("Merged " + params.labeled_species +
                     " intensity and curvature kymograph")
    mrg_imp.show()
    return mrg_imp
コード例 #11
0
def downsample_for_isotropy(imp, extra_downsample_factor=2.0, info=None):
	"""downsample x, y pixel directions to get ~cubic voxels"""
	title = imp.getTitle();
	cal = imp.getCalibration();
	if info is None:
		pix_w = cal.pixelWidth;
		pix_h = cal.pixelHeight;
		pix_d = cal.pixelDepth;
	else:
		pix_w = info.get_xy_pixel_size_um();
		pix_h = pix_w;
		pix_d = info.get_z_plane_spacing_um();
	im_w = imp.getWidth();
	im_h = imp.getHeight();
	im_d = imp.getNSlices();
	print("original pixel whd = ({}, {}, {})".format(pix_w, pix_h, pix_d));
	print("original image whd = ({}, {}, {})".format(im_w, im_h, im_d));
	im_nch = imp.getNChannels();
	if im_nch > 1:
		split_ch = ChannelSplitter().split(imp);
	else:
		split_ch = [imp];
	print("downsampling {} and making isotropic...".format(title));
	IJ.showStatus("Downsampling and making ~isotropic...");
	xy_scale = pix_h / (pix_d * extra_downsample_factor);
	xy_scaled_h = int(xy_scale * im_h);
	xy_scaled_w = int(xy_scale * im_w);
	z_scale = 1/ extra_downsample_factor;
	z_scaled_h = int(z_scale * im_d);
	out_imps = [];
	for ch_imp in split_ch:
		print(ch_imp.getTitle());
		sp = StackProcessor(ch_imp.getStack());
		print((xy_scaled_w, xy_scaled_h));
		stack = sp.resize(xy_scaled_w, xy_scaled_h, True);
		xz_stack = rot_around_x(stack);
		xz_sp = StackProcessor(xz_stack);
		xz_stack = xz_sp.resize(xy_scaled_w, z_scaled_h, True);
		out_stack = rot_around_x(xz_stack);
		out_imps.append(ImagePlus("Isotropic downsampled {}".format(title), out_stack));
	cal.setUnit('um');
	cal.pixelWidth = im_w/xy_scaled_w * pix_w;
	cal.pixelHeight = im_h/xy_scaled_h * pix_h;
	cal.pixelDepth = im_d/z_scaled_h * pix_d;
	print("new pixel whd = ({}, {}, {})".format(cal.pixelWidth, cal.pixelHeight, cal.pixelDepth));
	imp.changes = False;
	imp.close();
	for ch_imp in split_ch:
		ch_imp.close();
	if len(out_imps) > 1:
		out_imp = RGBStackMerge().mergeChannels(out_imps, False);
	else:
		out_imp = out_imps[0];
	out_imp.setCalibration(cal);
	print("new image whd = ({}, {}, {})".format(out_imp.getWidth(), out_imp.getHeight(), out_imp.getNSlices()));
	print("...done downsampling {} and making isotropic. ".format(title));
	IJ.showStatus("...done downsampling and making ~isotropic. ");
	return out_imp;
コード例 #12
0
ファイル: mColoc3D.py プロジェクト: rejsmont/FijiScripts
	def previewImage(self, imp):
		roi = imp.getRoi()
		splitter = ChannelSplitter()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c))
			projector = ZProjector(channel)
			projector.setMethod(ZProjector.MAX_METHOD)
			projector.doProjection()
			channels.append(projector.getProjection())
		image = RGBStackMerge.mergeChannels(channels, False)
		image.title = imp.title + " MAX Intensity"
		image.luts = imp.luts
		imp.setRoi(roi)
		return image
コード例 #13
0
ファイル: mcoloc.py プロジェクト: rejsmont/FijiScripts
def getPreview(image):
	enhancer = ContrastEnhancer()
	projector = ZProjector()
	splitter = ChannelSplitter()
	imp1 = ImagePlus("CH1", )
	width, height, channels, slices, frames = image.getDimensions()
	chimps = []
	for ch in range(1, channels + 1):
		projector = ZProjector(ImagePlus("C%i" % ch, splitter.getChannel(image, ch)))
		projector.setMethod(ZProjector.MAX_METHOD)
		projector.doProjection()
		proj = projector.getProjection()
		enhancer.equalize(proj)
		chimps.append(proj)
		
	return RGBStackMerge.mergeChannels(chimps, False)
コード例 #14
0
ファイル: PreProcessor.py プロジェクト: schiklen/DotObjects
def preprocess(cell):
    print cell.getRawImageFilePath()
    imp = Opener().openImage(cell.getRawImageFilePath()) # open raw Image
    #if imp.getBitDepth() != 8:  # converting to 8 bit if 
    #   ImageConverter(imp).convertToGray8()
    roi = imp.roi
    imps = CS.split(imp)
    p = Preprocessor()
    for aimp in imps:
        p.setImp(aimp)
        p.run()
        if roi != None:
            aimp.setRoi(roi)
            for n in range(1, aimp.getImageStackSize()+1):
                aimp.getImageStack().getProcessor(n).fillOutside(roi)
            aimp.killRoi()
        final = StackMerge.mergeChannels(imps, False)
        final.copyScale(imp) # copyscale from .copyscale
    return final
コード例 #15
0
def analyze(image, outdir, index, size=10000):
	"""Opens a file and creates masks."""
	masks = []
	imagetitle = image.getTitle().split(".")[0]

	# segmentation
	IJ.setAutoThreshold(image, "Default dark");
	IJ.run(image, "Options...", "iterations=1 count=1 do=Nothing");
	#IJ.run(mask, "Convert to Mask", "");
	IJ.run(image, "Analyze Particles...", "size=0-"+str(size)+" show=Masks summarize display");
	masks.append(IJ.getImage())
	IJ.run(image, "Analyze Particles...", "size="+str(size)+"-infinity show=Masks summarize display");
	masks.append(IJ.getImage())
	
	# create multi-color merged mask
	mergedmask = RGBStackMerge.mergeChannels(masks, False)
	for m in masks:
	    m.close()
	mergedmask.setTitle(imagetitle + "-"+str(index)+"-mask.tif")
	outputfile = path.join(outdir, mergedmask.getTitle())
	IJ.saveAs(mergedmask, "TIFF", outputfile)
コード例 #16
0
 	print 'yellow image file: ' + green_id
        g_imp = ImagePlus(img_dir+'/'+green_id)
        imps_for_comp[1] = g_imp
    if red:
        red_id = color_sublists['rfp'][stage_pos]
  	print 'red image file: ' + red_id
        r_imp = ImagePlus(img_dir+'/'+red_id)
        imps_for_comp[5] = r_imp
    if brightfield:
        bf_id = color_sublists['bf'][stage_pos]
	print 'brightfield image file: ' + bf_id
        bf_imp = ImagePlus(img_dir+'/'+bf_id)
    print ''
    if 'w' in colors:
	if len(colors) > 2:
    	    composite = RGBStackMerge.mergeChannels(imps_for_comp, True)
    	    IJ.saveAsTiff(composite, merge_output_dir + '/' + stage_pos)
    	    composite.close()
    else:
	if len(colors) > 1:
    	    composite = RGBStackMerge.mergeChannels(imps_for_comp, True)
    	    IJ.saveAsTiff(composite, merge_output_dir + '/' + stage_pos)
    	    composite.close()
    imps_for_z_comp = [None, None, None, None, None, None, None]
    if blue:
        z_cyan = maxZprojection(c_imp)
        IJ.saveAsTiff(z_cyan, z_proj_dir+'/blue/'+stage_pos)
        imps_for_z_comp[4] = z_cyan
        c_imp.close()
    if cyan:
        z_cyan = maxZprojection(c_imp)
コード例 #17
0
        k = k + 1
        stack.addSlice(
            str(k),
            FloatProcessor(h, w, doutarray[ioffset:(ioffset + planesize)]))
        ioffset = ioffset + planesize
#outds1 = ijmService.getDataset(doutMNarray)
imp.setStack(stack, c, z, 1)

if c == 2:
    outds1 = extractChannel(imp, 1, 2)
    outds2 = extractChannel(imp, 2, 2)
    #  outds1 = createChannel(doutarray,h,w,z,1)
    #  outds2 = createChannel(doutarray,h,w,z,2)
    outds1.setColor(java.awt.Color.RED)
    outds2.setColor(java.awt.Color.GREEN)
    outds = RGBStackMerge.mergeChannels(array([outds1, outds2], ImagePlus), 0)
else:
    if c > 2:
        outds1 = extractChannel(imp, 1, 3)
        outds2 = extractChannel(imp, 2, 3)
        outds3 = extractChannel(imp, 3, 3)
        outds1.setColor(java.awt.Color.RED)
        outds2.setColor(java.awt.Color.GREEN)
        outds3.setColor(java.awt.Color.BLUE)
        outds = RGBStackMerge.mergeChannels(
            array([outds1, outds2, outds3], ImagePlus), 0)
    else:
        outds = imp
outds.show()
IJ.run(
    "Multichannel ZT-axis Profile",
コード例 #18
0
    _filtered = [threshold(p) for p in chpx[i]]  # filtered pixels
    filtered.append(FloatProcessor(ip.width, ip.height, _filtered, None))

# save each channels
for i in range(3):
    IJ.save(ImagePlus("filtered_%d" % i, filtered[i]),
            dstpath[:-4] + '_%d' % i)

# add slices to new stack
stack_new = ImageStack(imp.width, imp.height)

for i in range(3):
    stack_new.addSlice(None, filtered[i])

# new image (stack)
imp_new = ImagePlus("new", stack_new)
imp_new.show()
IJ.save(imp_new, dstpath[:-4] + '_stack.tif')

# new image (color)
mergeimp = RGBStackMerge.mergeChannels([
    ImagePlus(None, filtered[0]),
    ImagePlus(None, filtered[1]),
    ImagePlus(None, filtered[2]), None, None, None, None
], False)
mergeimp.title = "filtered"
RGBStackConverter.convertToRGB(mergeimp)
mergeimp.show()
IJ.save(mergeimp, dstpath)
コード例 #19
0
    imRed=IJ.openImage(rFn)
    imTL=IJ.openImage(tlFn)

    # imGreen.show()
    # imRed.show()
    # imTL.show()

    # stack=ij.ImageStack(imRed.width, imRed.height)

    # stack.addSlice("red", imRed.getProcessor())
    # stack.addSlice("green", imGreen.getProcessor())
    # stack.addSlice("tl", imTL.getProcessor())

    # imstack=ij.ImagePlus("Stack", stack)

    imMerge=RGBStackMerge.mergeChannels([imRed, imGreen, None, imTL], True)

    #The merged image is a composite with three seperate channels. For now, we just want to convert the thing to RGB and save it out. 

    RGBStackConverter.convertToRGB(imMerge)

    saveFn=os.path.join(analysisPath, tlFn[-9:-7], 'Merge.jpg'
    #imMerge.show()

    if stack==None:
        stack=Stack("MergedChannels", imMerge)
    else:fiji
        stack+=imMerge
    
    FileSaver(imMerge).saveAsJpeg(saveFn)
コード例 #20
0
def processFile():
	# start logging
	IJ.log("\n______________________________\n\n\t\tOlympus DM correction\n\t\tVersion " + pluginVersion +"\n______________________________\n")

	# ask user for file
	ofd = OpenDialog("Choose a file", None)  
	filename = ofd.getFileName()  
  
	if filename is None:  
  		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
  		return

  	directory = ofd.getDirectory()  
  	filepath = directory + filename  
  	IJ.log("File path: " + filepath)

	if not filename.endswith(".oir"):
		IJ.log("Not an Olympus (.oir) file.\nNo image to process.\n")
		return

	filenameExExt = os.path.splitext(filename)[0]
      
	# parse metadata
	reader = ImageReader()
	omeMeta = MetadataTools.createOMEXMLMetadata()
	reader.setMetadataStore(omeMeta)
	reader.setId(filepath)
	numChannels = reader.getSizeC()
	numSlices = reader.getSizeZ()
	numFrames = reader.getSizeT()
	seriesCount = reader.getSeriesCount()

	globalMetadata = reader.getGlobalMetadata()
	seriesMetadata = reader.getSeriesMetadata()

	objLensName = globalMetadata['- Objective Lens name #1']

	areaRotation = float(seriesMetadata['area rotation #1'])
	acquisitionValueRotation = float(seriesMetadata['acquisitionValue rotation #1'])
	if 'regionInfo rotation #1' in seriesMetadata:
		regionInfoRotation = float(seriesMetadata['regionInfo rotation #1'])
	else:
		regionInfoRotation = float(0)

	totalRotation = areaRotation + regionInfoRotation
	physSizeX = omeMeta.getPixelsPhysicalSizeX(0)
	physSizeY = omeMeta.getPixelsPhysicalSizeY(0)
	pxSizeX = physSizeX.value(UNITS.MICROM)
	pxSizeY = physSizeY.value(UNITS.MICROM)

	# log metadata
	IJ.log("\nMETADATA")
	#IJ.log("Filename: " + filepath)
	IJ.log("Number of series: " + str(seriesCount))
	IJ.log("Number of channels: " + str(numChannels))
	IJ.log("Number of frames: " + str(numFrames))
	IJ.log("Number of slices: " + str(numSlices))
	IJ.log("Objective lens: " + objLensName)
	IJ.log("FOV rotation: " + str(areaRotation))
	IJ.log("ROI rotation: " + str(regionInfoRotation))
	IJ.log("Total rotation: " + str(totalRotation))
	IJ.log("Pixel size:")
	IJ.log("\t\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol())
	IJ.log("\t\tY = " + str(physSizeY.value()) + " " + physSizeY.unit().getSymbol())

	# ask user to identify dichroic mirror used for each channel  
	gdDM = GenericDialog("Dichroic mirrors")
	DMs = ["DM1", "DM2", "DM3", "DM4", "DM5"] 
	for i in range(numChannels):
		gdDM.addChoice("Channel " + str(i+1), DMs, DMs[0])
	gdDM.addCheckbox("Merge channels", False) 
	gdDM.showDialog()
	if gdDM.wasCanceled():
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
		return
	dichroics = []
	for i in range(numChannels):
		dichroics.append(gdDM.getNextChoice())
	merge = gdDM.getNextBoolean()
	IJ.log("\nUser selected dichroic mirrors")
	for i in range(numChannels):
		IJ.log("\t\tChannel " + str(i+1) + ": " + dichroics[i])	

	if merge:
		channels = []
		chDict = {}
		for i in range(numChannels):
			chName = "Channel"+str(i+1)
			channels.append(chName)
			chDict[chName] = i
		channels.append("NONE")
		colourChoices = ["red", "green", "blue", "gray", "cyan", "magenta", "yellow"]
		gdMerge = GenericDialog("Merge channels")
		for c in colourChoices:
			gdMerge.addChoice(c + ":", channels, channels[numChannels])
		gdMerge.showDialog()
		if gdMerge.wasCanceled():
			IJ.log("User canceled the dialog!\nImage processing canceled!\n")
			return
		IJ.log("\nUser selected channel colours")
		mergeList = []
		for i in range(len(colourChoices)):
			ch = gdMerge.getNextChoice()
			if ch == "NONE":
				mergeList.append(None)
			else:
				mergeList.append(chDict[ch])
				IJ.log("\t\t" + colourChoices[i] + ": " + ch)

	# ask user for an output directory
	dc = DirectoryChooser("Choose folder for output")  
	od = dc.getDirectory()    
	if od is None:  
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")  
		return  
  
	if merge:
		tifDir = od + "." + str(datetime.now()).replace(" ", "").replace(":", "") + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated temporary folder: " + tifDir + "\n")
		else:
			IJ.log("Unable to create temporary folder!\n")
	else:
		tifDir = od + filenameExExt + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated subfolder: " + tifDir + "\n")
		else:
			IJ.log("\nSubfolder " + tifDir +  " already exists")

	# correct images
	tifFilePaths = []
	for i in range(numChannels):
		ip = extractChannel(oirFile=filepath, ch=i)
		if dichroics[i] == "DM1":
			IJ.log("Channel " + str(i+1) + " was imaged using DM1, so no correction required.")
		else:
			offsets = getOffset(obj=objLensName,dm=dichroicDict[dichroics[i]])
			xom = offsets['x']
			yom = offsets['y']
			if abs(totalRotation) > 0.1:
				rotOff = rotateOffset(x=xom, y=yom, angle=-totalRotation)
				xom = rotOff['x']
				yom = rotOff['y']
			xop = int(round(xom/pxSizeX))
			yop = int(round(yom/pxSizeY))
			IJ.log("Channel " + str(i+1) + " offsets")
			IJ.log("\t\tMicrometres")
			IJ.log("\t\t\t\tx = " + str(xom))
			IJ.log("\t\t\t\ty = " + str(yom))
			IJ.log("\t\tPixels")
			IJ.log("\t\t\t\tx = " + str(xop))
			IJ.log("\t\t\t\ty = " + str(yop))
			IJ.run(ip, "Translate...", "x=" + str(-xop) + " y=" + str(-yop) + " interpolation=None stack")

		tifFilePath = tifDir + filenameExExt + "_ch_"+str(i+1)+".tif"
		tifFilePaths.append(tifFilePath)
		if os.path.exists(tifFilePath):
			IJ.log("\nOutput file exists: " + tifFilePath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
			return
		FileSaver(ip).saveAsTiff(tifFilePath)

	if merge:
		for i in range(len(mergeList)):
			if mergeList[i] != None:
				mergeList[i] = readSingleChannelImg(tifFilePaths[mergeList[i]])
		merged = RGBStackMerge.mergeChannels(mergeList, False)
		mergedChannelFilepath = od + filenameExExt + ".tif"
		if os.path.exists(mergedChannelFilepath):
			IJ.log("\nOutput file exists: " + mergedChannelFilepath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
		FileSaver(merged).saveAsTiff(mergedChannelFilepath)
		for tf in tifFilePaths:
			os.remove(tf)
		os.rmdir(tifDir)
			
	IJ.log("\nFinished processing file:\n" + filepath + "\n")
	if merge:
		IJ.log("Image file with channels aligned:\n" + od + filenameExExt + ".tif\n")
	else:
		IJ.log("Aligned images (one tiff file for each channel) can be found in:\n" + tifDir + "\n")
def processFile(filename, inDir, outDir, dichroics, mergeList):

	if mergeList is None:
		merge = False
	else:
		merge = True
	
	filenameExExt = os.path.splitext(filename)[0]
	filepath = inDir + filename
      
	# parse metadata
	reader = ImageReader()
	omeMeta = MetadataTools.createOMEXMLMetadata()
	reader.setMetadataStore(omeMeta)
	reader.setId(filepath)
	numChannels = reader.getSizeC()
	numSlices = reader.getSizeZ()
	numFrames = reader.getSizeT()
	seriesCount = reader.getSeriesCount()

	globalMetadata = reader.getGlobalMetadata()
	seriesMetadata = reader.getSeriesMetadata()

	objLensName = globalMetadata['- Objective Lens name #1']

	areaRotation = float(seriesMetadata['area rotation #1'])
	acquisitionValueRotation = float(seriesMetadata['acquisitionValue rotation #1'])
	if 'regionInfo rotation #1' in seriesMetadata:
		regionInfoRotation = float(seriesMetadata['regionInfo rotation #1'])
	else:
		regionInfoRotation = float(0)

	totalRotation = areaRotation + regionInfoRotation
	physSizeX = omeMeta.getPixelsPhysicalSizeX(0)
	physSizeY = omeMeta.getPixelsPhysicalSizeY(0)
	pxSizeX = physSizeX.value(UNITS.MICROM)
	pxSizeY = physSizeY.value(UNITS.MICROM)

	# log metadata
	IJ.log("\nMETADATA")
	#IJ.log("Filename: " + filepath)
	IJ.log("Number of series: " + str(seriesCount))
	IJ.log("Number of channels: " + str(numChannels))
	IJ.log("Number of frames: " + str(numFrames))
	IJ.log("Number of slices: " + str(numSlices))
	IJ.log("Objective lens: " + objLensName)
	IJ.log("FOV rotation: " + str(areaRotation))
	IJ.log("ROI rotation: " + str(regionInfoRotation))
	IJ.log("Total rotation: " + str(totalRotation))
	IJ.log("Pixel size:")
	IJ.log("\t\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol())
	IJ.log("\t\tY = " + str(physSizeY.value()) + " " + physSizeY.unit().getSymbol())
  
	if merge:
		tifDir = outDir + "." + str(datetime.now()).replace(" ", "").replace(":", "") + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated temporary folder: " + tifDir + "\n")
		else:
			IJ.log("Unable to create temporary folder!\n")
	else:
		tifDir = outDir + filenameExExt + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated subfolder: " + tifDir + "\n")
		else:
			IJ.log("\nSubfolder " + tifDir +  " already exists.\n")

	# correct images
	tifFilePaths = []
	for i in range(numChannels):
		ip = extractChannel(oirFile=filepath, ch=i)
		if dichroics[i] == "DM1":
			IJ.log("Channel " + str(i+1) + " was imaged using DM1, so no correction required.")
		else:
			offsets = getOffset(obj=objLensName,dm=dichroicDict[dichroics[i]])
			xom = offsets['x']
			yom = offsets['y']
			if abs(totalRotation) > 0.1:
				rotOff = rotateOffset(x=xom, y=yom, angle=-totalRotation)
				xom = rotOff['x']
				yom = rotOff['y']
			xop = int(round(xom/pxSizeX))
			yop = int(round(yom/pxSizeY))
			IJ.log("Channel " + str(i+1) + " offsets")
			IJ.log("\t\tMicrometres")
			IJ.log("\t\t\t\tx = " + str(xom))
			IJ.log("\t\t\t\ty = " + str(yom))
			IJ.log("\t\tPixels")
			IJ.log("\t\t\t\tx = " + str(xop))
			IJ.log("\t\t\t\ty = " + str(yop))
			IJ.run(ip, "Translate...", "x=" + str(-xop) + " y=" + str(-yop) + " interpolation=None stack")

		tifFilePath = tifDir + filenameExExt + "_ch_"+str(i+1)+".tif"
		tifFilePaths.append(tifFilePath)
		if os.path.exists(tifFilePath):
			IJ.log("\nOutput file exists: " + tifFilePath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
			return
		FileSaver(ip).saveAsTiff(tifFilePath)

	if merge:
		max_list = []
		for i in range(len(mergeList)):
			if mergeList[i] != None:
				mergeList[i] = readSingleChannelImg(tifFilePaths[mergeList[i]])
				channel = mergeList[i]#https://python.hotexamples.com/examples/ij.plugin/RGBStackMerge/mergeChannels/python-rgbstackmerge-mergechannels-method-examples.html
				projector = ZProjector(channel)
				projector.setMethod(ZProjector.MAX_METHOD)
				projector.doProjection()
				max_list.append(projector.getProjection())
		merged = RGBStackMerge.mergeChannels(mergeList, False)
		merged_max = RGBStackMerge.mergeChannels(max_list, False)
		mergedChannelFilepath = outDir + filenameExExt + ".tif"
		maxMergedChannelFilepath = outDir + filenameExExt + "_max.tif"
		if os.path.exists(mergedChannelFilepath):
			IJ.log("\nOutput file exists: " + mergedChannelFilepath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
		FileSaver(merged).saveAsTiff(mergedChannelFilepath)
		FileSaver(merged_max).saveAsTiff(maxMergedChannelFilepath)
		for tf in tifFilePaths:
			os.remove(tf)
		os.rmdir(tifDir)	

	IJ.log("\nFinished processing file:\n" + filepath + "\n")
	if merge:
		IJ.log("Image file with channels aligned:\n" + outDir + filenameExExt + ".tif\n")
	else:
		IJ.log("Aligned images (one tiff file for each channel) can be found in:\n" + tifDir + "\n")
コード例 #22
0
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
コード例 #23
0
def processImage(filename):
    # many zeiss images have a pyramid format. In order to speed up the evaluation, we chose only the second highest resolution (=series_2).
    # depending on your computer/workstation this parameter can be optimized (i.e. chose series_1 if you have a fast computer or series_3 for slow ones)
    IJ.run(
        "Bio-Formats", "open=" + filename +
        " color_mode=Composite rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT series_2"
    )
    imp = IJ.getImage()
    imp.show()
    if (not entertain):
        imp.show()

    # preparing memory for saving the results
    original1 = NewImage.createFloatImage("Original 1",
                                          imp.getWidth() / tileSize + 1,
                                          imp.getHeight() / tileSize + 1, 1,
                                          NewImage.FILL_BLACK)
    original1Map = original1.getProcessor()

    original2 = NewImage.createFloatImage("Original 2",
                                          imp.getWidth() / tileSize + 1,
                                          imp.getHeight() / tileSize + 1, 1,
                                          NewImage.FILL_BLACK)
    original2Map = original2.getProcessor()

    spotCount1 = NewImage.createFloatImage("Spot count 1",
                                           imp.getWidth() / tileSize + 1,
                                           imp.getHeight() / tileSize + 1, 1,
                                           NewImage.FILL_BLACK)
    spotCount1Map = spotCount1.getProcessor()

    spotCount2 = NewImage.createFloatImage("Spot count 2",
                                           imp.getWidth() / tileSize + 1,
                                           imp.getHeight() / tileSize + 1, 1,
                                           NewImage.FILL_BLACK)
    spotCount2Map = spotCount2.getProcessor()

    ratio = NewImage.createFloatImage("Ratio",
                                      imp.getWidth() / tileSize + 1,
                                      imp.getHeight() / tileSize + 1, 1,
                                      NewImage.FILL_BLACK)
    ratioMap = ratio.getProcessor()

    if (entertain):
        ratio.show()

    # go through all tiles
    for x in range(0, ratioMap.getWidth() - 1):
        for y in range(0, ratioMap.getHeight() - 1):
            # crop out the tile from the original images
            imp.setRoi(Roi(x * tileSize, y * tileSize, tileSize, tileSize))
            channel1 = Duplicator().run(imp, 1, 1, 1, 1, 1, 1)
            channel2 = Duplicator().run(imp, 2, 2, 1, 1, 1, 1)

            # spot detection
            spots1 = detectSpots(channel1,
                                 spotDetection_GaussianBlur_sigma_GFP,
                                 spotDetection_findMaxima_noise_GFP)
            spots2 = detectSpots(channel2,
                                 spotDetection_GaussianBlur_sigma_DAPI,
                                 spotDetection_findMaxima_noise_DAPI)

            # pixel statistics
            statistics1 = channel1.getStatistics()
            statistics2 = channel2.getStatistics()

            # calculate ratio if spots were found
            s1 = 0
            s2 = 0
            r = 0
            if (spots1 is not None and spots2 is not None):
                fp1 = spots1.getFloatPolygon()
                fp2 = spots2.getFloatPolygon()
                s1 = fp1.npoints
                s2 = fp2.npoints
                if (s2 > cutOff_DAPI and s1 > cutOff_GFP):
                    r = 1.0 * s1 / s2

            # fill result memory
            original1Map.setf(x, y, statistics1.mean)
            original2Map.setf(x, y, statistics2.mean)
            spotCount1Map.setf(x, y, s1)
            spotCount2Map.setf(x, y, s2)
            ratioMap.setf(x, y, r)

        if (entertain):
            # show current result image
            ratio.updateAndDraw()
            IJ.run(ratio, "Enhance Contrast", "saturated=0.35")

    # put all results image channels together to one image
    images = []
    images.append(original1)
    images.append(original2)
    images.append(spotCount1)
    images.append(spotCount2)
    images.append(ratio)
    resultMap = RGBStackMerge.mergeChannels(images, False)

    # fix pixel size
    # factor is multiplied by 2 because ImageJ seems to have a problem when using .czi file series of lower resolution (i.e. series_2); please check for individual cases!
    factor = (imp.getWidth() / resultMap.getWidth()) * 2
    IJ.run(
        resultMap, "Properties...", "channels=5 slices=1 frames=1 unit=" +
        imp.getCalibration().getUnit() + " pixel_width=" +
        str(imp.getCalibration().pixelWidth * factor) + " pixel_height=" +
        str(imp.getCalibration().pixelHeight * factor) + " voxel_depth=1.0000")
    IJ.run(
        ratio, "Properties...", "channels=1 slices=1 frames=1 unit=" +
        imp.getCalibration().getUnit() + " pixel_width=" +
        str(imp.getCalibration().pixelWidth * factor) + " pixel_height=" +
        str(imp.getCalibration().pixelHeight * factor) + " voxel_depth=1.0000")

    # visualisation
    resultMap.setC(1)
    IJ.run(resultMap, "Green", "")
    IJ.run(resultMap, "Enhance Contrast", "saturated=0.35")
    resultMap.setC(2)
    IJ.run(resultMap, "Blue", "")
    IJ.run(resultMap, "Enhance Contrast", "saturated=0.35")
    resultMap.setC(3)
    IJ.run(resultMap, "mpl-inferno", "")
    IJ.run(resultMap, "Enhance Contrast", "saturated=0.35")
    resultMap.setC(4)
    IJ.run(resultMap, "mpl-inferno", "")
    IJ.run(resultMap, "Enhance Contrast", "saturated=0.35")
    resultMap.setC(5)
    IJ.run(resultMap, "mpl-inferno", "")
    resultMap.show()
    IJ.resetMinAndMax(resultMap)
    resultMap.setDisplayMode(IJ.COLOR)

    IJ.run(ratio, "mpl-inferno", "")
    IJ.setMinAndMax(ratio, 0, 1)

    # save result
    IJ.saveAsTiff(resultMap, filename + "_suitable-name_map.tif")
    IJ.saveAsTiff(ratio, filename + "_suitable-name_ratio.tif")

    IJ.run("Close All", "")
コード例 #24
0
ファイル: mcoloc.py プロジェクト: rejsmont/FijiScripts
		thr1, thrimp1 = calculateThreshold(imp1, roi, methods[0])
		thr2, thrimp2 = calculateThreshold(imp2, roi, methods[1])
		
		cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
		rtype = img1.randomAccess().get().createVariable()
		raw = manders.calculateMandersCorrelation(cursor, rtype)
		rthr1 = rtype.copy()
		rthr2 = rtype.copy()
		rthr1.set(thr1)
		rthr2.set(thr2)
		cursor.reset()
		thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
		print "Results are: %f %f %f %f" % (raw.m1, raw.m2, thrd.m1, thrd.m2)

		results.incrementCounter()
		rowno = results.getCounter() - 1
		results.setValue("Cell", rowno, int(rowno))
		results.setValue("Threshold 1", rowno, int(thr1))
		results.setValue("Threshold 2", rowno, int(thr2))
		results.setValue("M1 raw", rowno, float(raw.m1))
		results.setValue("M2 raw", rowno, float(raw.m2))
		results.setValue("M1 thrd", rowno, float(thrd.m1))
		results.setValue("M2 thrd", rowno, float(thrd.m2))
		
		thrimp = RGBStackMerge.mergeChannels([thrimp1, thrimp2], False)
		saver = FileSaver(thrimp)
		saver.saveAsTiffStack(outputDir + "Cell_%i-" % results.getCounter() + title + ".tif")
		thrimp.close()

results.show("Colocalization results")
コード例 #25
0
ファイル: MaskView.py プロジェクト: kapoorlab/IJCurieMacros
def batch_open_images(pathImage,
                      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: Reject files that contain the given string (default: wild characters).
    :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 = []
    Masks = []
    for img_path, file_name in path_to_Image:
        # IJ.openImage() returns an ImagePlus object or None.
        imp = IJ.openImage(img_path)
        imp.show()
        IJ.run("8-bit")
        print(img_path)
        if check_filter(file_name):
            continue
        else:
            # An object equals True and None equals False.

            MaskName = str(pathMask) + '/' + "Mask" + file_name + '.tif'
            Mask = IJ.openImage(MaskName)
            Mask.show()
            IJ.run("8-bit")
            IJ.run("Find Edges")
            IJ.selectWindow(file_name + ".tif")
            IJ.selectWindow("Mask" + file_name + ".tif")
            Mask.changes = False
            imp.changes = False

            impResult = RGBStackMerge.mergeChannels([imp, Mask], False)
            impResult.show()
            IJ.saveAs(impResult, '.tif',
                      str(pathMask) + "/" + file_name)
            imp.close()
            Mask.close()

            #print(img_path, RoiName)
            Images.append(imp)
    return Images
コード例 #26
0
ファイル: Deep_CLEM.py プロジェクト: ed17usiv/Deep_CLEM
# overwrite EM stack with transformed EM image
fs = FileSaver(EM)
fs.saveAsTiff(saveEMfilepath)

# open EM image as ImagePlus for merging channel
EM = ImagePlus(saveEMfilepath)

# split rLM image in different channels
saverLMpath = os.path.join(transformation_output, "rLM.tif")
rLM = IJ.openImage(saverLMpath)
R, G, B = ChannelSplitter.split(rLM)

# Merge channels
overlay = RGBStackMerge.mergeChannels(
    [None, None, B, EM, None, None, None],
    True)  # Change R,G, B if the chromatin channel is a different one.
# If you want a different color for the chromatin in the overlay image, change the  position of the letter R,G,B,
# e.g. [B, None, None, EM, None, None, None] for displaying chromatin in the red channel.
RGBStackConverter.convertToRGB(overlay)

# save overlay
saveoverlaypath = os.path.join(workdir, "overlay_EM_Chromatin.tif")
fs = FileSaver(overlay)
fs.saveAsTiff(saveoverlaypath)

print("(----- )overlay EM and rLM image done")

############################################ clean up

# copy important files into the working directory
コード例 #27
0
ファイル: mColoc3D.py プロジェクト: rejsmont/FijiScripts
	def saveMultichannelImage(self, title, channels, luts):
		tmp = RGBStackMerge.mergeChannels(channels, False)
		tmp.luts = luts
		saver = FileSaver(tmp)
		saver.saveAsTiffStack(self.outputDir + title + ".tif")
		tmp.close()
コード例 #28
0
ファイル: test_channel_merge.py プロジェクト: zvtrung/tips
----------  ---  ----------------------------------------------------
2019-06-16  JRM  Initial adaptation. Use the GIT_HOME environment
                 variable to get the start of the path


"""

import os
from ij import IJ, ImagePlus
from ij.plugin import RGBStackMerge, RGBStackConverter

# use a path relative to the GIT_HOME environment variable
git_home = os.getenv("GIT_HOME")
print(git_home)

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

# Load the R, G, and B color separation images. These were created
# using make_mandrill_256.py
impc1 = ImagePlus(git_home + "/tips/ImageJ/tif/mandrill_256_red.tif")
impc2 = ImagePlus(git_home + "/tips/ImageJ/tif/mandrill_256_green.tif")
impc3 = ImagePlus(git_home + "/tips/ImageJ/tif/mandrill_256_blue.tif")

# merge my three images
imp_merge = RGBStackMerge.mergeChannels([impc1, impc2, impc3], True)

# convert the composite image to the RGB image
RGBStackConverter.convertToRGB(imp_merge)

imp_merge.show()
コード例 #29
0
            IJ.setThreshold(green_coloc,summary["Green" + "-threshold-used"], 255);
            IJ.run(green_coloc, "Convert to Mask", "");
            pa_green.analyze(green_coloc)
#            green_coloc.show()
            rt4 = ResultsTable()
            ta_coloc2=Analyzer(green_coloc,Measurements.INTEGRATED_DENSITY ,rt4);
            ta_coloc2.measure();
            greenIntensity=(rt4.getColumnAsDoubles(rt4.getColumnIndex("IntDen")))[0];

            ic_coloc =ImageCalculator();
            coloc_img=ic_coloc.run("Multiply create",red_coloc,green_coloc);
            rt5 = ResultsTable()
            ta_coloc3=Analyzer(coloc_img,Measurements.INTEGRATED_DENSITY ,rt5);
            ta_coloc3.measure();
            totalIntensity=(rt5.getColumnAsDoubles(rt5.getColumnIndex("IntDen")))[0];
            rgb=RGBStackMerge();
            composite=rgb.mergeChannels([red_coloc,green_coloc],False); 
            composite.show();
            fs=FileSaver(composite);
            fs.saveAsJpeg(outputDirectory + '/' + "coloc_"+filename);
            composite.close();
            
            if redIntensity == 0:
                summary["Red-Green-Coloc-%"]= "NaN"
            else:
            	summary["Red-Green-Coloc-%"]= float (totalIntensity*100/redIntensity)
            
            if greenIntensity == 0:
                summary["Green-Green-Coloc-%"]= "NaN"
            else:
            	summary["Green-Red-Coloc-%"]= float (totalIntensity*100/greenIntensity)
コード例 #30
0
if gd.wasOKed():
	amplifyChannel = gd.getNextChoiceIndex() + 1
	refChannel = gd.getNextChoiceIndex() + 1
	ampFactor = gd.getNextNumber()
	doRemoveBleedthrough = gd.getNextBoolean()
	doCorrectRefraction = gd.getNextBoolean()
	chImages = ChannelSplitter.split(theImage)
	
	## After this step, the image to operate on is "nextStepImage"
	if doRemoveBleedthrough:
		params = ("bleeding_channel=" + str(refChannel) + " bloodied_channel=" + str(amplifyChannel) + " " +
				"allowable_saturation_percent=1.0 rsquare_threshold=0.50")
		IJ.run("Remove Bleedthrough (automatic)", params)
		unbledImage = WindowManager.getImage("Corrected_ch" + str(amplifyChannel))
		mergingImages = [unbledImage,chImages[refChannel-1].duplicate()]
		nextStepImage = RGBStackMerge.mergeChannels(mergingImages,True)
		#nextStepImage.show()
		unbledImage.close()
		for img in mergingImages:
			img.close()
	else:
		mergingImages = [chImages[amplifyChannel-1].duplicate(),chImages[refChannel-1].duplicate()]
		nextStepImage = RGBStackMerge.mergeChannels(mergingImages,True)
		#nextStepImage.show()
		for img in mergingImages:
			img.close()
	for img in chImages:
		img.close()
	# theImage.close()

	## After this step, the image to operate on is "next2StepImage"
コード例 #31
0
def main():
    DEBUG = False
    
    CN = [c.strip() for c in channel_names.split(",")]

    if DEBUG:
        imp1, imp2, imp3 = open_test()
    else:
        imp1, imp2, imp3 = open_msr(str(msr_fn))
    
    msr_fn_base = os.path.basename(str(msr_fn))

    signed2unsigned16(imp1)
    signed2unsigned16(imp2)
    signed2unsigned16(imp3)

    imp1.updateAndDraw()
    imp2.updateAndDraw()
    imp3.updateAndDraw()

    IJ.run(imp1, "Enhance Contrast", "saturated=0.35")
    IJ.run(imp2, "Enhance Contrast", "saturated=0.35")
    IJ.run(imp3, "Enhance Contrast", "saturated=0.35")

    cal = imp1.getCalibration()
    IMAGE_AREA_UM = cal.pixelWidth * imp1.getWidth() * cal.pixelHeight * imp1.getHeight()

    t1 = apply_mask(imp1, sigma, CN[0], is_auto_thresh)
    t2 = apply_mask(imp2, sigma, CN[1], is_auto_thresh)
    t3 = apply_mask(imp3, sigma, CN[2], is_auto_thresh)

    results = ResultsTable()
    results.setHeading(0, "Channel")
    results.setHeading(1, "Count")
    results.setHeading(2, "Surface area (um)")
    results.setHeading(3, "Surface area (%)")
    results.setHeading(4, "Surface signal")    
    #results.setHeading(5, "Threshold used")    

    def add_to_table(channel, c, a, s):
        results.incrementCounter()
        results.setValue(0, results.getCounter()-1, channel)
        results.addValue(1, c)
        results.addValue(2, a)
        results.addValue(3, 100 * a /IMAGE_AREA_UM)
        results.addValue(4, s)
        #results.setLabel(msr_fn_base, results.getCounter()-1)

    imp1_mask, c,a,s = analyze(imp1, min_area)
    add_to_table(CN[0], c, a, s) 
    #results.addValue(4, t1)

    imp2_mask, c,a,s = analyze(imp2, min_area)
    add_to_table(CN[1], c, a,s)
    #results.addValue(4, t2)
    
    imp3_mask, c,a,s = analyze(imp3, min_area)
    add_to_table(CN[2], c, a,s)
    #results.addValue(4, t3)

#    IJ.run(imp1, "Enhance Contrast", "saturated=0.35")
#    IJ.run(imp2, "Enhance Contrast", "saturated=0.35")
#    IJ.run(imp3, "Enhance Contrast", "saturated=0.35")

    imp_raw = RGBStackMerge.mergeChannels([imp1, imp2, imp3], True)

    luts = list(imp_raw.getLuts())
    imp_raw.setLuts([luts[2], luts[0], luts[1]] )
    
    imp_raw.setTitle(msr_fn_base )
    imp_raw.show()

    if save_raw:
        save_base_fn = os.path.splitext(str(msr_fn))[0]
        IJ.save(imp_raw, save_base_fn + ".tif")
    

    IJ.run(imp1, "Convert to Mask", "")
    IJ.run(imp2, "Convert to Mask", "")
    IJ.run(imp3, "Convert to Mask", "")
    
    ic = ImageCalculator()
    imp12  = ic.run("Muliply create", imp1,  imp2)
    imp13  = ic.run("Muliply create", imp1,  imp3)
    imp23  = ic.run("Muliply create", imp2,  imp3)
    imp123 = ic.run("Muliply create", imp12, imp3)

    imp12_mask, c,a,s = analyze(imp12, min_area)
    add_to_table("{}+{}".format(CN[0],CN[1]), c, a, -1)

    imp13_mask, c,a,s = analyze(imp13, min_area)
    add_to_table("{}+{}".format(CN[0],CN[2]), c, a, -1)

    imp23_mask,c,a,s = analyze(imp23, min_area)
    add_to_table("{}+{}".format(CN[1],CN[2]), c, a, -1)

    imp123_mask,c,a,s = analyze(imp123, min_area)
    add_to_table("{}+{}+{}".format(CN[0],CN[1], CN[2]), c, a, -1)

    title = "Coloco3surf {}".format(msr_fn_base)
    results.show(title)
    
    imp_merge = RGBStackMerge.mergeChannels([imp1_mask, imp2_mask, imp3_mask, imp12_mask, imp13_mask, imp23_mask, imp123_mask], False)

    luts = list(imp_merge.getLuts())
    imp_merge.setLuts([luts[2], luts[0], luts[1]] + luts[3:])
    

    imp_merge.setTitle(title)
    imp_merge.show()

    if save_surf:
        save_base_fn = os.path.splitext(str(msr_fn))[0]
        IJ.save(imp_merge, save_base_fn + "_surfaces.tif")

    IJ.log("Done")
コード例 #32
0
        for f in image_list:
            if (w_re.search(f) != None and
                    int(w_re.search(f).group()[0:3]) != 405):  #Leave out DAPI
                wave_lengths.append(int(w_re.search(f).group()[0:3]))
                break
    channel_no = len(wave_lengths)
    print 'Detected ' + str(
        channel_no) + ' channel(s) with wavelength(s) ' + str(wave_lengths)
    return wave_lengths, channel_no


oc = OverlayCommands()
rt = ResultsTable()
measured = rt.getResultsTable()
cs = ChannelSplitter()
cm = RGBStackMerge()
zp = ZProjector()
zp.setMethod(ZProjector.AVG_METHOD)

IJ.run("Close All")

#Find images and wavelengths
imagelist = [
    f for f in os.listdir(str(inputpath))
    if (('.tif' in f.lower()) and ('thumb' not in f.lower()))
]
wavelengths, nChannels = get_apical_channels(imagelist, 6)
tm_wavelength = [x for x in wavelengths if not x == ref_wavelength][0]

#Sort image files
regexDetect = re.compile(
コード例 #33
0
# for each channel.
channels = {}
for image_file in image_files:
	channel = re.search('channel(\d+)_', image_file).group(1)
	if channel in channels:
		channels[channel] += 1
	else:
		channels[channel] = 1

if len(channels) > 7:
	print 'Images with more than 7 channels are not currently supported by the Merge Channels operation.'
	sys.exit(1)

# Open an image sequence for each channel.
stacks = []
for channel in channels:
	num_frames = channels[channel]

	IJ.run('Image Sequence...', 'open=%s file=channel%s sort' % (image_files[0], channel))
	stack = IJ.getImage()
	stack.setTitle(channel)
	stack.setDimensions(1, 1, num_frames)  # TODO Don't hardcode the number of slices
	stacks.append(stack)

merged_image = RGBStackMerge().mergeChannels(stacks, False)
merged_image.setTitle(dir_name)

# TODO Alternatively, we could upload directly to OMERO. But that probably
# would not work in headless mode.
IJ.run(merged_image, 'OME-TIFF...', 'save=%s.ome.tif compression=Uncompressed' % image_dir_path)
コード例 #34
0
		rt.setValue("Ch2_TotalIntensity", ct, stats.area * stats.mean)
		rt.setValue("Ch2_MeanIntensity", ct, stats.mean)
		rt.setValue("Ch3_TotalIntensity", ct, statsch3.area * statsch3.mean)
		rt.setValue("Ch3_meanIntensity", ct, statsch3.mean)
		ct += 1
rt.show("Dot Intensity")


#AREA, AREA_FRACTION, CENTER_OF_MASS, CENTROID, CIRCULARITY, ELLIPSE, FERET, 
#INTEGRATED_DENSITY, INVERT_Y, KURTOSIS, LABELS, LIMIT, MAX_STANDARDS, MEAN, 
#MEDIAN, MIN_MAX, MODE, PERIMETER, RECT, SCIENTIFIC_NOTATION, SHAPE_DESCRIPTORS, 
#SKEWNESS, SLICE, STACK_POSITION, STD_DEV

# preparing merged stack with detected dots. 

merge = RGBStackMerge()
#stacks = Array()
#stacks[0] = imp2.getImageStack()
#stacks[1] = imp.getImageStack()
#imgconv = ImageConverter(imp)
#imgconv.setDoScaling(True)
#imgconv.convertToGray8() 
IJ.run(impch2, "Enhance Contrast", "saturated=0.02 use")
IJ.run(impch2, "8-bit", "")
IJ.run(impch3, "Enhance Contrast", "saturated=0.02 use")
IJ.run(impch3, "8-bit", "")
stacks = array(ImageStack, [imp2.getImageStack(), impch2.getImageStack(), impch3.getImageStack()])
impmerged = merge.createComposite(imp2.getWidth(), imp2.getHeight(), imp2.getStackSize(), stacks, True)
impmerged.show()

impch1.changes = False
コード例 #35
0
def cellSegmentation(srcDir, dstDir, currentDir, filename, keepDirectories):
  print "Processing:"  
  # Opening the image
  print "Open image file", filename
  imp = IJ.openImage(os.path.join(currentDir, dstDir))
  # Put your processing commands here!
  localinput=srcDir.replace("/", "\\")
  saveDir = localinput.replace(srcDir, dstDir)
  string="."
  dotIndex=filename.find(string)
  localfile= filename[0:dotIndex]
  print(localfile)
  IJ.run("New... ", "name="+f+" type=Table")
  print(f,"\\Headings:Cell\tarea\tCirc\tAR\tRoundness\tMaximum")
  IJ.run("Bio-Formats", "open=[" + localinput + os.path.sep + filename +"] autoscale color_mode=Default rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT")
  IJ.open()
  idd= WM.getIDList();
  imageID= idd[0];
  IJ.run("Clear Results")
  WM.getImage(imageID)
  IJ.run("Duplicate...", "duplicate channels="+str(x)+"") #Nucleus channel #took away x
  IJ.run("Z Project...", "projection=[Standard Deviation]");#picture for frame detection
  IJ.run("8-bit");
  IJ.run("Duplicate...", "title=IMAGE");#frame
  IJ.run("Duplicate...", "title=SUBTRACT");#Background subtraction mask (for frame and watershed)
  imp=IJ.getImage()
  pixelWidth=imp.getWidth()
  pixelWidth=pixelWidth/1647.89
  pixelHeight= imp.getHeight()
#create subtraction mask, applying constraining maximum (step I)
  IJ.selectWindow("SUBTRACT")
  nResults=imp.getStatistics()
  row = nResults
  rt_exist = WM.getWindow("Results")
  if rt_exist==None:
    rt= ResultsTable()
  else:
    rt = rt_exist.getTextPanel().getOrCreateResultsTable()
  rt.setValue("Max ", 0, row.max) #text file
  rt.show("Results")
  u=math.floor(row.mean*3)
  IJ.run("Max...","value="+str(u)) #constraining maximum of 3-fold mean to reduce effect of extreme values during subtraction
		#gaussian blurring (step II)
  IJ.run("Gaussian Blur...", "sigma=100 scaled") #blurring for subtraction mask

  IJ.selectWindow("IMAGE")
  pxrollrad = cellradius/pixelWidth; #rolling ball radius in pixels needed (= predefined cell radius[µm]/pixelsize[µm/px])
  IJ.run("Subtract Background...", "rolling="+str(pxrollrad)+"")
  IJ.run("Gaussian Blur...", "sigma=2 scaled") #reduces punctate character of grayscale image '
  IM=IJ.selectWindow("IMAGE")
  SUB=IJ.selectWindow("SUBTRACT")
  ic().run("SUBTRACT", IM, SUB) #just subtracts two images
  IJ.selectWindow("IMAGE") #see how to call
  IJ.run("Duplicate...", "title=AND")#watershed
  IJ.run("Duplicate...", "title=CHECK")#for checking if maxima exist within selection later
  
#Apply threshold to get binary image of cell borders (step IV)
  IJ.selectWindow("IMAGE")
  imp = IJ.getImage()  # the current image
  imp.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE)
  IJ.run("Subtract Background...","...")
  IJ.run("Convert to Mask", "method=Default background=Dark only black")
  IJ.run("Fill Holes")

#Create watershed line image (step V)
  IJ.selectWindow("AND")
  IJ.run("Gaussian Blur...", "sigma=2 scaled")
  imp=IJ.getImage()
  pixelWidth=imp.getWidth()
  pixelWidth=pixelWidth/1647.89
  pixelHeight= imp.getHeight()
  # Saving the image
  nResults=imp.getStatistics()
  row = nResults
  rt.setValue("Max ", 1, row.max) #text file
  nBins = 256
  Hist = HistogramWindow("Histogram",imp,nBins)
  Table = Hist.getResultsTable()
  Counts = Table.getColumn(1)
  #mean gray value of pixels belonging to cells needed (i.e. mean of ONLY non-zero pixel)
  Sum = 0 #all counts
  CV = 0 #weighed counts (= counts * intensity)
  for i in range(0, len(Counts)): #starting with 1 instead of 0. -> 0 intensity values are not considered.
    Sum += Counts[i]
    CV += Counts[i]*i
  m = (CV/Sum)
  m=math.floor(m)
  l = math.floor(2*m) #Maxima need to be at least twice the intensity of cellular mean intensity
  IJ.run("Find Maxima...", "noise="+str(l)+" output=[Segmented Particles] exclude") #watershedding

#Combine watershed lines and cell frame (step VI) 
  IJ.selectWindow("IMAGE")
  imp=IJ.getImage()
  imp.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE)
  IJ.run(imp, "Watershed", "") #useful
  imp = IJ.getImage()
  ip = imp.getProcessor()
  segip = MaximumFinder().findMaxima( ip, 1, ImageProcessor.NO_THRESHOLD, MaximumFinder.SEGMENTED , False, False)
  segip.invert()
  segimp = ImagePlus("seg", segip)
  segimp.show()
  mergeimp = RGBStackMerge.mergeChannels(array([segimp, None, None, imp, None, None, None], ImagePlus), True)
  mergeimp.show()
  pa_exist = WM.getWindow("Results for PA")   
  if pa_exist==None:
    pa_rt= ResultsTable()   
  else:
    pa_rt = pa_exist.getTextPanel().getOrCreateResultsTable()     
  ParticleAnalyzer.setResultsTable(pa_rt)    
  IJ.run("Set Measurements...", "area mean perimeter shape decimal=3")  
  IJ.run("Analyze Particles...", "size=" + str(cellradius) + "-Infinity circularity=0.1-1.00 add"); #Cell bodies detected 
  pa_rt.show("Results for PA ")
  save_all(srcDir, dstDir, filename, localfile, keepDirectories, imageID)
コード例 #36
0
ファイル: Plotter.py プロジェクト: rejsmont/nuclearP
if flat == True:
    for i in range(0, channels):
	imageProcessor = ShortProcessor(sx*4, sy*4)
	imageStack = ImageStack(sx*4, sy*4)
        for sphere in spheres:
            fnorm = int(round((sphere['f'][i] - fmin[i]) / (fmax[i] - fmin[i]) * 65536.0))
            x = sphere['cx'] * 4 - sphere['r']
            y = sphere['cy'] * 4 - sphere['r']
            d = sphere['r'] * 2
            imageProcessor.setValue(fnorm)
            imageProcessor.fillOval(x, y, d, d)
	imageStack.addSlice(imageProcessor)
	channelImages.append(ImagePlus("Rendering C" + "%i" % (i + 1), imageStack))
		
    imageO = RGBStackMerge.mergeChannels(channelImages, False)
elif pixels == True:
    for i in range(0, channels):
	imageProcessor = ShortProcessor(width, height)
	imageStack = ImageStack(width, height)
        for sphere in spheres:
            fnorm = int(round((sphere['f'][i] - fmin[i]) / (fmax[i] - fmin[i]) * 65536.0))
            x = sphere['cx']
            y = sphere['cy']
            d = sphere['r'] * 2
            imageProcessor.putPixel(x, y, fnorm)
	imageStack.addSlice(imageProcessor)
	channelImages.append(ImagePlus("Rendering C" + "%i" % (i + 1), imageStack))
	
    imageO = RGBStackMerge.mergeChannels(channelImages, False)
else:
コード例 #37
0
ファイル: RGMerge.py プロジェクト: jashworth-UTS/scripts
for l in open(filetab):
	f = l.strip().split()
	out = f[0]
	ch1 = '%s/%s' %(path,f[1])
	ch2 = '%s/%s' %(path,f[2])
	print('%s: opening %s and %s' %(out,ch1,ch2))
	ch1 = ij.IJ.openImage(ch1)
	conv = ImageConverter(ch1)
	conv.convertToGray16()
#	ch1.show()
	ch2 = ij.IJ.openImage(ch2)
	conv = ImageConverter(ch2)
	conv.convertToGray16()
#	ch2.show()
#	ch1.close()
#	ch2.close()
	mrg = RGBStackMerge.mergeChannels([ch1, ch2], False)
#	mrg.show()
	mrgf = '%s/%s.merged.tiff' %(path,out)
	ij.IJ.saveAs(mrg,"Tiff",mrgf)
	mrg.close()
	opts = ImporterOptions()
	opts.setId(mrgf)
	opts.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE)
	bio = BF.openImagePlus(opts)[0]
#	bio.show()
	ij.IJ.saveAs(bio.flatten(), "Tiff", '%s/%s.flat.tiff' %(path,out))
#	bio.close()
#	while(True): continue
コード例 #38
0
for image in moFileList:
   print "Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")"
   IJ.log("Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")")
   imp = Opener().openImage(path + image.group()) # open Image
   #if imp.getBitDepth() != 8:  # converting to 8 bit if 
   #   ImageConverter(imp).convertToGray8()
   roi = imp.roi
   imps = CS.split(imp)
   ppc = PPC()
   for aimp in imps:
      ppc.setImp(aimp)
      ppc.run()
      if roi != None:
         aimp.setRoi(roi)
         for n in range(1, aimp.getImageStackSize()+1):
            aimp.getImageStack().getProcessor(n).fillOutside(roi)
         aimp.killRoi()
   final = StackMerge.mergeChannels(imps, False)
   final.copyScale(imp) # copyscale from .copyscale
   if not pth.exists(saveFolder):
      makedirs(saveFolder)
   fileName = G_saveFilePrefix + image.group('prefix')
   IJ.saveAs(final, ".tiff", pth.join(saveFolder, fileName) )  # saveAs(ImagePlus imp, java.lang.String format, java.lang.String path) 
   print "Successfully saved", G_saveFilePrefix + image.group('prefix')
   IJ.log("Successfully saved " + G_saveFilePrefix + image.group('prefix') + ".tif")
   for win in WindowManager.getIDList():
      imp = WindowManager.getImage(win)
      imp.close()
print "Finished."
IJ.log("Finished pre-processing.")
コード例 #39
0
def analyse(imp, root, filename, thresholds):
  imp.show()
  print ""
  print(imp.getTitle())
  print "**********************************"
  
  channels=(1,2,3)
  backgrounds=thresholds #(175,0,275)

  #IJ.run(imp, "Gaussian Blur...", "sigma=1 stack");
  
  impA = []
  sumIntensities = []
  sumIntensitiesBW = []
  
  for iChannel in channels:

  	# general issues:
  	# - intensity decreases along z
  	
    # measure total intensity
    # - bg subtraction?
    impc = extractChannel(imp, iChannel, 1)
    impbw = threshold(impc, thresholds[iChannel-1]) 
    
    impcBGcorr = Duplicator().run(impc)
    IJ.run(impcBGcorr, "Subtract...", "value="+str(backgrounds[iChannel-1])+" stack");
    sumIntensities.append(measureSumIntensity3D(impcBGcorr))

    # measure number of pixels containing a signification signal
    # - what is good here for thresholding and preprocessing?
    #impbw = autoThreshold(impc, "Default")
    
    #impbw.setTitle("bw"+str(iChannel))
    #impbw.show()
    impA.append(impbw)
    sumIntensitiesBW.append(measureSumIntensity3D(impbw)/255)
      
  # measure how many pixels are above threshold in either of the images (2015-09-21)
  impbw = ImageCalculator().run("OR create stack", impA[0], impA[1])
  impbw = ImageCalculator().run("OR create stack", impbw, impA[2])
  impA.append(impbw)
  sumIntensitiesBW.append(measureSumIntensity3D(impbw)/255)  # volume of pixels that are above threshold in either of the images
  sumIntensities.append(0.0)
 
  print "intensities,",str(sumIntensities)[1:-1]
  print "volumes,",str(sumIntensitiesBW)[1:-1]

  # normalise to the volume of the 2nd channel (which is the AF channel) (removed on 2015-09-21)
  #sumIntensitiesNorm = [x / sumIntensitiesBW[1] for x in sumIntensities]
  #sumIntensitiesBWNorm = [x / sumIntensitiesBW[1] for x in sumIntensitiesBW]

  # normalise to the volume of the 4th channel (which is the OR channel) (added on 2015-09-21)
  sumIntensitiesNorm = [x / sumIntensitiesBW[3] for x in sumIntensities]
  sumIntensitiesBWNorm = [x / sumIntensitiesBW[3] for x in sumIntensitiesBW]
  
  # print all the results without the brackets (that's why the 1:-1 and not :)
  print "intensities normalised,",str(sumIntensitiesNorm)[1:-1] 
  print "volumes normalised,",str(sumIntensitiesBWNorm)[1:-1] 
  print "thresholds,",str(thresholds)[1:-1]
  
  impMerge = RGBStackMerge.mergeChannels(array(impA, ImagePlus), False)
  impMerge.setDisplayMode(IJ.COLOR);
  impMerge.setC(1);
  IJ.run(impMerge, "Green", "");
  impMerge.setC(2);
  IJ.run(impMerge, "Grays", "");
  impMerge.setC(3);
  IJ.run(impMerge, "Blue", "");
  impMerge.setC(4);
  IJ.run(impMerge, "Red", "");
  impMerge.show()
  IJ.saveAs(impMerge, "Tiff", os.path.join(root, filename + "--segmented.tif"));
コード例 #40
0

import os

print(folder)

images = [];

# load all images, collect them in a list
for root, directories, filenames in os.walk(folder.getAbsolutePath()):
    filenames.sort();
    for filename in filenames:
	    print(filename)
	    if (filename.endswith(".raw")):
		    IJ.run("Raw...", "open=[" + os.path.join(folder.getAbsolutePath(), filename) + "] image=[16-bit Signed] width=" + str(imageWidth) + " height=" + str(imageHeight) + " number=" + str(imageDepth) + " little-endian");
		    imp = IJ.getImage();
		    images.append(imp);
		    imp.hide();

# merge all images as channels
merged = RGBStackMerge.mergeChannels(images, False);
merged.show();

# switch channels and frames
IJ.run(merged,"Re-order Hyperstack ...", "channels=[Frames (t)] slices=[Slices (z)] frames=[Channels (c)]");
merged = IJ.getImage()

# fix Lookup table
IJ.run(merged, "Grays", "");

コード例 #41
0
ファイル: fun_with_arrays.py プロジェクト: zvtrung/tips
z	boolean
c	char
b	byte
h	short
i	int
l	long
f	float
d	double
"""

ja = jarray.array([0, 1, 2, 3], 'i')
print(ja)
"""
What if you want to make a java array of a specific class?
You could then name the class as the second argument.
For example

"""
img_dir = git_home + "/tips/ImageJ/"
imp_blobs_1 = IJ.openImage("http://imagej.nih.gov/ij/images/blobs.gif")
IJ.run(imp_blobs_1, "Red", "")
imp_blobs_2 = imp_blobs_1.duplicate()
IJ.run(imp_blobs_2, "Green", "")
imp_blobs_3 = imp_blobs_1.duplicate()
IJ.run(imp_blobs_3, "Blue", "")
img_array = jarray.array([imp_blobs_1, imp_blobs_2, imp_blobs_3], ImagePlus)
gray_stack = RGBStackMerge().mergeHyperstacks(img_array, True)
gray_stack.show()
gray_comp = RGBStackMerge().mergeChannels(img_array, False)
gray_comp.show()