Java Code Examples for net.imglib2.Interval#dimension()

The following examples show how to use net.imglib2.Interval#dimension() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TIFFFormat.java    From scifio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Saves the given image to the specified series in the current file. The
 * IFD hashtable allows specification of TIFF parameters such as bit depth,
 * compression and units.
 */
public void savePlane(final int imageIndex, final long planeIndex,
	final Plane plane, IFD ifd, final Interval bounds) throws IOException,
	FormatException
{
	final byte[] buf = plane.getBytes();
	if (checkParams) checkParams(imageIndex, planeIndex, buf, bounds);
	final int xAxis = getMetadata().get(imageIndex).getAxisIndex(Axes.X);
	final int yAxis = getMetadata().get(imageIndex).getAxisIndex(Axes.Y);
	final int x = (int) bounds.min(xAxis), y = (int) bounds.min(yAxis), //
			w = (int) bounds.dimension(xAxis), h = (int) bounds.dimension(yAxis);
	if (ifd == null) ifd = new IFD(log());
	final int type = getMetadata().get(imageIndex).getPixelType();
	final long index = planeIndex;
	// This operation is synchronized
	synchronized (this) {
		// This operation is synchronized against the TIFF saver.
		synchronized (tiffSaver) {
			prepareToWritePlane(imageIndex, planeIndex, plane, ifd, x, y, w, h);
		}
	}

	tiffSaver.writeImage(buf, ifd, index, type, x, y, w, h,
		planeIndex == getMetadata().get(imageIndex).getPlaneCount() - 1 &&
			imageIndex == getMetadata().getImageCount() - 1);
}
 
Example 2
Source File: Morphologies.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Computes the min coordinate and the size of an {@link Interval} after
 * padding with a list of {@link Shape}s in a series morphology operations.
 * 
 * @param source the interval to be applied with some morphology operation
 * @param shapes the list of Shapes for padding
 * @return a size-2 array storing the min coordinate and the size of the
 *         padded interval
 */
public static final long[][] computeMinSize(final Interval source,
	final List<Shape> shapes)
{

	final int numDims = source.numDimensions();
	final long[] min = new long[numDims];
	final long[] size = new long[numDims];

	for (int i = 0; i < numDims; i++) {
		min[i] = source.min(i);
		size[i] = source.dimension(i);
	}

	for (final Shape shape : shapes) {
		final Neighborhood<BitType> nh = MorphologyUtils.getNeighborhood(shape,
			source);
		for (int i = 0; i < numDims; i++) {
			min[i] += nh.min(i);
			size[i] += nh.dimension(i) - 1;
		}
	}

	return new long[][] { min, size };
}
 
Example 3
Source File: MetadataUtil.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <C extends CalibratedAxis> void copyTypedSpace(
	final Interval inInterval, final CalibratedSpace<C> in,
	final CalibratedSpace<C> out)
{

	int offset = 0;
	for (int d = 0; d < in.numDimensions(); d++) {
		if (inInterval != null && inInterval.dimension(d) == 1) {
			offset++;
		}
		else {
			out.setAxis((C) in.axis(d).copy(), d - offset);
		}
	}
}
 
Example 4
Source File: PaddingIntervalOrigin.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public O calculate(final I input, final Interval centeredInterval) {

	int numDimensions = input.numDimensions();

	// compute where to place the final Interval for the input so that the
	// coordinate in the center
	// of the input is at position (0,0).
	final long[] min = new long[numDimensions];
	final long[] max = new long[numDimensions];

	for (int d = 0; d < numDimensions; ++d) {
		min[d] = input.min(d) + input.dimension(d) / 2;
		max[d] = min[d] + centeredInterval.dimension(d) - 1;
	}

	return (O) new FinalInterval(min, max);
}
 
Example 5
Source File: TransformWeights.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
public TransformWeights(
		final ImagePortion portion,
		final Interval imgInterval,
		final Blending blending,
		final AffineTransform3D transform,
		final RandomAccessibleInterval< FloatType > overlapImg,
		final RandomAccessibleInterval< FloatType > blendingImg,
		final long[] offset )
{
	this.portion = portion;
	this.blendingImg = blendingImg;
	this.transform = transform;
	this.overlapImg = overlapImg;
	this.blending = blending;

	this.offsetX = (int)offset[ 0 ];
	this.offsetY = (int)offset[ 1 ];
	this.offsetZ = (int)offset[ 2 ];

	this.imgSizeX = (int)imgInterval.dimension( 0 );
	this.imgSizeY = (int)imgInterval.dimension( 1 );
	this.imgSizeZ = (int)imgInterval.dimension( 2 );
}
 
Example 6
Source File: FourNeighborhoodExtrema.java    From BigStitcher with GNU General Public License v2.0 5 votes vote down vote up
/**
 * split the given Interval into nSplits intervals along the largest dimension
 * @param interval input interval
 * @param nSplits how may splits
 * @return list of intervals input was split into
 */
public static List<Interval> splitAlongLargestDimension(Interval interval, long nSplits){
	
	List<Interval> res = new ArrayList<Interval>();
	
	long[] min = new long[interval.numDimensions()];
	long[] max = new long[interval.numDimensions()];
	interval.min(min);
	interval.max(max);
	
	int splitDim = 0;
	for (int i = 0; i< interval.numDimensions(); i++){
		if (interval.dimension(i) > interval.dimension(splitDim)) splitDim = i;
	}

	// there could be more splits than actual dimension entries
	nSplits = Math.min( nSplits, interval.dimension(splitDim) );

	long chunkSize = interval.dimension(splitDim) / nSplits;
	long maxSplitDim = max[splitDim];
	
	for (int i = 0; i<nSplits; i++){
		if (i != 0){
			min[splitDim] += chunkSize;	
		}
		max[splitDim] = min[splitDim] + chunkSize - 1;
		if (i == nSplits -1){
			max[splitDim] = maxSplitDim;
		}
		res.add(new FinalInterval(min, max));
	}
		
	return res;
}
 
Example 7
Source File: JPEGTileFormat.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ByteArrayPlane openPlane(final int imageIndex, final long planeIndex,
	final ByteArrayPlane plane, final Interval bounds,
	final SCIFIOConfig config) throws FormatException, IOException
{
	final Metadata meta = getMetadata();
	final byte[] buf = plane.getBytes();
	final int xIndex = meta.get(imageIndex).getAxisIndex(Axes.X);
	final int yIndex = meta.get(imageIndex).getAxisIndex(Axes.Y);
	final int x = (int) bounds.min(xIndex);
	final int y = (int) bounds.min(yIndex);
	final int w = (int) bounds.dimension(xIndex);
	final int h = (int) bounds.dimension(yIndex);
	FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex, buf.length,
		bounds);

	final int c = (int) meta.get(imageIndex).getAxisLength(Axes.CHANNEL);

	for (int ty = y; ty < y + h; ty++) {
		byte[] scanline = meta.getDecoder().getScanline(ty);
		if (scanline == null) {
			meta.getDecoder().initialize(getHandle(), 0);
			scanline = meta.getDecoder().getScanline(ty);
		}
		System.arraycopy(scanline, c * x, buf, (ty - y) * c * w, c * w);
	}

	return plane;
}
 
Example 8
Source File: GIFFormat.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ByteArrayPlane openPlane(final int imageIndex, final long planeIndex,
	final ByteArrayPlane plane, final Interval bounds,
	final SCIFIOConfig config) throws FormatException, IOException
{
	final byte[] buf = plane.getData();
	final Metadata meta = getMetadata();
	final int xIndex = meta.get(imageIndex).getAxisIndex(Axes.X);
	final int yIndex = meta.get(imageIndex).getAxisIndex(Axes.Y);
	plane.setColorTable(meta.getColorTable(0, 0));
	FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex, buf.length,
		bounds);
	final int x = (int) bounds.min(xIndex);
	final int y = (int) bounds.min(yIndex);
	final int w = (int) bounds.dimension(xIndex);
	final int h = (int) bounds.dimension(yIndex);
	final int[] act = meta.getColorTables().get((int) planeIndex);

	final byte[] b = meta.getImages().get((int) planeIndex);
	if (planeIndex > 0 && meta.isTransparency()) {
		final byte[] prev = meta.getImages().get((int) planeIndex - 1);
		int idx = meta.getTransIndex();
		if (idx >= 127) idx = 0;
		for (int i = 0; i < b.length; i++) {
			if ((act[b[i] & 0xff] & 0xffffff) == idx) {
				b[i] = prev[i];
			}
		}
		meta.getImages().setElementAt(b, (int) planeIndex);
	}

	for (int row = 0; row < h; row++) {
		System.arraycopy(b, (row + y) * (int) meta.get(imageIndex)
			.getAxisLength(Axes.X) + x, buf, row * w, w);
	}

	return plane;
}
 
Example 9
Source File: EPSFormat.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void initialize(final int imageIndex, final long planeIndex,
	final Interval bounds) throws IOException, FormatException
{
	if (!isInitialized(imageIndex, (int) planeIndex)) {

		writeHeader(imageIndex);

		if (!SCIFIOMetadataTools.wholePlane(imageIndex, getMetadata(),
			bounds))
		{
			final int xAxis = getMetadata().get(imageIndex).getAxisIndex(Axes.X);
			final int yAxis = getMetadata().get(imageIndex).getAxisIndex(Axes.Y);
			final int w = (int) bounds.dimension(xAxis);
			final int h = (int) bounds.dimension(yAxis);
			final int nChannels = (int) getMetadata().get(imageIndex)
				.getAxisLength(Axes.CHANNEL);
			// write a dummy plane that will be overwritten in sections
			final int planeSize = w * h * nChannels;
			for (int i = 0; i < planeSize; i++) {
				getHandle().writeBytes(DUMMY_PIXEL);
			}
		}
	}

	super.initialize(imageIndex, planeIndex, bounds);
}
 
Example 10
Source File: JPEG2000Format.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Compresses the buffer.
 *
 * @param imageIndex the image index within the dataset
 * @param planeIndex the plane index within the image
 * @param plane the image tile being compressed.
 * @param bounds bounds of the planar axes.
 * @throws FormatException if one of the parameters is invalid.
 * @throws IOException if there was a problem writing to the file.
 */
public byte[] compressBuffer(final int imageIndex, final long planeIndex,
	final Plane plane, final Interval bounds) throws FormatException,
	IOException
{
	final ImageMetadata imageMeta = getMetadata().get(imageIndex);

	final byte[] buf = plane.getBytes();
	checkParams(imageIndex, planeIndex, buf, bounds);
	final boolean littleEndian = imageMeta.isLittleEndian();
	final int bytesPerPixel = imageMeta.getBitsPerPixel() / 8;
	final int nChannels = (int) imageMeta.getAxisLength(Axes.CHANNEL);

	// To be on the save-side
	CodecOptions options = getCodecOptions();
	if (options == null) options = JPEG2000CodecOptions.getDefaultOptions();
	options.width = (int) bounds.dimension(imageMeta.getAxisIndex(Axes.X));
	options.height = (int) bounds.dimension(imageMeta.getAxisIndex(Axes.Y));
	options.channels = nChannels;
	options.bitsPerSample = bytesPerPixel * 8;
	options.littleEndian = littleEndian;
	options.interleaved = plane.getImageMetadata()
		.getInterleavedAxisCount() > 0;
	options.lossless = getCompression() == null || getCompression().equals(
		CompressionType.J2K.getCompression());
	options.colorModel = getColorModel();

	final JPEG2000Codec codec = codecService.getCodec(JPEG2000Codec.class);
	return codec.compress(buf, options);
}
 
Example 11
Source File: DifferenceOfGaussianCUDA.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
public static int[] getImgSizeInt( final Interval img )
{
	final int[] dim = new int[ img.numDimensions() ];
	for ( int d = 0; d < img.numDimensions(); ++d )
		dim[ d ] = (int)img.dimension( d );
	return dim;
}
 
Example 12
Source File: DifferenceOfGaussianCUDA.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
public static long[] getImgSize( final Interval img )
{
	final long[] dim = new long[ img.numDimensions() ];
	for ( int d = 0; d < img.numDimensions(); ++d )
		dim[ d ] = img.dimension( d );
	return dim;
}
 
Example 13
Source File: ByteArrayPlane.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected byte[] blankPlane(final Interval bounds) {
	byte[] buf = null;

	final long[] sizes = new long[bounds.numDimensions() + 1];
	for (int i = 0; i < sizes.length - 1; i++) {
		sizes[i] = bounds.dimension(i);
	}
	sizes[sizes.length - 1] = FormatTools.getBytesPerPixel(getImageMetadata()
		.getPixelType());

	buf = ArrayUtils.allocate(sizes);
	return buf;
}
 
Example 14
Source File: SCIFIOMetadataTools.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns true if the provided axes correspond to a complete image row
 */
public static boolean wholeRow(final int imageIndex, final Metadata meta,
	final Interval bounds)
{
	final int yIndex = meta.get(imageIndex).getAxisIndex(Axes.Y);

	for (int d = 0; d < bounds.numDimensions(); d++) {
		if (d == yIndex) continue;
		final long length = meta.get(imageIndex).getAxisLength(d);
		if (bounds.min(d) != 0 || bounds.dimension(d) != length) return false;
	}

	return true;
}
 
Example 15
Source File: ICSFormat.java    From scifio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void writePlane(final int imageIndex, final long planeIndex,
	final Plane plane, final Interval bounds) throws FormatException,
	IOException
{
	checkParams(imageIndex, planeIndex, plane.getBytes(), bounds);
	final Metadata meta = getMetadata();
	final boolean interleaved = plane.getImageMetadata()
		.getInterleavedAxisCount() > 0;

	final int xAxis = meta.get(imageIndex).getAxisIndex(Axes.X);
	final int yAxis = meta.get(imageIndex).getAxisIndex(Axes.Y);
	final int x = (int) bounds.min(xAxis), y = (int) bounds.min(yAxis), //
			w = (int) bounds.dimension(xAxis), h = (int) bounds.dimension(yAxis);

	int rgbChannels = 1;

	if (meta.get(imageIndex).isMultichannel()) {
		final int cIndex = meta.get(imageIndex).getAxisIndex(Axes.CHANNEL);
		rgbChannels = (int) (bounds.dimension(cIndex));
	}

	final int sizeX = (int) meta.get(imageIndex).getAxisLength(Axes.X);
	final int pixelType = getMetadata().get(imageIndex).getPixelType();
	final int bytesPerPixel = FormatTools.getBytesPerPixel(pixelType);
	final int planeSize = (int) (meta.get(0).getSize() / meta.get(0)
		.getPlaneCount());

	pixels.seek(pixelOffset + planeIndex * planeSize);
	if (SCIFIOMetadataTools.wholePlane(imageIndex, meta, bounds) &&
		(interleaved || rgbChannels == 1))
	{
		pixels.write(plane.getBytes());
	}
	else {
		pixels.skipBytes(bytesPerPixel * rgbChannels * sizeX * y);
		for (int row = 0; row < h; row++) {
			final ByteArrayOutputStream strip = new ByteArrayOutputStream();
			for (int col = 0; col < w; col++) {
				for (int c = 0; c < rgbChannels; c++) {
					final int index = interleaved ? rgbChannels * (row * w + col) + c
						: w * (c * h + row) + col;
					strip.write(plane.getBytes(), index * bytesPerPixel,
						bytesPerPixel);
				}
			}
			pixels.skipBytes(bytesPerPixel * rgbChannels * x);
			pixels.write(strip.toByteArray());
			pixels.skipBytes(bytesPerPixel * rgbChannels * (sizeX - w - x));
		}
	}
	lastPlane = planeIndex;
}
 
Example 16
Source File: BMPFormat.java    From scifio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public ByteArrayPlane openPlane(final int imageIndex, final long planeIndex,
	final ByteArrayPlane plane, final Interval bounds,
	final SCIFIOConfig config) throws FormatException, IOException
{
	final Metadata meta = getMetadata();
	final ImageMetadata imageMeta = meta.get(imageIndex);
	final int xIndex = imageMeta.getAxisIndex(Axes.X);
	final int yIndex = imageMeta.getAxisIndex(Axes.Y);
	final int x = (int) bounds.min(xIndex);
	final int y = (int) bounds.min(yIndex);
	final int w = (int) bounds.dimension(xIndex);
	final int h = (int) bounds.dimension(yIndex);

	final byte[] buf = plane.getData();
	final int compression = meta.getCompression();
	final int bpp = imageMeta.getBitsPerPixel();
	final int sizeX = (int) imageMeta.getAxisLength(Axes.X);
	final int sizeY = (int) imageMeta.getAxisLength(Axes.Y);
	final int sizeC = (int) imageMeta.getAxisLength(Axes.CHANNEL);

	FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex, buf.length,
		bounds);

	if (compression != RAW && getHandle().length() < FormatTools.getPlaneSize(
		this, imageIndex))
	{
		throw new UnsupportedCompressionException(compression +
			" not supported");
	}

	final int rowsToSkip = meta.isInvertY() ? y : sizeY - (h + y);
	final int rowLength = sizeX * (imageMeta.isIndexed() ? 1 : sizeC);
	getHandle().seek(meta.getGlobal() + rowsToSkip * rowLength);

	int pad = ((rowLength * bpp) / 8) % 2;
	if (pad == 0) {
		pad = ((rowLength * bpp) / 8) % 4;
	}
	else {
		pad *= sizeC;
	}
	int planeSize = sizeX * sizeC * h;
	if (bpp >= 8) planeSize *= (bpp / 8);
	else planeSize /= (8 / bpp);
	planeSize += pad * h;
	if (planeSize + getHandle().offset() > getHandle().length()) {
		planeSize -= (pad * h);

		// sometimes we have RGB images with a single padding byte
		if (planeSize + sizeY + getHandle().offset() <= getHandle().length()) {
			pad = 1;
			planeSize += h;
		}
		else {
			pad = 0;
		}
	}

	getHandle().skipBytes(rowsToSkip * pad);

	final byte[] rawPlane = new byte[planeSize];
	getHandle().read(rawPlane);

	final BitBuffer bb = new BitBuffer(rawPlane);

	final ColorTable palette = meta.getColorTable(0, 0);
	plane.setColorTable(palette);

	final int effectiveC = palette != null && palette.getLength() > 0 ? 1
		: sizeC;
	for (int row = h - 1; row >= 0; row--) {
		final int rowIndex = meta.isInvertY() ? h - 1 - row : row;
		bb.skipBits(x * bpp * effectiveC);
		for (int i = 0; i < w * effectiveC; i++) {
			if (bpp <= 8) {
				buf[rowIndex * w * effectiveC + i] = (byte) (bb.getBits(bpp) &
					0xff);
			}
			else {
				for (int b = 0; b < bpp / 8; b++) {
					buf[(bpp / 8) * (rowIndex * w * effectiveC + i) + b] = (byte) (bb
						.getBits(8) & 0xff);
				}
			}
		}
		if (row > 0) {
			bb.skipBits((sizeX - w - x) * bpp * effectiveC + pad * 8);
		}
	}

	if (imageMeta.getAxisLength(Axes.CHANNEL) > 1) {
		ImageTools.bgrToRgb(buf, imageMeta.getInterleavedAxisCount() > 0, 1,
			(int) imageMeta.getAxisLength(Axes.CHANNEL));
	}
	return plane;
}
 
Example 17
Source File: NativeQTFormat.java    From scifio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void writePlane(final int imageIndex, final long planeIndex,
	final Plane plane, final Interval bounds) throws FormatException,
	IOException
{
	final byte[] buf = plane.getBytes();
	checkParams(imageIndex, planeIndex, buf, bounds);
	if (needLegacy) {
		legacy.savePlane(imageIndex, planeIndex, plane, bounds);
		return;
	}

	final Metadata meta = getMetadata();
	final boolean interleaved = plane.getImageMetadata()
		.getInterleavedAxisCount() > 0;
	// get the width and height of the image
	final int width = (int) meta.get(imageIndex).getAxisLength(Axes.X);
	// need to check if the width is a multiple of 8
	// if it is, great; if not, we need to pad each scanline with enough
	// bytes to make the width a multiple of 8

	final int nChannels = (int) meta.get(imageIndex).getAxisLength(
		Axes.CHANNEL);

	final int xIndex = meta.get(imageIndex).getAxisIndex(Axes.X);
	final int yIndex = meta.get(imageIndex).getAxisIndex(Axes.Y);
	final int x = (int) bounds.min(xIndex), y = (int) bounds.min(yIndex), //
			w = (int) bounds.dimension(xIndex), h = (int) bounds.dimension(
				yIndex);

	getHandle().seek(offsets.get((int) planeIndex) + y * (nChannels * width +
		pad));

	// invert each pixel
	// this will makes the colors look right in other readers (e.g.
	// xine),
	// but needs to be reversed in QTReader

	final byte[] tmp = new byte[buf.length];
	if (nChannels == 1 && !needLegacy) {
		for (int i = 0; i < buf.length; i++) {
			tmp[i] = (byte) (255 - buf[i]);
		}
	}
	else System.arraycopy(buf, 0, tmp, 0, buf.length);

	if (!interleaved) {
		// need to write interleaved data
		final byte[] tmp2 = new byte[tmp.length];
		System.arraycopy(tmp, 0, tmp2, 0, tmp.length);
		for (int i = 0; i < tmp.length; i++) {
			final int c = i / (w * h);
			final int index = i % (w * h);
			tmp[index * nChannels + c] = tmp2[i];
		}
	}

	final int rowLen = tmp.length / h;
	for (int row = 0; row < h; row++) {
		getHandle().skipBytes(nChannels * x);
		getHandle().write(tmp, row * rowLen, rowLen);
		for (int i = 0; i < pad; i++) {
			getHandle().writeByte(0);
		}
		if (row < h - 1) {
			getHandle().skipBytes(nChannels * (width - w - x));
		}
	}
	numWritten++;
}
 
Example 18
Source File: EPSFormat.java    From scifio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void writePlane(final int imageIndex, final long planeIndex,
	final Plane plane, final Interval bounds) throws FormatException,
	IOException
{

	final byte[] buf = plane.getBytes();
	final boolean interleaved = plane.getImageMetadata()
		.getInterleavedAxisCount() > 0;
	checkParams(imageIndex, planeIndex, buf, bounds);
	final ImageMetadata imageMetadata = getMetadata().get(imageIndex);
	final int xAxis = imageMetadata.getAxisIndex(Axes.X);
	final int yAxis = imageMetadata.getAxisIndex(Axes.Y);
	final int x = (int) bounds.min(xAxis);
	final int y = (int) bounds.min(yAxis);
	final int w = (int) bounds.dimension(xAxis);
	final int h = (int) bounds.dimension(yAxis);
	final int sizeX = (int) imageMetadata.getAxisLength(Axes.X);
	final int nChannels = (int) imageMetadata.getAxisLength(Axes.CHANNEL);

	// write pixel data
	// for simplicity, write 80 char lines

	final int planeSize = (int) (bounds.max(xAxis) * bounds.max(yAxis));

	final StringBuilder buffer = new StringBuilder();

	final int offset = y * sizeX * nChannels * 2;
	final DataHandle<Location> handle = getHandle();
	handle.seek(planeOffset + offset);
	for (int row = 0; row < h; row++) {
		handle.skipBytes(nChannels * x * 2);
		for (int col = 0; col < w * nChannels; col++) {
			final int i = row * w * nChannels + col;
			final int index = interleaved || nChannels == 1 ? i : (i %
				nChannels) * planeSize + (i / nChannels);
			final String s = Integer.toHexString(buf[index]);
			// only want last 2 characters of s
			if (s.length() > 1) buffer.append(s.substring(s.length() - 2));
			else {
				buffer.append("0");
				buffer.append(s);
			}
		}
		buffer.append('\n');
		handle.writeBytes(buffer.toString());
		buffer.delete(0, buffer.length());
		handle.skipBytes(nChannels * (sizeX - w - x) * 2);
	}

	// write footer

	handle.seek(handle.length());
	handle.writeBytes("\nshowpage\n");
}
 
Example 19
Source File: NonCirculantNormalizationFactor.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected void createNormalizationImageSemiNonCirculant(Interval fastFFTInterval) {

		// k is the window size (valid image region)
		final int length = k.numDimensions();

		final long[] n = new long[length];
		final long[] nFFT = new long[length];

		// n is the valid image size plus the extended region
		// also referred to as object space size
		for (int d = 0; d < length; d++) {
			n[d] = k.dimension(d) + l.dimension(d) - 1;
		}

		// nFFT is the size of n after (potentially) extending further
		// to a fast FFT size
		for (int d = 0; d < length; d++) {
			nFFT[d] = fastFFTInterval.dimension(d);
		}

		FinalDimensions fd = new FinalDimensions(nFFT);

		// create the normalization image
		normalization = create.calculate(fd);

		// size of the measurement window
		final Point size = new Point(length);
		final long[] sizel = new long[length];

		for (int d = 0; d < length; d++) {
			size.setPosition(k.dimension(d), d);
			sizel[d] = k.dimension(d);
		}

		// starting point of the measurement window when it is centered in fft space
		final Point start = new Point(length);
		final long[] startl = new long[length];
		final long[] endl = new long[length];

		for (int d = 0; d < length; d++) {
			start.setPosition((nFFT[d] - k.dimension(d)) / 2, d);
			startl[d] = (nFFT[d] - k.dimension(d)) / 2;
			endl[d] = startl[d] + sizel[d] - 1;
		}

		// size of the object space
		final Point maskSize = new Point(length);
		final long[] maskSizel = new long[length];

		for (int d = 0; d < length; d++) {
			maskSize.setPosition(Math.min(n[d], nFFT[d]), d);
			maskSizel[d] = Math.min(n[d], nFFT[d]);
		}

		// starting point of the object space within the fft space
		final Point maskStart = new Point(length);
		final long[] maskStartl = new long[length];

		for (int d = 0; d < length; d++) {
			maskStart.setPosition((Math.max(0, nFFT[d] - n[d]) / 2), d);
			maskStartl[d] = (Math.max(0, nFFT[d] - n[d]) / 2);
		}

		final RandomAccessibleInterval<O> temp = Views.interval(normalization,
			new FinalInterval(startl, endl));
		final Cursor<O> normCursor = Views.iterable(temp).cursor();

		// draw a cube the size of the measurement space
		while (normCursor.hasNext()) {
			normCursor.fwd();
			normCursor.get().setReal(1.0);
		}

		final Img<O> tempImg = create.calculate(fd);

		// 3. correlate psf with the output of step 2.
		correlater.compute(normalization, tempImg);

		normalization = tempImg;

		final Cursor<O> cursorN = normalization.cursor();

		while (cursorN.hasNext()) {
			cursorN.fwd();

			if (cursorN.get().getRealFloat() <= 1e-3f) {
				cursorN.get().setReal(1.0f);

			}
		}
	}
 
Example 20
Source File: MinimalTIFFFormat.java    From scifio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
		public ByteArrayPlane openPlane(final int imageIndex, final long planeIndex,
			final ByteArrayPlane plane, final Interval bounds,
			final SCIFIOConfig config) throws FormatException, IOException
		{
			final Metadata meta = getMetadata();
			plane.setColorTable(meta.getColorTable(imageIndex, planeIndex));
			final byte[] buf = plane.getBytes();
			final IFDList ifds = meta.getIfds();
			final TiffParser tiffParser = meta.getTiffParser();
			final int xIndex = meta.get(imageIndex).getAxisIndex(Axes.X);
			final int yIndex = meta.get(imageIndex).getAxisIndex(Axes.Y);
			final int x = (int) bounds.min(xIndex);
			final int y = (int) bounds.min(yIndex);
			final int w = (int) bounds.dimension(xIndex);
			final int h = (int) bounds.dimension(yIndex);
			FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex, buf.length,
				bounds);

			final IFD firstIFD = ifds.get(0);
			meta.setLastPlane(planeIndex);
			final IFD ifd = ifds.get((int) planeIndex);
			if ((firstIFD.getCompression() == TiffCompression.JPEG_2000 || firstIFD
				.getCompression() == TiffCompression.JPEG_2000_LOSSY) && meta
					.getResolutionLevels() != null)
			{
				// FIXME: resolution levels
//        if (getCoreIndex() > 0) {
//          ifd = meta.getSubResolutionIFDs().get(planeIndex).get(getCoreIndex() - 1);
//        }
				setResolutionLevel(ifd);
			}

			tiffParser.getSamples(ifd, buf, x, y, w, h);

			final boolean float16 = meta.get(imageIndex)
				.getPixelType() == FormatTools.FLOAT && firstIFD
					.getBitsPerSample()[0] == 16;
			final boolean float24 = meta.get(imageIndex)
				.getPixelType() == FormatTools.FLOAT && firstIFD
					.getBitsPerSample()[0] == 24;

			if (float16 || float24) {
				final int nPixels = w * h * (int) meta.get(imageIndex).getAxisLength(
					Axes.CHANNEL);
				final int nBytes = float16 ? 2 : 3;
				final int mantissaBits = float16 ? 10 : 16;
				final int exponentBits = float16 ? 5 : 7;
				final int maxExponent = (int) Math.pow(2, exponentBits) - 1;
				final int bits = (nBytes * 8) - 1;

				final byte[] newBuf = new byte[buf.length];
				for (int i = 0; i < nPixels; i++) {
					final int v = Bytes.toInt(buf, i * nBytes, nBytes, meta.get(
						imageIndex).isLittleEndian());
					final int sign = v >> bits;
					int exponent = (v >> mantissaBits) & (int) (Math.pow(2,
						exponentBits) - 1);
					int mantissa = v & (int) (Math.pow(2, mantissaBits) - 1);

					if (exponent == 0) {
						if (mantissa != 0) {
							while ((mantissa & (int) Math.pow(2, mantissaBits)) == 0) {
								mantissa <<= 1;
								exponent--;
							}
							exponent++;
							mantissa &= (int) (Math.pow(2, mantissaBits) - 1);
							exponent += 127 - (Math.pow(2, exponentBits - 1) - 1);
						}
					}
					else if (exponent == maxExponent) {
						exponent = 255;
					}
					else {
						exponent += 127 - (Math.pow(2, exponentBits - 1) - 1);
					}

					mantissa <<= (23 - mantissaBits);

					final int value = (sign << 31) | (exponent << 23) | mantissa;
					Bytes.unpack(value, newBuf, i * 4, 4, meta.get(imageIndex)
						.isLittleEndian());
				}
				System.arraycopy(newBuf, 0, buf, 0, newBuf.length);
			}

			return plane;
		}