Example usage for java.awt Rectangle isEmpty

List of usage examples for java.awt Rectangle isEmpty

Introduction

In this page you can find the example usage for java.awt Rectangle isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Usage

From source file:org.esa.s2tbx.dataio.jp2.internal.JP2TileOpImage.java

private void computeRectDirect(WritableRaster dest, Rectangle destRect) {
    try (OpenJP2Decoder decoder = new OpenJP2Decoder(this.cacheDir, this.imageFile, this.bandIndex,
            this.dataType, getLevel(), 20, tileIndex)) {
        Raster readTileImage = null;
        final DataBuffer dataBuffer = dest.getDataBuffer();
        int tileWidth = this.getTileWidth();
        int tileHeight = this.getTileHeight();
        final int fileTileX = destRect.x / tileLayout.tileWidth;
        final int fileTileY = destRect.y / tileLayout.tileHeight;
        int fileTileOriginX = destRect.x - fileTileX * tileLayout.tileWidth;
        int fileTileOriginY = destRect.y - fileTileY * tileLayout.tileHeight;
        Dimension dimensions = decoder.getImageDimensions();
        Rectangle fileTileRect = new Rectangle(0, 0, dimensions.width, dimensions.height);

        if (fileTileOriginX == 0 && tileLayout.tileWidth == tileWidth && fileTileOriginY == 0
                && tileLayout.tileHeight == tileHeight && tileWidth * tileHeight == dataBuffer.getSize()) {
            readTileImage = decoder.read(null);
        } else {//from w w  w  .j  a v  a  2s .c  o m
            final Rectangle tileRect = new Rectangle(fileTileOriginX, fileTileOriginY, tileWidth, tileHeight);
            final Rectangle intersection = fileTileRect.intersection(tileRect);
            if (!intersection.isEmpty()) {
                readTileImage = decoder.read(intersection);
            }
        }
        if (readTileImage != null) {
            Raster readBandRaster = readTileImage.createChild(0, 0, readTileImage.getWidth(),
                    readTileImage.getHeight(), 0, 0, bands);
            dest.setDataElements(dest.getMinX(), dest.getMinY(), readBandRaster);
        }

    } catch (IOException e) {
        logger.severe(e.getMessage());
    }
}

From source file:org.esa.s2tbx.dataio.s2.S2TileOpImage.java

protected void readTileData(File outputFile, int tileX, int tileY, int tileWidth, int tileHeight, int jp2TileX,
        int jp2TileY, int jp2TileWidth, int jp2TileHeight, short[] tileData, Rectangle destRect)
        throws IOException {

    // todo - we still have a synchronisation problem here: often zero areas are generated in a tile.
    // This does not happen, if we synchronise entire computeRect() on the instance, but it is less efficient.
    try (FileImageInputStream fis = new FileImageInputStream(outputFile)) {
        int jp2Width, jp2Height;
        final String[] tokens = fis.readLine().split(" ");
        long dataPos = fis.getStreamPosition();
        if (tokens.length != 6) {
            throw new IOException("Unexpected PGX tile image format");
        }//w ww.j av  a2  s . c o  m

        // String pg = tokens[0];   // PG
        // String ml = tokens[1];   // ML
        // String plus = tokens[2]; // +
        try {
            // int jp2File.nbits = Integer.parseInt(tokens[3]);
            jp2Width = Integer.parseInt(tokens[4]);
            jp2Height = Integer.parseInt(tokens[5]);
        } catch (NumberFormatException e) {
            throw new IOException("Unexpected PGX tile image format");
        }
        if (jp2Width > jp2TileWidth || jp2Height > jp2TileHeight) {
            throw new IllegalStateException(
                    String.format("width (=%d) > tileWidth (=%d) || height (=%d) > tileHeight (=%d)", jp2Width,
                            jp2TileWidth, jp2Height, jp2TileHeight));
        }

        int jp2X = destRect.x - jp2TileX * jp2TileWidth;
        int jp2Y = destRect.y - jp2TileY * jp2TileHeight;
        if (jp2X < 0 || jp2Y < 0) {
            throw new IllegalStateException(String.format("jp2X (=%d) < 0 || jp2Y (=%d) < 0", jp2X, jp2Y));
        }

        if (jp2X == 0 && jp2Width == tileWidth && jp2Y == 0 && jp2Height == tileHeight
                && tileWidth * tileHeight == tileData.length) {
            fis.seek(dataPos);
            fis.readFully(tileData, 0, tileData.length);
        } else {
            final Rectangle jp2FileRect = new Rectangle(0, 0, jp2Width, jp2Height);
            final Rectangle tileRect = new Rectangle(jp2X, jp2Y, tileWidth, tileHeight);
            final Rectangle intersection = jp2FileRect.intersection(tileRect);
            if (!intersection.isEmpty()) {
                SystemUtils.LOG
                        .fine(String.format("%s: tile=(%d,%d): jp2FileRect=%s, tileRect=%s, intersection=%s\n",
                                outputFile, tileX, tileY, jp2FileRect, tileRect, intersection));
                long seekPos = dataPos
                        + S2Config.SAMPLE_BYTE_COUNT * (intersection.y * jp2Width + intersection.x);
                int tilePos = 0;
                for (int y = 0; y < intersection.height; y++) {
                    fis.seek(seekPos);
                    fis.readFully(tileData, tilePos, intersection.width);
                    seekPos += S2Config.SAMPLE_BYTE_COUNT * jp2Width;
                    tilePos += tileWidth;
                    for (int x = intersection.width; x < tileWidth; x++) {
                        tileData[y * tileWidth + x] = S2Config.FILL_CODE_OUT_OF_X_BOUNDS;
                    }
                }

                for (int y = intersection.height; y < tileHeight; y++) {
                    for (int x = 0; x < tileWidth; x++) {
                        tileData[y * tileWidth + x] = S2Config.FILL_CODE_OUT_OF_Y_BOUNDS;
                    }
                }
            } else {
                Arrays.fill(tileData, S2Config.FILL_CODE_NO_INTERSECTION);
            }
        }
    }
}

From source file:org.geotools.coverage.io.util.Utilities.java

/**
 * Evaluates the requested envelope and builds a new adjusted version of it fitting this coverage envelope.
 * //from   www  .j  a va  2s .c  om
 * <p>
 * While adjusting the requested envelope this methods also compute the source region as a rectangle which is suitable for a successive read
 * operation with {@link ImageIO} to do crop-on-read.
 * 
 * @param originalGridToWorld
 * 
 * @param coordinateReferenceSystem
 * 
 * 
 * @param requestedEnvelope is the envelope we are requested to load.
 * @param sourceRegion represents the area to load in raster space. This parameter cannot be null since it gets filled with whatever the crop
 *        region is depending on the <code>requestedEnvelope</code>.
 * @param requestedDim is the requested region where to load data of the specified envelope.
 * @param readGridToWorld the Grid to world transformation to be used
 * @param wgs84BaseEnvelope2D
 * @return the adjusted requested envelope, empty if no requestedEnvelope has been specified, {@code null} in case the requested envelope does not
 *         intersect the coverage envelope or in case the adjusted requested envelope is covered by a too small raster region (an empty region).
 * 
 * @throws DataSourceException in case something bad occurs
 */
public static GeneralEnvelope evaluateRequestedParams(GridEnvelope originalGridRange, Envelope2D baseEnvelope2D,
        CoordinateReferenceSystem spatialReferenceSystem2D, MathTransform originalGridToWorld,
        GeneralEnvelope requestedEnvelope, Rectangle sourceRegion, Rectangle requestedDim,
        MathTransform2D readGridToWorld, Envelope2D wgs84BaseEnvelope2D) throws DataSourceException {

    GeneralEnvelope adjustedRequestedEnvelope = new GeneralEnvelope(2);
    GeneralGridEnvelope baseGridRange = (GeneralGridEnvelope) originalGridRange;

    try {
        // ////////////////////////////////////////////////////////////////
        //
        // Check if we have something to load by intersecting the
        // requested envelope with the bounds of this data set.
        //
        // ////////////////////////////////////////////////////////////////
        if (requestedEnvelope != null) {
            final GeneralEnvelope requestedEnvelope2D = Utilities.getRequestedEnvelope2D(requestedEnvelope);

            // ////////////////////////////////////////////////////////////
            //
            // INTERSECT ENVELOPES AND CROP Destination REGION
            //
            // ////////////////////////////////////////////////////////////
            adjustedRequestedEnvelope = Utilities.getIntersection(baseEnvelope2D, spatialReferenceSystem2D,
                    requestedEnvelope2D, requestedDim, readGridToWorld, wgs84BaseEnvelope2D);
            if (adjustedRequestedEnvelope == null)
                return null;

            // /////////////////////////////////////////////////////////////////////
            //
            // CROP SOURCE REGION
            //
            // /////////////////////////////////////////////////////////////////////
            sourceRegion.setRect(Utilities.getCropRegion(adjustedRequestedEnvelope,
                    Utilities.getOriginalGridToWorld(originalGridToWorld, PixelInCell.CELL_CORNER)));
            if (sourceRegion.isEmpty()) {
                if (LOGGER.isLoggable(Level.INFO)) {
                    LOGGER.log(Level.INFO, "Too small envelope resulting in empty cropped raster region");
                }
                return null;
                // TODO: Future versions may define a 1x1 rectangle starting
                // from the lower coordinate
            }
            if (!sourceRegion.intersects(baseGridRange.toRectangle()) || sourceRegion.isEmpty())
                throw new DataSourceException("The crop region is invalid.");
            sourceRegion.setRect(sourceRegion.intersection(baseGridRange.toRectangle()));

            if (LOGGER.isLoggable(Level.FINE)) {
                StringBuilder sb = new StringBuilder("Adjusted Requested Envelope = ")
                        .append(adjustedRequestedEnvelope.toString()).append("\n")
                        .append("Requested raster dimension = ").append(requestedDim.toString()).append("\n")
                        .append("Corresponding raster source region = ").append(sourceRegion.toString());
                LOGGER.log(Level.FINE, sb.toString());
            }

        } else {
            // don't use the source region. Set an empty one
            sourceRegion.setBounds(new Rectangle(0, 0, Integer.MIN_VALUE, Integer.MIN_VALUE));
        }
    } catch (TransformException e) {
        throw new DataSourceException("Unable to create a coverage for this source", e);
    } catch (FactoryException e) {
        throw new DataSourceException("Unable to create a coverage for this source", e);
    }
    return adjustedRequestedEnvelope;
}

From source file:org.geotools.gce.imagecollection.Utils.java

/**
 * Checks that the provided <code>dimensions</code> when intersected with
 * the source region used by the provided {@link ImageReadParam} instance
 * does not result in an empty {@link Rectangle}.
 * // www .  j a v  a2 s  .  com
 * <p>
 * Input parameters cannot be null.
 * 
 * @param readParameters
 *            an instance of {@link ImageReadParam} for which we want to
 *            check the source region element.
 * @param dimensions
 *            an instance of {@link Rectangle} to use for the check.
 * @return <code>true</code> if the intersection is not empty,
 *         <code>false</code> otherwise.
 */
static boolean checkEmptySourceRegion(final ImageReadParam readParameters, final Rectangle dimensions) {
    Utilities.ensureNonNull("readDimension", dimensions);
    Utilities.ensureNonNull("readP", readParameters);
    final Rectangle sourceRegion = readParameters.getSourceRegion();
    Rectangle.intersect(sourceRegion, dimensions, sourceRegion);
    if (sourceRegion.isEmpty())
        return true;
    readParameters.setSourceRegion(sourceRegion);
    return false;
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

/**
* Load a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* 
* @param imageReadParameters the {@link ImageReadParam} to use for reading.
* @param index the index to use for the {@link ImageReader}.
* @param cropBBox the bbox to use for cropping. 
* @param mosaicWorldToGrid the cropping grid to world transform.
* @param request the incoming request to satisfy.
* @param hints {@link Hints} to be used for creating this raster.
* @return a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* @throws IOException in case an error occurs.
*//* ww w .j ava 2 s.c  om*/
public GranuleLoadingResult loadRaster(final ImageReadParam imageReadParameters, final int index,
        final ReferencedEnvelope cropBBox, final MathTransform2D mosaicWorldToGrid,
        final RasterLayerRequest request, final Hints hints) throws IOException {

    if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
        final String name = Thread.currentThread().getName();
        LOGGER.finer("Thread:" + name + " Loading raster data for granuleDescriptor " + this.toString());
    }
    ImageReadParam readParameters = null;
    int imageIndex;
    final boolean useFootprint = roiProvider != null
            && request.getFootprintBehavior() != FootprintBehavior.None;
    Geometry inclusionGeometry = useFootprint ? roiProvider.getFootprint() : null;
    final ReferencedEnvelope bbox = useFootprint
            ? new ReferencedEnvelope(granuleBBOX.intersection(inclusionGeometry.getEnvelopeInternal()),
                    granuleBBOX.getCoordinateReferenceSystem())
            : granuleBBOX;
    boolean doFiltering = false;
    if (filterMe && useFootprint) {
        doFiltering = Utils.areaIsDifferent(inclusionGeometry, baseGridToWorld, granuleBBOX);
    }

    // intersection of this tile bound with the current crop bbox
    final ReferencedEnvelope intersection = new ReferencedEnvelope(bbox.intersection(cropBBox),
            cropBBox.getCoordinateReferenceSystem());
    if (intersection.isEmpty()) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    // check if the requested bbox intersects or overlaps the requested area 
    if (useFootprint && inclusionGeometry != null && !JTS.toGeometry(cropBBox).intersects(inclusionGeometry)) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {
        //
        //get info about the raster we have to read
        //

        // get a stream
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null)
            return null;

        // get a reader and try to cache the relevant SPI
        if (cachedReaderSPI == null) {
            reader = ImageIOExt.getImageioReader(inStream);
            if (reader != null)
                cachedReaderSPI = reader.getOriginatingProvider();
        } else
            reader = cachedReaderSPI.createReaderInstance();
        if (reader == null) {
            if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
                LOGGER.warning(new StringBuilder("Unable to get s reader for granuleDescriptor ")
                        .append(this.toString()).append(" with request ").append(request.toString())
                        .append(" Resulting in no granule loaded: Empty result").toString());
            }
            return null;
        }
        // set input
        customizeReaderInitialization(reader, hints);
        reader.setInput(inStream);

        // Checking for heterogeneous granules
        if (request.isHeterogeneousGranules()) {
            // create read parameters
            readParameters = new ImageReadParam();

            //override the overviews controller for the base layer
            imageIndex = ReadParamsController.setReadParams(
                    request.spatialRequestHelper.getRequestedResolution(), request.getOverviewPolicy(),
                    request.getDecimationPolicy(), readParameters, request.rasterManager, overviewsController);
        } else {
            imageIndex = index;
            readParameters = imageReadParameters;
        }

        //get selected level and base level dimensions
        final GranuleOverviewLevelDescriptor selectedlevel = getLevel(imageIndex, reader);

        // now create the crop grid to world which can be used to decide
        // which source area we need to crop in the selected level taking
        // into account the scale factors imposed by the selection of this
        // level together with the base level grid to world transformation
        AffineTransform2D cropWorldToGrid = new AffineTransform2D(selectedlevel.gridToWorldTransformCorner);
        cropWorldToGrid = (AffineTransform2D) cropWorldToGrid.inverse();
        // computing the crop source area which lives into the
        // selected level raster space, NOTICE that at the end we need to
        // take into account the fact that we might also decimate therefore
        // we cannot just use the crop grid to world but we need to correct
        // it.
        final Rectangle sourceArea = CRS.transform(cropWorldToGrid, intersection).toRectangle2D().getBounds();
        //gutter
        if (selectedlevel.baseToLevelTransform.isIdentity()) {
            sourceArea.grow(2, 2);
        }
        XRectangle2D.intersect(sourceArea, selectedlevel.rasterDimensions, sourceArea);//make sure roundings don't bother us
        // is it empty??
        if (sourceArea.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.fine("Got empty area for granuleDescriptor " + this.toString() + " with request "
                        + request.toString() + " Resulting in no granule loaded: Empty result");

            }
            return null;

        } else if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
            LOGGER.finer("Loading level " + imageIndex + " with source region: " + sourceArea + " subsampling: "
                    + readParameters.getSourceXSubsampling() + "," + readParameters.getSourceYSubsampling()
                    + " for granule:" + granuleUrl);
        }

        // Setting subsampling 
        int newSubSamplingFactor = 0;
        final String pluginName = cachedReaderSPI.getPluginClassName();
        if (pluginName != null && pluginName.equals(ImageUtilities.DIRECT_KAKADU_PLUGIN)) {
            final int ssx = readParameters.getSourceXSubsampling();
            final int ssy = readParameters.getSourceYSubsampling();
            newSubSamplingFactor = ImageIOUtilities.getSubSamplingFactor2(ssx, ssy);
            if (newSubSamplingFactor != 0) {
                if (newSubSamplingFactor > maxDecimationFactor && maxDecimationFactor != -1) {
                    newSubSamplingFactor = maxDecimationFactor;
                }
                readParameters.setSourceSubsampling(newSubSamplingFactor, newSubSamplingFactor, 0, 0);
            }
        }

        // set the source region
        readParameters.setSourceRegion(sourceArea);
        RenderedImage raster;
        try {
            // read
            raster = request.getReadType().read(readParameters, imageIndex, granuleUrl,
                    selectedlevel.rasterDimensions, reader, hints, false);

        } catch (Throwable e) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.log(java.util.logging.Level.FINE,
                        "Unable to load raster for granuleDescriptor " + this.toString() + " with request "
                                + request.toString() + " Resulting in no granule loaded: Empty result",
                        e);
            }
            return null;
        }

        // use fixed source area
        sourceArea.setRect(readParameters.getSourceRegion());

        //
        // setting new coefficients to define a new affineTransformation
        // to be applied to the grid to world transformation
        // -----------------------------------------------------------------------------------
        //
        // With respect to the original envelope, the obtained planarImage
        // needs to be rescaled. The scaling factors are computed as the
        // ratio between the cropped source region sizes and the read
        // image sizes.
        //
        // place it in the mosaic using the coords created above;
        double decimationScaleX = ((1.0 * sourceArea.width) / raster.getWidth());
        double decimationScaleY = ((1.0 * sourceArea.height) / raster.getHeight());
        final AffineTransform decimationScaleTranform = XAffineTransform.getScaleInstance(decimationScaleX,
                decimationScaleY);

        // keep into account translation  to work into the selected level raster space
        final AffineTransform afterDecimationTranslateTranform = XAffineTransform
                .getTranslateInstance(sourceArea.x, sourceArea.y);

        // now we need to go back to the base level raster space
        final AffineTransform backToBaseLevelScaleTransform = selectedlevel.baseToLevelTransform;

        // now create the overall transform
        final AffineTransform finalRaster2Model = new AffineTransform(baseGridToWorld);
        finalRaster2Model.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if (!XAffineTransform.isIdentity(backToBaseLevelScaleTransform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(backToBaseLevelScaleTransform);
        if (!XAffineTransform.isIdentity(afterDecimationTranslateTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(afterDecimationTranslateTranform);
        if (!XAffineTransform.isIdentity(decimationScaleTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(decimationScaleTranform);

        // adjust roi
        if (useFootprint) {

            ROIGeometry transformed;
            try {
                transformed = roiProvider.getTransformedROI(finalRaster2Model.createInverse());
                if (transformed.getAsGeometry().isEmpty()) {
                    // inset might have killed the geometry fully
                    return null;
                }

                PlanarImage pi = PlanarImage.wrapRenderedImage(raster);
                if (!transformed.intersects(pi.getBounds())) {
                    return null;
                }
                pi.setProperty("ROI", transformed);
                raster = pi;

            } catch (NoninvertibleTransformException e) {
                if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                    LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                            + " due to a problem when managing the ROI");
                return null;
            }

        }
        // keep into account translation factors to place this tile
        finalRaster2Model.preConcatenate((AffineTransform) mosaicWorldToGrid);
        final Interpolation interpolation = request.getInterpolation();

        //paranoiac check to avoid that JAI freaks out when computing its internal layouT on images that are too small
        Rectangle2D finalLayout = ImageUtilities.layoutHelper(raster, (float) finalRaster2Model.getScaleX(),
                (float) finalRaster2Model.getScaleY(), (float) finalRaster2Model.getTranslateX(),
                (float) finalRaster2Model.getTranslateY(), interpolation);
        if (finalLayout.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                        + " due to jai scale bug creating a null source area");
            return null;
        }

        // apply the affine transform  conserving indexed color model
        final RenderingHints localHints = new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL,
                interpolation instanceof InterpolationNearest ? Boolean.FALSE : Boolean.TRUE);
        if (XAffineTransform.isIdentity(finalRaster2Model, Utils.AFFINE_IDENTITY_EPS)) {
            return new GranuleLoadingResult(raster, null, granuleUrl, doFiltering, pamDataset);
        } else {
            //
            // In case we are asked to use certain tile dimensions we tile
            // also at this stage in case the read type is Direct since
            // buffered images comes up untiled and this can affect the
            // performances of the subsequent affine operation.
            //
            final Dimension tileDimensions = request.getTileDimensions();
            if (tileDimensions != null && request.getReadType().equals(ReadType.DIRECT_READ)) {
                final ImageLayout layout = new ImageLayout();
                layout.setTileHeight(tileDimensions.width).setTileWidth(tileDimensions.height);
                localHints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout));
            } else {
                if (hints != null && hints.containsKey(JAI.KEY_IMAGE_LAYOUT)) {
                    final Object layout = hints.get(JAI.KEY_IMAGE_LAYOUT);
                    if (layout != null && layout instanceof ImageLayout) {
                        localHints
                                .add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, ((ImageLayout) layout).clone()));
                    }
                }
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_CACHE)) {
                final Object cache = hints.get(JAI.KEY_TILE_CACHE);
                if (cache != null && cache instanceof TileCache)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, (TileCache) cache));
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_SCHEDULER)) {
                final Object scheduler = hints.get(JAI.KEY_TILE_SCHEDULER);
                if (scheduler != null && scheduler instanceof TileScheduler)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_SCHEDULER, (TileScheduler) scheduler));
            }
            boolean addBorderExtender = true;
            if (hints != null && hints.containsKey(JAI.KEY_BORDER_EXTENDER)) {
                final Object extender = hints.get(JAI.KEY_BORDER_EXTENDER);
                if (extender != null && extender instanceof BorderExtender) {
                    localHints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, (BorderExtender) extender));
                    addBorderExtender = false;
                }
            }
            // BORDER extender
            if (addBorderExtender) {
                localHints.add(ImageUtilities.BORDER_EXTENDER_HINTS);
            }

            ImageWorker iw = new ImageWorker(raster);
            iw.setRenderingHints(localHints);
            iw.affine(finalRaster2Model, interpolation, request.getBackgroundValues());
            return new GranuleLoadingResult(iw.getRenderedImage(), null, granuleUrl, doFiltering, pamDataset);
        }

    } catch (IllegalStateException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (org.opengis.referencing.operation.NoninvertibleTransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (TransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;

    } finally {
        try {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && inStream != null) {
                inStream.close();
            }
        } finally {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && reader != null) {
                reader.dispose();
            }
        }
    }
}

From source file:org.geotools.gce.imagemosaic.RasterLayerResponse.java

/**
 * Once we reach this method it means that we have loaded all the images
 * which were intersecting the requested envelope. Next step is to create
 * the final mosaic image and cropping it to the exact requested envelope.
 * @param visitor /*from w ww  .  ja v  a2  s .  co m*/
 * 
 * @return A {@link RenderedImage}}.
 */
private RenderedImage buildMosaic(final MosaicBuilder visitor) throws IOException {

    // build final layout and use it for cropping purposes
    final ImageLayout layout = new ImageLayout(rasterBounds.x, rasterBounds.y, rasterBounds.width,
            rasterBounds.height);

    //prepare hints
    final Dimension tileDimensions = request.getTileDimensions();
    if (tileDimensions != null) {
        layout.setTileHeight(tileDimensions.width).setTileWidth(tileDimensions.height);
    }
    final RenderingHints localHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
    if (hints != null && !hints.isEmpty()) {
        if (hints.containsKey(JAI.KEY_TILE_CACHE)) {
            final Object tc = hints.get(JAI.KEY_TILE_CACHE);
            if (tc != null && tc instanceof TileCache)
                localHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, (TileCache) tc));
        }
        boolean addBorderExtender = true;
        if (hints != null && hints.containsKey(JAI.KEY_BORDER_EXTENDER)) {
            final Object extender = hints.get(JAI.KEY_BORDER_EXTENDER);
            if (extender != null && extender instanceof BorderExtender) {
                localHints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, (BorderExtender) extender));
                addBorderExtender = false;
            }
        }
        if (addBorderExtender) {
            localHints.add(ImageUtilities.BORDER_EXTENDER_HINTS);
        }
        if (hints.containsKey(JAI.KEY_TILE_SCHEDULER)) {
            final Object ts = hints.get(JAI.KEY_TILE_SCHEDULER);
            if (ts != null && ts instanceof TileScheduler)
                localHints.add(new RenderingHints(JAI.KEY_TILE_SCHEDULER, (TileScheduler) ts));
        }
    }

    //
    // SPECIAL CASE
    // 1 single tile, we try not do a mosaic.
    final ROI[] sourceRoi = visitor.sourceRoi;
    if (visitor.granulesNumber == 1 && Utils.OPTIMIZE_CROP) {
        // the roi is exactly equal to the 
        final ROI roi = visitor.rois.get(0);
        Rectangle bounds = Utils.toRectangle(roi.getAsShape());
        if (bounds != null) {
            RenderedImage image = visitor.getSourcesAsArray()[0];
            Rectangle imageBounds = PlanarImage.wrapRenderedImage(image).getBounds();
            if (imageBounds.equals(bounds)) {

                // do we need to crop? (image is bigger than requested?)
                if (!rasterBounds.contains(imageBounds)) {
                    // we have to crop
                    XRectangle2D.intersect(imageBounds, rasterBounds, imageBounds);

                    if (imageBounds.isEmpty()) {
                        // return back a constant image
                        return null;
                    }
                    // crop
                    ImageWorker iw = new ImageWorker(image);
                    iw.setRenderingHints(localHints);
                    iw.crop(imageBounds.x, imageBounds.y, imageBounds.width, imageBounds.height);

                    image = iw.getRenderedImage();
                    imageBounds = PlanarImage.wrapRenderedImage(image).getBounds();
                }

                // and, do we need to add a border around the image?
                if (!imageBounds.contains(rasterBounds)) {
                    image = MosaicDescriptor.create(new RenderedImage[] { image },
                            request.isBlend() ? MosaicDescriptor.MOSAIC_TYPE_BLEND
                                    : MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
                            (alphaIn || visitor.doInputTransparency) ? visitor.alphaChannels : null, sourceRoi,
                            visitor.sourceThreshold, backgroundValues, localHints);
                }

                return image;
            }
        }
    }

    // 
    // Final Merge
    // 
    // I can even do a stacking merge or a flat merge
    final RenderedImage mosaic = request.getMergeBehavior().process(visitor.getSourcesAsArray(),
            backgroundValues, visitor.sourceThreshold,
            (alphaIn || visitor.doInputTransparency) ? visitor.alphaChannels : null, sourceRoi,
            request.isBlend() ? MosaicDescriptor.MOSAIC_TYPE_BLEND : MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
            localHints);

    if (setRoiProperty) {

        //Adding globalRoi to the output
        RenderedOp rop = (RenderedOp) mosaic;
        ROI globalRoi = null;
        ROI[] rois = sourceRoi;
        for (int i = 0; i < rois.length; i++) {
            if (globalRoi == null) {
                globalRoi = new ROIGeometry(((ROIGeometry) rois[i]).getAsGeometry());
            } else {
                globalRoi = globalRoi.add(rois[i]);
            }
        }
        rop.setProperty("ROI", globalRoi);
    }

    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine("Mosaic created ");

    // create the coverage
    return mosaic;

}

From source file:org.mitre.mpf.wfm.camel.operations.detection.trackmerging.TrackMergingProcessor.java

private boolean intersects(Track track1, Track track2, double segMinOverlap) {
    if (!StringUtils.equalsIgnoreCase(track1.getType(), track2.getType())) {
        // Tracks of different types should not be candidates for merger. Ex: It would make no sense to merge a motion and speech track.
        return false;
    } else if (StringUtils.equalsIgnoreCase(track1.getType(), "SPEECH")) {
        // Speech tracks should not be candidates for merger.
        return false;
    }/* ww w .  j a v  a  2 s .  c o  m*/

    Detection track1End = track1.getDetections().last();
    Detection track2End = track2.getDetections().first();

    Detection first = (track1End.getMediaOffsetFrame() < track2End.getMediaOffsetFrame()) ? track1End
            : track2End;
    Detection second = (first == track1End) ? track2End : track1End;

    Rectangle rectangle1 = new Rectangle(first.getX(), first.getY(), first.getWidth(), first.getHeight());
    Rectangle rectangle2 = new Rectangle(second.getX(), second.getY(), second.getWidth(), second.getHeight());

    if (rectangle1.getWidth() == 0 || rectangle2.getWidth() == 0 || rectangle1.getHeight() == 0
            || rectangle1.getHeight() == 0) {
        return false;
    }

    Rectangle intersection = rectangle1.intersection(rectangle2);
    if (intersection.isEmpty()) {
        return false;
    }

    double intersectArea = intersection.getHeight() * intersection.getWidth();
    double unionArea = (rectangle2.getHeight() * rectangle2.getWidth())
            + (rectangle1.getHeight() * rectangle1.getWidth()) - intersectArea;
    double percentOverlap = intersectArea / unionArea;

    return percentOverlap > segMinOverlap;
}

From source file:pcgen.gui2.PCGenFrame.java

/**
 * This checks to make sure that the given rectangle will be visible
 * on the current graphics environment//from ww w . ja  v  a 2s  .  c o m
 */
private boolean checkBounds(Rectangle rect) {
    if (rect.isEmpty()) {
        return false;
    }
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

    for (GraphicsDevice device : env.getScreenDevices()) {
        Rectangle bounds = device.getDefaultConfiguration().getBounds();
        if (bounds.contains(rect) || bounds.intersects(rect)) {
            return true;
        }
    }
    return false;
}