def write_fused(output_path,channel,sizeZ,theC,physX,physY,physZ):

	IJ.log("Writing fused data")

	# number of slices will determine filename format
	digits = "00"
	if sizeZ < 100:
		digits = "0"
	if sizeZ < 10:
		digits = ""

	# get the base metadata from the first fused image
	meta = MetadataTools.createOMEXMLMetadata()
	reader = get_reader(output_path+"img_t1_z%s1_c1"%digits,meta)
	reader.close()
	
	# reset some metadata
	meta.setPixelsPhysicalSizeX(physX,0)
	meta.setPixelsPhysicalSizeY(physY,0)
	meta.setPixelsPhysicalSizeZ(physZ,0)
	meta.setPixelsSizeZ(PositiveInteger(sizeZ),0)
	meta.setChannelID("Channel:0:" + str(0), 0, 0)
	spp = channel['spp']
	meta.setChannelSamplesPerPixel(spp, 0, 0)
	name = channel['name']
	color = channel['color']
	meta.setChannelName(name,0,0)
	meta.setChannelColor(color,0,0)
		
	# determine the number of subsets that need to be written
	slices_per_subset = 200
	num_output_files = divmod(sizeZ,slices_per_subset)
	fpaths = []
	if num_output_files[0] == 0:
		nslices = [sizeZ]
		num_output_files = 1
		fpaths.append("%sfused_C%s.ome.tif"%(output_path,str(theC-1)))
	else:
		nslices = []
		for n in range(num_output_files[0]):
			nslices.append(slices_per_subset)

		if num_output_files[1] > 0:
			nslices.append(num_output_files[1])		
		
		for s in range(len(nslices)):
			fpaths.append("%sfused_C%s_subset%s.ome.tif"%(output_path,str(theC-1),str(s)))

	# setup a writer
	writer = ImageWriter()
	writer.setCompression('LZW')
	writer.setMetadataRetrieve(meta)
	writer.setId(fpaths[0])

	# write the slices, changing the output file when necessary
	theZ = 0
	for f in range(len(fpaths)):
		meta.setImageName(os.path.basename(fpaths[f]),0)
		writer.changeOutputFile(fpaths[f])
		for s in range(nslices[f]):
			fpath = output_path+"img_t1_z%s%s_c1"%(digits,str(theZ+1))
			if (len(digits) == 1) and (theZ+1 > 9):
				fpath = output_path+"img_t1_z%s_c1"%(str(theZ+1))
			if (len(digits) == 2) and (theZ+1 > 9):
				fpath = output_path+"img_t1_z0%s_c1"%(str(theZ+1))
			if (len(digits) == 2) and (theZ+1 > 99):
				fpath = output_path+"img_t1_z%s_c1"%(str(theZ+1))
			IJ.log("writing slice %s"%os.path.basename(fpath))
			m = MetadataTools.createOMEXMLMetadata()
			
			r = get_reader(fpath,m)
			m.setPixelsPhysicalSizeX(physX,0)
			m.setPixelsPhysicalSizeY(physY,0)
			m.setPixelsPhysicalSizeZ(physZ,0)
			m.setChannelID("Channel:0:" + str(0), 0, 0)
			spp = channel['spp']
			m.setChannelSamplesPerPixel(spp, 0, 0)
			name = channel['name']
			color = channel['color']
			m.setChannelName(name,0,0)
			m.setChannelColor(color,0,0)
			writer.saveBytes(theZ,r.openBytes(0))
			r.close()
			theZ += 1
	writer.close()
Exemple #2
0
def save_ome_tiff(filename, image, metadata):
    reader = ImageReader()
    writer = ImageWriter()
    writer.setMetadataRetrieve(metadata)
    writer.setId(filename)
    nchan = image.getNChannels()
    stack = image.getImageStack()
    print(image.getStackSize())
    for i in range(nchan):
        writer.setSeries(0)
        process = stack.getProcessor(i + 1)
        pixels = process.getPixels()
        pixels = DataTools.floatsToBytes(pixels, True)
        writer.saveBytes(i, pixels)
    writer.close()
Exemple #3
0
def run():
    t_start = datetime.now()
    image_paths = glob(os.path.join(str(import_dir.getPath()), '*tif'))

    print '\tread image metadata'
    reader = ImageReader()
    in_meta = MetadataTools.createOMEXMLMetadata()
    reader.setMetadataStore(in_meta)

    x_dims = []
    y_dims = []
    z_dims = []
    c_dims = []
    t_dims = []
    eff = []
    spp = []

    for image_path in image_paths:
        print '\t  parse %s' % (image_path)
        reader.setId(image_path)
        x_dims.append(reader.getSizeX())
        y_dims.append(reader.getSizeY())
        z_dims.append(reader.getSizeZ())
        c_dims.append(reader.getSizeC())
        t_dims.append(reader.getSizeT())
        eff.append(reader.imageCount / z_dims[-1] / t_dims[-1])
        spp.append(reader.getSizeC() / eff[-1])

    format = FormatTools.getPixelTypeString(reader.getPixelType())
    series = reader.getSeries()
    big_endian = Boolean.FALSE
    order = reader.getDimensionOrder()
    reader.close()

    # Compute the dimensions of the output file
    x_dim = max(x_dims)
    y_dim = max(y_dims)
    z_dim = max(z_dims)
    c_dim = max(c_dims)
    t_dim = max(t_dims)

    print '\t  series: %i' % series
    print '\t  format: %s' % format
    print '\t  dimension order: %s' % order
    print '\t  x: %s -> %i' % (x_dims, x_dim)
    print '\t  y: %s -> %i' % (y_dims, y_dim)
    print '\t  z: %s -> %i' % (z_dims, z_dim)
    print '\t  c: %s -> %i' % (c_dims, c_dim)
    print '\t  t: %s -> %i' % (t_dims, t_dim)
    print '\t  effective size c: %s' % eff
    print '\t  samples per pixel: %s' % spp

    # Get the time dimension from the number of input files
    t_dim = len(image_paths)

    # TODO: Tried to work out the order with Axes class, got something weird though.
    dimensions = [Short(x_dim), Short(y_dim), Short(c_dim), Short(z_dim)]

    pixels_per_plane = x_dim * y_dim

    # Assemble the metadata for the output file
    out_meta = MetadataTools.createOMEXMLMetadata()
    out_meta.setImageID(MetadataTools.createLSID('Image', series), series)
    out_meta.setPixelsID(MetadataTools.createLSID('Pixels', series), series)
    out_meta.setPixelsBinDataBigEndian(Boolean.TRUE, 0, 0)
    out_meta.setPixelsDimensionOrder(DimensionOrder.fromString(order), series)
    out_meta.setPixelsType(PixelType.fromString(format), series)
    out_meta.setPixelsSizeX(PositiveInteger(x_dim), series)
    out_meta.setPixelsSizeY(PositiveInteger(y_dim), series)
    out_meta.setPixelsSizeZ(PositiveInteger(z_dim), series)
    out_meta.setPixelsSizeC(PositiveInteger(c_dim), series)
    out_meta.setPixelsSizeT(PositiveInteger(t_dim), series)

    for c in range(c_dim):
        out_meta.setChannelID(MetadataTools.createLSID('Channel', series, c),
                              series, c)
        out_meta.setChannelSamplesPerPixel(PositiveInteger(1), series, c)

    # Initialize the BF writer
    result_path = os.path.join(result_dir.getPath(), result_name)
    writer = ImageWriter()
    writer.setMetadataRetrieve(out_meta)
    writer.setId(result_path)
    print '\tcreated to %s' % (result_path)

    # Write the stacks into the output file
    N = len(image_paths)
    for i, image_path in enumerate(image_paths):
        status.showStatus(i, N, "catenating %i of %i time-points" % (i, N))
        print '\t  processing %s' % (image_path)
        ds = io.open(image_path)
        xi = ds.dimensionIndex(Axes.X)
        xv = ds.dimension(xi)
        yi = ds.dimensionIndex(Axes.Y)
        yv = ds.dimension(yi)
        zi = ds.dimensionIndex(Axes.Z)
        zv = ds.dimension(zi)
        ti = ds.dimensionIndex(Axes.TIME)
        tv = ds.dimension(ti)
        ci = ds.dimensionIndex(Axes.CHANNEL)
        cv = ds.dimension(ci)

        dx = float(x_dim - xv) / 2.0
        dy = float(y_dim - yv) / 2.0
        dz = float(z_dim - zv) / 2.0
        print '\t     translation vector (dx, dy, dz) = (%f, %f, %f)' % (
            dx, dy, dz)

        if (dx != 0) or (dy != 0) or (dz != 0):
            stk = Views.translate(ds, long(dx), long(dy), long(0), long(dz))
            stk = Views.extendZero(stk)
        else:
            stk = Views.extendZero(ds.getImgPlus().getImg())

        print '\t     writing planes ',
        n = 0
        plane = 1
        byte_array = []
        interval_view = Views.interval(stk, \
                                       [Long(0), Long(0), Long(0), Long(0)], \
                                       [Long(x_dim - 1), Long(y_dim - 1), Long(c_dim - 1), Long(z_dim - 1)])
        cursor = interval_view.cursor()
        while cursor.hasNext():
            n += 1
            cursor.fwd()
            value = cursor.get().getInteger()
            bytes = DataTools.shortToBytes(value, big_endian)
            byte_array.extend(bytes)

            if n == pixels_per_plane:
                writer.saveBytes(plane - 1, byte_array)

                print '.',
                if ((plane) % 10) == 0:
                    print '\n\t                    ',

                byte_array = []
                plane += 1
                n = 0

        print ' '

    writer.close()
    t = datetime.now() - t_start
    print '\twrote %i planes to %s in %i sec.' % (plane - 1, result_path,
                                                  t.total_seconds())
    print '... done.'
def write_tiles(r,tiles_dir,theT,sizeC,sizeZ,meta):
	writer = ImageWriter()
	writer.setCompression('LZW')
	writer.setMetadataRetrieve(meta)
	writer.setId("%s/tile_%s.ome.tif"%(tiles_dir,theT))
	planes = sizeZ * sizeC
	p = 0
	for theZ in range(sizeZ):
		for theC in range(sizeC):
			writer.saveBytes(p,r.openBytes(reader.getIndex(theZ, theC, theT)))
			p += 1
	writer.close()
def write_fused(output_path,meta):
	imp = ij.WindowManager.getCurrentImage()
	meta.setPixelsSizeX(PositiveInteger(imp.getWidth()),0)
	meta.setPixelsSizeY(PositiveInteger(imp.getHeight()),0)
	writer = ImageWriter()
	writer.setCompression('LZW')
	writer.setMetadataRetrieve(meta)
	writer.setId("%s/fused.ome.tif"%output_path)
	littleEndian = not writer.getMetadataRetrieve().getPixelsBinDataBigEndian(0, 0)
	planes = imp.getStack()
	for p in range(planes.getSize()):
		proc = planes.getProcessor(p+1)
		writer.saveBytes(p,DataTools.shortsToBytes(proc.getPixels(), littleEndian))
	writer.close()
Exemple #6
0
start = len(shape + " " + "points=") + 1

pts = omeMetaStr[start+prefix:stop]

new_pts_str =pts.replace(" ",",")
new_pts = [int(p) for p in new_pts_str.split(",")]

xs = new_pts[0::2]
ys = new_pts[1::2]

proi = PolygonRoi(xs, ys, len(xs), Roi.POLYGON)  
imp = imps[0]
imp.setRoi(proi)

# create a writer and set metadata
writer = ImageWriter()
writer.setMetadataRetrieve(omeMeta)
writer.setId('%s')

# get the stack
planes = imp.getStack()
for p in range(planes.getSize()):

    # get the plane
    plane = planes.getProcessor(p+1)
    
    # fill outside
    plane.fillOutside(proi)
    
    pixels = plane.convertToByte(True).getPixels()
    writer.saveBytes(p,pixels)