Example usage for java.awt.image WritableRaster setSample

List of usage examples for java.awt.image WritableRaster setSample

Introduction

In this page you can find the example usage for java.awt.image WritableRaster setSample.

Prototype

public void setSample(int x, int y, int b, double s) 

Source Link

Document

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a double for input.

Usage

From source file:Main.java

static BufferedImage average(BufferedImage[] images) {
    BufferedImage average = new BufferedImage(images[0].getWidth(), images[0].getHeight(),
            BufferedImage.TYPE_BYTE_GRAY);
    WritableRaster raster = average.getRaster().createCompatibleWritableRaster();
    for (int k = 0; k < images[0].getHeight(); ++k) {
        for (int j = 0; j < images[0].getWidth(); ++j) {
            float sum = 0.0f;
            for (int i = 0; i < images.length; ++i) {
                sum = sum + images[i].getRaster().getSample(j, k, 0);
            }/*from  w w  w  .j av  a2  s .  com*/
            raster.setSample(j, k, 0, Math.round(sum / images.length));
        }
    }
    average.setData(raster);
    return average;
}

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Creates a {@link WritableRaster writable raster}.
 * //  w w  w .  j a v a  2 s  .  c o  m
 * @param width width of the raster to create.
 * @param height height of the raster to create.
 * @param dataClass data type for the raster. If <code>null</code>, defaults to double.
 * @param sampleModel the samplemodel to use. If <code>null</code>, defaults to 
 *                  <code>new ComponentSampleModel(dataType, width, height, 1, width, new int[]{0});</code>.
 * @param value value to which to set the raster to. If null, the default of the raster creation is 
 *                  used, which is 0.
 * @return a {@link WritableRaster writable raster}.
 */
public static WritableRaster createDoubleWritableRaster(int width, int height, Class<?> dataClass,
        SampleModel sampleModel, Double value) {
    int dataType = DataBuffer.TYPE_DOUBLE;
    if (dataClass != null) {
        if (dataClass.isAssignableFrom(Integer.class)) {
            dataType = DataBuffer.TYPE_INT;
        } else if (dataClass.isAssignableFrom(Float.class)) {
            dataType = DataBuffer.TYPE_FLOAT;
        } else if (dataClass.isAssignableFrom(Byte.class)) {
            dataType = DataBuffer.TYPE_BYTE;
        }
    }
    if (sampleModel == null) {
        sampleModel = new ComponentSampleModel(dataType, width, height, 1, width, new int[] { 0 });
    }

    WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, null);
    if (value != null) {
        // autobox only once
        double v = value;

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                raster.setSample(x, y, 0, v);
            }
        }
    }
    return raster;
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * scales bands to min = 0 & max = 2^8 or 2^16
 *
 * @param image/* w  w w. j  av  a 2 s  . co  m*/
 * @param min   int[] containing minima per band
 * @param max
 * @return
 */
public static BufferedImage scaleIntensities(BufferedImage image, int[] min, int[] max)
        throws IllegalArgumentException {
    WritableRaster raster = image.getRaster();

    if ((min.length != max.length) || min.length != raster.getNumBands())
        throw new IllegalArgumentException(
                "Please ensure consistency of min and max arrays and number of bands in image");

    int width = image.getWidth();
    int height = image.getHeight();

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            for (int band = 0; band < raster.getNumBands(); band++) {
                int pixel = raster.getSample(col, row, band);
                if (pixel < min[band])
                    pixel = min[band];
                if (pixel > max[band])
                    pixel = max[band];
                pixel = ((int) (((((double) pixel - min[band]) / (max[band] - min[band]))
                        * ((int) Math.pow(2, image.getColorModel().getPixelSize()) - 1)) + 0.5));
                raster.setSample(col, row, band, pixel);
            }
        }
    }

    return image;
}

From source file:nitf.imageio.NITFReader.java

/**
 * Optimization to read the entire image in one fell swoop... This is most
 * likely the common use case for this codec, so we hope this optimization
 * will be helpful.// www . j a v  a  2  s .  c  o  m
 * 
 * @param imageIndex
 * @param sourceXSubsampling
 * @param sourceYSubsampling
 * @param bandOffsets
 * @param pixelSize
 * @param imRas
 * @throws IOException
 */
protected void readFullImage(int imageIndex, Rectangle destRegion, int sourceXSubsampling,
        int sourceYSubsampling, int[] bandOffsets, int pixelSize, WritableRaster imRas) throws IOException {
    try {
        ImageSubheader subheader = record.getImages()[imageIndex].getSubheader();
        int numCols = destRegion.width;
        int numRows = destRegion.height;

        int nBands = subheader.getBandCount();

        /*
         * NOTE: This is a "fix" that will be removed once the underlying
         * NITRO library gets patched. Currently, if you make a request of a
         * single band, it doesn't matter which band you request - the data
         * from the first band will be returned regardless. This is
         * obviously wrong. To thwart this, we will read all bands, then
         * scale down what we return to the user based on their actual
         * request.
         */

        int[] requestBands = bandOffsets;
        /*
         * if (nBands != bandOffsets.length && bandOffsets.length == 1
         * && bandOffsets[0] != 0)
         * {
         * requestBands = new int[nBands];
         * for (int i = 0; i < nBands; ++i)
         * requestBands[i] = i;
         * }
         */

        int bufSize = numCols * numRows * pixelSize;
        byte[][] imageBuf = new byte[requestBands.length][bufSize];

        // make a SubWindow from the params
        // TODO may want to read by blocks or rows to make faster and more
        // memory efficient
        SubWindow window;
        window = new SubWindow();
        window.setNumBands(requestBands.length);
        window.setBandList(requestBands);
        window.setNumCols(numCols);
        window.setNumRows(numRows);
        window.setStartCol(0);
        window.setStartRow(0);

        // the NITRO library can do the subsampling for us
        if (sourceYSubsampling != 1 || sourceXSubsampling != 1) {
            DownSampler downSampler = new PixelSkipDownSampler(sourceYSubsampling, sourceXSubsampling);
            window.setDownSampler(downSampler);
        }

        // String pixelJustification = subheader.getPixelJustification()
        // .getStringData().trim();
        // boolean shouldSwap = pixelJustification.equals("R");

        // since this is Java, we need the data in big-endian format
        // boolean shouldSwap = ByteOrder.nativeOrder() !=
        // ByteOrder.BIG_ENDIAN;

        nitf.ImageReader imageReader = getImageReader(imageIndex);
        imageReader.read(window, imageBuf);

        List<ByteBuffer> bandBufs = new ArrayList<ByteBuffer>();

        for (int i = 0; i < bandOffsets.length; ++i) {
            ByteBuffer bandBuf = null;

            // the special "fix" we added needs to do this
            if (bandOffsets.length != requestBands.length) {
                bandBuf = ByteBuffer.wrap(imageBuf[bandOffsets[i]]);
            } else {
                bandBuf = ByteBuffer.wrap(imageBuf[i]);
            }
            // ban dBuf.order(ByteOrder.nativeOrder());
            // shouldSwap ? ByteOrder.LITTLE_ENDIAN
            // : ByteOrder.BIG_ENDIAN);

            bandBufs.add(bandBuf);
        }

        // optimization for 1 band case... just dump the whole thing
        if (bandOffsets.length == 1) {
            ByteBuffer bandBuf = bandBufs.get(0);

            switch (pixelSize) {
            case 1:
                ByteBuffer rasterByteBuf = ByteBuffer.wrap(((DataBufferByte) imRas.getDataBuffer()).getData());
                rasterByteBuf.put(bandBuf);
                break;
            case 2:
                ShortBuffer rasterShortBuf = ShortBuffer
                        .wrap(((DataBufferUShort) imRas.getDataBuffer()).getData());
                rasterShortBuf.put(bandBuf.asShortBuffer());
                break;
            case 4:
                FloatBuffer rasterFloatBuf = FloatBuffer
                        .wrap(((DataBufferFloat) imRas.getDataBuffer()).getData());
                rasterFloatBuf.put(bandBuf.asFloatBuffer());
                break;
            case 8:
                DoubleBuffer rasterDoubleBuf = DoubleBuffer
                        .wrap(((DataBufferDouble) imRas.getDataBuffer()).getData());
                rasterDoubleBuf.put(bandBuf.asDoubleBuffer());
                break;
            }
        } else {
            // for multi-band case, we need to iterate over each pixel...
            // TODO -- optimize this!... somehow

            for (int srcY = 0, srcX = 0; srcY < numRows; srcY++) {
                // Copy each (subsampled) source pixel into imRas
                for (int dstX = 0; dstX < numCols; srcX += pixelSize, dstX++) {
                    for (int i = 0; i < bandOffsets.length; ++i) {
                        ByteBuffer bandBuf = bandBufs.get(i);

                        switch (pixelSize) {
                        case 1:
                            imRas.setSample(dstX, srcY, i, bandBuf.get(srcX));
                            break;
                        case 2:
                            imRas.setSample(dstX, srcY, i, bandBuf.getShort(srcX));
                            break;
                        case 4:
                            imRas.setSample(dstX, srcY, i, bandBuf.getFloat(srcX));
                            break;
                        case 8:
                            imRas.setSample(dstX, srcY, i, bandBuf.getDouble(srcX));
                            break;
                        }
                    }
                }
            }
        }
    } catch (NITFException e1) {
        throw new IOException(ExceptionUtils.getStackTrace(e1));
    }
}

From source file:nitf.imageio.NITFReader.java

/**
 * Reads image data as bytes for the given region, and writes it to the
 * given writable raster//from   ww  w .j a v  a 2s  . c o  m
 * 
 * @param sourceRegion
 * @param sourceXSubsampling
 * @param sourceYSubsampling
 * @param bandOffsets
 * @param destinationOffset
 * @param imRas
 * @return Raster
 * @throws IOException
 */
protected void readRaster(int imageIndex, Rectangle sourceRegion, Rectangle destRegion, int sourceXSubsampling,
        int sourceYSubsampling, int[] bandOffsets, int pixelSize, Point destinationOffset, WritableRaster imRas)
        throws IOException {
    checkIndex(imageIndex);

    try {
        ImageSubheader subheader = record.getImages()[imageIndex].getSubheader();
        int numCols = subheader.getNumCols().getIntData();
        int numRows = subheader.getNumRows().getIntData();

        // try to optimize the read call by reading in the entire
        // image at once
        if ((destRegion.height * sourceYSubsampling) == numRows
                && (destRegion.width * sourceXSubsampling) == numCols) {
            readFullImage(imageIndex, destRegion, sourceXSubsampling, sourceYSubsampling, bandOffsets,
                    pixelSize, imRas);
            return;
        }
        // the general purpose case
        else {
            int colBytes = destRegion.width * pixelSize;

            int dstMinX = imRas.getMinX();
            int dstMaxX = dstMinX + imRas.getWidth() - 1;
            int dstMinY = imRas.getMinY();
            int dstMaxY = dstMinY + imRas.getHeight() - 1;
            // int swap = 0;

            int nBands = subheader.getBandCount();

            /*
             * NOTE: This is a "fix" that will be removed once the
             * underlying NITRO library gets patched. Currently, if you make
             * a request of a single band, it doesn't matter which band you
             * request - the data from the first band will be returned
             * regardless. This is obviously wrong. To thwart this, we will
             * read all bands, then scale down what we return to the user
             * based on their actual request.
             */
            int[] requestBands = new int[nBands];
            for (int i = 0; i < nBands; ++i)
                requestBands[i] = i;

            byte[][] rowBuf = new byte[requestBands.length][colBytes];

            // make a SubWindow from the params
            // TODO may want to read by blocks or rows to make faster and
            // more
            // memory efficient
            SubWindow window;
            window = new SubWindow();
            window.setNumBands(requestBands.length);
            window.setBandList(requestBands);
            window.setNumCols(destRegion.width);
            window.setNumRows(1);
            window.setStartCol(sourceRegion.x);
            window.setStartRow(sourceRegion.y);

            // the NITRO library can do the subsampling for us
            if (sourceYSubsampling != 1 || sourceXSubsampling != 1) {
                DownSampler downSampler = new PixelSkipDownSampler(sourceYSubsampling, sourceXSubsampling);
                window.setDownSampler(downSampler);
            }

            // String pixelJustification = record.getImages()[imageIndex]
            // .getSubheader().getPixelJustification().getStringData()
            // .trim();
            // swap = pixelJustification.equals("R") ? 1 : 0;

            List<ByteBuffer> bandBufs = new ArrayList<ByteBuffer>();
            for (int i = 0; i < requestBands.length; ++i) {
                ByteBuffer bandBuf = null;
                bandBuf = ByteBuffer.wrap(rowBuf[i]);
                // bandBuf.order(ByteOrder.nativeOrder());
                // bandBuf.order(swap == 0 ? ByteOrder.BIG_ENDIAN
                // : ByteOrder.LITTLE_ENDIAN);
                bandBufs.add(bandBuf);
            }

            nitf.ImageReader imageReader = getImageReader(imageIndex);
            for (int srcY = 0; srcY < sourceRegion.height; srcY++) {
                if (sourceYSubsampling != 1 && (srcY % sourceYSubsampling) != 0)
                    continue;

                window.setStartRow(sourceRegion.y + srcY);

                // Read the row
                try {
                    imageReader.read(window, rowBuf);
                } catch (NITFException e) {
                    throw new IIOException("Error reading line " + srcY, e);
                }

                // Determine where the row will go in the destination
                int dstY = destinationOffset.y + srcY / sourceYSubsampling;
                if (dstY < dstMinY) {
                    continue; // The row is above imRas
                }
                if (dstY > dstMaxY) {
                    break; // We're done with the image
                }

                // Copy each (subsampled) source pixel into imRas
                for (int srcX = 0, dstX = destinationOffset.x; srcX < colBytes; srcX += pixelSize, dstX++) {
                    if (dstX < dstMinX) {
                        continue;
                    }
                    if (dstX > dstMaxX) {
                        break;
                    }

                    for (int i = 0; i < bandOffsets.length; ++i) {
                        ByteBuffer bandBuf = bandBufs.get(bandOffsets[i]);

                        switch (pixelSize) {
                        case 1:
                            imRas.setSample(dstX, dstY, i, bandBuf.get(srcX));
                            break;
                        case 2:
                            imRas.setSample(dstX, dstY, i, bandBuf.getShort(srcX));
                            break;
                        case 4:
                            imRas.setSample(dstX, dstY, i, bandBuf.getFloat(srcX));
                            break;
                        case 8:
                            imRas.setSample(dstX, dstY, i, bandBuf.getDouble(srcX));
                            break;
                        }
                    }
                }
            }
        }
    } catch (NITFException e1) {
        throw new IOException(ExceptionUtils.getStackTrace(e1));
    }
}

From source file:org.geotools.imageio.netcdf.NetCDFImageReader.java

/**
 * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam)
 *///  w w w . j a v  a  2  s  . c  om
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    clearAbortRequest();

    final Slice2DIndex slice2DIndex = getSlice2DIndex(imageIndex);
    final String variableName = slice2DIndex.getVariableName();
    final VariableAdapter wrapper = getCoverageDescriptor(new NameImpl(variableName));

    /*
     * Fetches the parameters that are not already processed by utility
     * methods like 'getDestination' or 'computeRegions' (invoked below).
     */
    final int strideX, strideY;
    // final int[] srcBands;
    final int[] dstBands;
    if (param != null) {
        strideX = param.getSourceXSubsampling();
        strideY = param.getSourceYSubsampling();
        // srcBands = param.getSourceBands();
        dstBands = param.getDestinationBands();
    } else {
        strideX = 1;
        strideY = 1;
        // srcBands = null;
        dstBands = null;
    }

    /*
     * Gets the destination image of appropriate size. We create it now
     * since it is a convenient way to get the number of destination bands.
     */
    final int width = wrapper.getWidth();
    final int height = wrapper.getHeight();
    /*
     * Computes the source region (in the NetCDF file) and the destination
     * region (in the buffered image). Copies those informations into UCAR
     * Range structure.
     */
    final Rectangle srcRegion = new Rectangle();
    final Rectangle destRegion = new Rectangle();
    computeRegions(param, width, height, null, srcRegion, destRegion);

    // Flipping is needed only when the input latitude coordinate is ordered
    // from min to max
    if (needsFlipping) {
        flipVertically(param, height, srcRegion);
    }
    int destWidth = destRegion.x + destRegion.width;
    int destHeight = destRegion.y + destRegion.height;

    /*
     * build the ranges that need to be read from each 
     * dimension based on the source region
     */
    final List<Range> ranges = new LinkedList<Range>();
    try {
        // add the ranges the COARDS way: T, Z, Y, X
        // T
        int first = slice2DIndex.getTIndex();
        int length = 1;
        int stride = 1;
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Z
        first = slice2DIndex.getZIndex();
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Y
        first = srcRegion.y;
        length = srcRegion.height;
        stride = strideY;
        ranges.add(new Range(first, first + length - 1, stride));
        // X
        first = srcRegion.x;
        length = srcRegion.width;
        stride = strideX;
        ranges.add(new Range(first, first + length - 1, stride));
    } catch (InvalidRangeException e) {
        throw netcdfFailure(e);
    }

    /*
     * create the section of multidimensional array indices
     * that defines the exact data that need to be read 
     * for this image index and parameters 
     */
    final Section section = new Section(ranges);

    /*
     * Setting SampleModel and ColorModel.
     */
    final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight);
    final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel);

    final WritableRaster raster = Raster.createWritableRaster(sampleModel, new Point(0, 0));
    final BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

    CoordinateAxis axis = wrapper.variableDS.getCoordinateSystems().get(0).getLatAxis();
    boolean flipYAxis = false;
    try {
        Array yAxisStart = axis.read(new Section().appendRange(2));
        float y1 = yAxisStart.getFloat(0);
        float y2 = yAxisStart.getFloat(1);
        if (y2 > y1) {
            flipYAxis = true;
        }
    } catch (InvalidRangeException e) {
        throw new RuntimeException(e);
    }
    /*
     * Reads the requested sub-region only.
     */
    processImageStarted(imageIndex);
    final int numDstBands = 1;
    final float toPercent = 100f / numDstBands;
    final int type = raster.getSampleModel().getDataType();
    final int xmin = destRegion.x;
    final int ymin = destRegion.y;
    final int xmax = destRegion.width + xmin;
    final int ymax = destRegion.height + ymin;
    for (int zi = 0; zi < numDstBands; zi++) {
        // final int srcBand = (srcBands == null) ? zi : srcBands[zi];
        final int dstBand = (dstBands == null) ? zi : dstBands[zi];
        final Array array;
        try {
            // TODO leak through
            array = wrapper.variableDS.read(section);
        } catch (InvalidRangeException e) {
            throw netcdfFailure(e);
        }
        if (flipYAxis) {
            final IndexIterator it = array.getIndexIterator();
            for (int y = ymax; --y >= ymin;) {
                for (int x = xmin; x < xmax; x++) {
                    switch (type) {
                    case DataBuffer.TYPE_DOUBLE: {
                        raster.setSample(x, y, dstBand, it.getDoubleNext());
                        break;
                    }
                    case DataBuffer.TYPE_FLOAT: {
                        raster.setSample(x, y, dstBand, it.getFloatNext());
                        break;
                    }
                    case DataBuffer.TYPE_BYTE: {
                        byte b = it.getByteNext();
                        // int myByte = (0x000000FF & ((int) b));
                        // short anUnsignedByte = (short) myByte;
                        // raster.setSample(x, y, dstBand, anUnsignedByte);
                        raster.setSample(x, y, dstBand, b);
                        break;
                    }
                    default: {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                        break;
                    }
                    }
                }
            }
        } else {
            switch (type) {
            case DataBuffer.TYPE_DOUBLE: {
                DoubleBuffer doubleBuffer = array.getDataAsByteBuffer().asDoubleBuffer();
                double[] samples = new double[destRegion.width * destRegion.height];
                doubleBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            }
            case DataBuffer.TYPE_FLOAT:
                float[] samples = new float[destRegion.width * destRegion.height];
                FloatBuffer floatBuffer = array.getDataAsByteBuffer().asFloatBuffer();
                floatBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            case DataBuffer.TYPE_BYTE:
                //THIS ONLY WORKS FOR ONE BAND!!
                raster.setDataElements(xmin, ymin, destRegion.width, destRegion.height,
                        array.getDataAsByteBuffer().array());
                break;
            case DataBuffer.TYPE_INT:
                IntBuffer intBuffer = array.getDataAsByteBuffer().asIntBuffer();
                int[] intSamples = new int[destRegion.width * destRegion.height];
                intBuffer.get(intSamples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, intSamples);
                break;
            default: {
                final IndexIterator it = array.getIndexIterator();
                for (int y = ymin; y < ymax; y++) {
                    for (int x = xmin; x < xmax; x++) {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                    }
                }
                break;
            }

            }

        }
        /*
         * Checks for abort requests after reading. It would be a waste of a
         * potentially good image (maybe the abort request occurred after we
         * just finished the reading) if we didn't implemented the
         * 'isCancel()' method. But because of the later, which is checked
         * by the NetCDF library, we can't assume that the image is
         * complete.
         */
        if (abortRequested()) {
            processReadAborted();
            return image;
        }
        /*
         * Reports progress here, not in the deeper loop, because the costly
         * part is the call to 'variable.read(...)' which can't report
         * progress. The loop that copy pixel values is fast, so reporting
         * progress there would be pointless.
         */
        processImageProgress(zi * toPercent);
    }
    processImageComplete();
    return image;
}

From source file:org.geotools.imageio.unidata.UnidataImageReader.java

/**
 * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam)
 *//*from  w w w .  j a  va2  s. c  om*/
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    clearAbortRequest();

    final UnidataSlice2DIndex slice2DIndex = getSlice2DIndex(imageIndex);
    final String variableName = slice2DIndex.getVariableName();
    final UnidataVariableAdapter wrapper = getCoverageDescriptor(new NameImpl(variableName));

    /*
     * Fetches the parameters that are not already processed by utility
     * methods like 'getDestination' or 'computeRegions' (invoked below).
     */
    final int strideX, strideY;
    // final int[] srcBands;
    final int[] dstBands;
    if (param != null) {
        strideX = param.getSourceXSubsampling();
        strideY = param.getSourceYSubsampling();
        // srcBands = param.getSourceBands();
        dstBands = param.getDestinationBands();
    } else {
        strideX = 1;
        strideY = 1;
        // srcBands = null;
        dstBands = null;
    }

    /*
     * Gets the destination image of appropriate size. We create it now
     * since it is a convenient way to get the number of destination bands.
     */
    final int width = wrapper.getWidth();
    final int height = wrapper.getHeight();
    /*
     * Computes the source region (in the NetCDF file) and the destination
     * region (in the buffered image). Copies those informations into UCAR
     * Range structure.
     */
    final Rectangle srcRegion = new Rectangle();
    final Rectangle destRegion = new Rectangle();
    computeRegions(param, width, height, null, srcRegion, destRegion);
    flipVertically(param, height, srcRegion);
    int destWidth = destRegion.x + destRegion.width;
    int destHeight = destRegion.y + destRegion.height;

    /*
     * build the ranges that need to be read from each 
     * dimension based on the source region
     */
    final List<Range> ranges = new LinkedList<Range>();
    try {
        // add the ranges the COARDS way: T, Z, Y, X
        // T
        int first = slice2DIndex.getTIndex();
        int length = 1;
        int stride = 1;
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Z
        first = slice2DIndex.getZIndex();
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Y
        first = srcRegion.y;
        length = srcRegion.height;
        stride = strideY;
        ranges.add(new Range(first, first + length - 1, stride));
        // X
        first = srcRegion.x;
        length = srcRegion.width;
        stride = strideX;
        ranges.add(new Range(first, first + length - 1, stride));
    } catch (InvalidRangeException e) {
        throw netcdfFailure(e);
    }

    /*
     * create the section of multidimensional array indices
     * that defines the exact data that need to be read 
     * for this image index and parameters 
     */
    final Section section = new Section(ranges);

    /*
     * Setting SampleModel and ColorModel.
     */
    final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight);
    final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel);

    final WritableRaster raster = Raster.createWritableRaster(sampleModel, new Point(0, 0));
    final BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

    CoordinateAxis axis = wrapper.variableDS.getCoordinateSystems().get(0).getLatAxis();
    boolean flipYAxis = false;
    try {
        Array yAxisStart = axis.read(new Section().appendRange(2));
        float y1 = yAxisStart.getFloat(0);
        float y2 = yAxisStart.getFloat(1);
        if (y2 > y1) {
            flipYAxis = true;
        }
    } catch (InvalidRangeException e) {
        throw new RuntimeException(e);
    }
    /*
     * Reads the requested sub-region only.
     */
    processImageStarted(imageIndex);
    final int numDstBands = 1;
    final float toPercent = 100f / numDstBands;
    final int type = raster.getSampleModel().getDataType();
    final int xmin = destRegion.x;
    final int ymin = destRegion.y;
    final int xmax = destRegion.width + xmin;
    final int ymax = destRegion.height + ymin;
    for (int zi = 0; zi < numDstBands; zi++) {
        // final int srcBand = (srcBands == null) ? zi : srcBands[zi];
        final int dstBand = (dstBands == null) ? zi : dstBands[zi];
        final Array array;
        try {
            // TODO leak through
            array = wrapper.variableDS.read(section);
        } catch (InvalidRangeException e) {
            throw netcdfFailure(e);
        }
        if (flipYAxis) {
            final IndexIterator it = array.getIndexIterator();
            for (int y = ymax; --y >= ymin;) {
                for (int x = xmin; x < xmax; x++) {
                    switch (type) {
                    case DataBuffer.TYPE_DOUBLE: {
                        raster.setSample(x, y, dstBand, it.getDoubleNext());
                        break;
                    }
                    case DataBuffer.TYPE_FLOAT: {
                        raster.setSample(x, y, dstBand, it.getFloatNext());
                        break;
                    }
                    case DataBuffer.TYPE_BYTE: {
                        byte b = it.getByteNext();
                        // int myByte = (0x000000FF & ((int) b));
                        // short anUnsignedByte = (short) myByte;
                        // raster.setSample(x, y, dstBand, anUnsignedByte);
                        raster.setSample(x, y, dstBand, b);
                        break;
                    }
                    default: {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                        break;
                    }
                    }
                }
            }
        } else {
            switch (type) {
            case DataBuffer.TYPE_DOUBLE: {
                DoubleBuffer doubleBuffer = array.getDataAsByteBuffer().asDoubleBuffer();
                double[] samples = new double[destRegion.width * destRegion.height];
                doubleBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            }
            case DataBuffer.TYPE_FLOAT:
                float[] samples = new float[destRegion.width * destRegion.height];
                FloatBuffer floatBuffer = array.getDataAsByteBuffer().asFloatBuffer();
                floatBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            case DataBuffer.TYPE_BYTE:
                //THIS ONLY WORKS FOR ONE BAND!!
                raster.setDataElements(xmin, ymin, destRegion.width, destRegion.height,
                        array.getDataAsByteBuffer().array());
                break;
            case DataBuffer.TYPE_INT:
                IntBuffer intBuffer = array.getDataAsByteBuffer().asIntBuffer();
                int[] intSamples = new int[destRegion.width * destRegion.height];
                intBuffer.get(intSamples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, intSamples);
                break;
            default: {
                final IndexIterator it = array.getIndexIterator();
                for (int y = ymin; y < ymax; y++) {
                    for (int x = xmin; x < xmax; x++) {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                    }
                }
                break;
            }

            }

        }
        /*
         * Checks for abort requests after reading. It would be a waste of a
         * potentially good image (maybe the abort request occurred after we
         * just finished the reading) if we didn't implemented the
         * 'isCancel()' method. But because of the later, which is checked
         * by the NetCDF library, we can't assume that the image is
         * complete.
         */
        if (abortRequested()) {
            processReadAborted();
            return image;
        }
        /*
         * Reports progress here, not in the deeper loop, because the costly
         * part is the call to 'variable.read(...)' which can't report
         * progress. The loop that copy pixel values is fast, so reporting
         * progress there would be pointless.
         */
        processImageProgress(zi * toPercent);
    }
    processImageComplete();
    return image;
}

From source file:org.jgrasstools.hortonmachine.modules.geomorphology.curvatures.OmsCurvaturesBivariate.java

@Execute
public void process() throws Exception {
    if (!concatOr(outProf == null, doReset)) {
        return;/*from w ww.  ja v a  2 s.c  o  m*/
    }
    checkNull(inElev);

    if (pCells < 3) {
        pCells = 3;
    }
    if (pCells % 2 == 0) {
        pCells = pCells + 1;
    }

    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inElev);
    int nCols = regionMap.getCols();
    int nRows = regionMap.getRows();
    double xRes = regionMap.getXres();
    double yRes = regionMap.getYres();

    RandomIter elevationIter = CoverageUtilities.getRandomIterator(inElev);

    WritableRaster profWR = CoverageUtilities.createDoubleWritableRaster(nCols, nRows, null, null,
            doubleNovalue);
    WritableRaster planWR = CoverageUtilities.createDoubleWritableRaster(nCols, nRows, null, null,
            doubleNovalue);
    WritableRaster slopeWR = CoverageUtilities.createDoubleWritableRaster(nCols, nRows, null, null,
            doubleNovalue);
    WritableRaster aspectWR = CoverageUtilities.createDoubleWritableRaster(nCols, nRows, null, null,
            doubleNovalue);

    final double[] planProfSlopeAspect = new double[4];
    double disXX = Math.pow(xRes, 2.0);
    double disYY = Math.pow(yRes, 2.0);
    /*
     * calculate curvatures
     */
    pm.beginTask("Processing...", nRows - 2);
    for (int r = 1; r < nRows - 1; r++) {
        if (isCanceled(pm)) {
            return;
        }
        for (int c = 1; c < nCols - 1; c++) {
            calculateCurvatures(elevationIter, planProfSlopeAspect, nCols, nRows, c, r, xRes, yRes, disXX,
                    disYY, pCells);
            planWR.setSample(c, r, 0, planProfSlopeAspect[0]);
            profWR.setSample(c, r, 0, planProfSlopeAspect[1]);
            slopeWR.setSample(c, r, 0, planProfSlopeAspect[2]);
            aspectWR.setSample(c, r, 0, planProfSlopeAspect[3]);
        }
        pm.worked(1);
    }
    pm.done();

    if (isCanceled(pm)) {
        return;
    }
    CoordinateReferenceSystem crs = inElev.getCoordinateReferenceSystem();
    outProf = CoverageUtilities.buildCoverage("prof_curvature", profWR, regionMap, crs);
    outPlan = CoverageUtilities.buildCoverage("plan_curvature", planWR, regionMap, crs);
    outSlope = CoverageUtilities.buildCoverage("slope", slopeWR, regionMap, crs);
    outAspect = CoverageUtilities.buildCoverage("aspect", aspectWR, regionMap, crs);
}

From source file:org.mrgeo.services.mrspyramid.MrsPyramidService.java

public Raster createColorScaleSwatch(ColorScale cs, String format, int width, int height) throws Exception {
    double[] extrema = { 0, 0 };

    WritableRaster wr = RasterUtils.createEmptyRaster(width, height, 1, DataBuffer.TYPE_FLOAT);

    if (width > height) {
        extrema[1] = width - 1;/*from   www  .  jav a 2 s.c o m*/
        for (int w = 0; w < width; w++) {
            for (int h = 0; h < height; h++) {
                wr.setSample(w, h, 0, w);
            }
        }
    } else {
        extrema[1] = height - 1;
        for (int h = 0; h < height; h++) {
            for (int w = 0; w < width; w++) {
                wr.setSample(w, h, 0, extrema[1] - h);
            }
        }
    }

    ColorScaleApplier applier = (ColorScaleApplier) ImageHandlerFactory.getHandler(format,
            ColorScaleApplier.class);

    return applier.applyColorScale(wr, cs, extrema, new double[] { -9999, 0 });
}

From source file:org.photovault.image.RawConvOpImage.java

/**
 * Compute single tile of the image/*www .  jav a  2  s .c om*/
 * @param x
 * @param y
 * @return
 */
@Override
public Raster computeTile(int x, int y) {
    if (contrastLut == null) {
        createLumLut();
    }
    Raster r = source.getTile(x, y);
    WritableRaster w = r.createCompatibleWritableRaster(r.getMinX(), r.getMinY(), r.getWidth(), r.getHeight());
    int startX = r.getMinX();
    int startY = r.getMinY();
    for (int l = startY; l < startY + r.getHeight(); l++) {
        for (int c = startX; c < startX + r.getWidth(); c++) {
            long sr = r.getSample(c, l, 0);
            long sg = r.getSample(c, l, 1);
            long sb = r.getSample(c, l, 2);
            long avg = (sr + sg + sb) / 3;
            long m = contrastLut[(int) avg];
            long[] pixel = new long[3];
            pixel[0] = (sr * m) >> 16;
            pixel[1] = (sg * m) >> 16;
            pixel[2] = (sb * m) >> 16;
            long clippedSum = 0;
            long totalHeadroom = 0;
            boolean clipped[] = new boolean[3];
            int channelsClipped = 0;
            int channelsUnclipped = 0;
            for (int n = 0; n < 3; n++) {
                if (pixel[n] > 65535) {
                    channelsClipped++;
                    clipped[n] = true;
                    clippedSum += pixel[n] - 65535;
                } else {
                    clipped[n] = false;
                    totalHeadroom += 65536 - pixel[n];
                    channelsUnclipped++;
                }
            }
            if (channelsClipped > 0) {
                for (int n = 0; n < 3; n++) {
                    if (!clipped[n]) {
                        // Spread the clipped energy to other channels so that
                        // they reach saturation at the same time
                        long headroom = 65536 - pixel[n];
                        pixel[n] += clippedSum * headroom / totalHeadroom;
                    }
                }
            }
            //                while ( channelsClipped > 0 && clippedSum > 0 &&
            //                        channelsUnclipped > 0 ) {
            //                    long spreaded = 0;
            //                    long spreadPerChan = clippedSum / channelsUnclipped +1;
            //                    for ( int n = 0; n < 3; n++ ) {
            //                        if ( !clipped[n] ) {
            //                            long add = Math.min( spreadPerChan, 65536 - pixel[n] );
            //                            pixel[n] += add;
            //                            spreaded += add;
            //                            if ( pixel[n] > 65535 ) {
            //                                channelsUnclipped--;
            //                            }
            //                        }
            //                    }
            //                    clippedSum -= spreaded;
            //                }
            try {
                w.setSample(c, l, 0, Math.min(65535, pixel[0]));
                w.setSample(c, l, 1, Math.min(65535, pixel[1]));
                w.setSample(c, l, 2, Math.min(65535, pixel[2]));
            } catch (ArrayIndexOutOfBoundsException e) {
                log.error(e);
            }
        }
    }
    return w;
}