Search in sources :

Example 16 with ProcessException

use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.

the class TouchesProcess method execute.

@Override
protected void execute() throws ProcessException {
    try {
        final Geometry geom1 = inputParameters.getValue(GEOM1);
        Geometry geom2 = inputParameters.getValue(GEOM2);
        // ensure geometries are in the same CRS
        final CoordinateReferenceSystem resultCRS = JTS.getCommonCRS(geom1, geom2);
        if (JTS.isConversionNeeded(geom1, geom2)) {
            geom2 = JTS.convertToCRS(geom2, resultCRS);
        }
        final boolean result = geom1.touches(geom2);
        outputParameters.getOrCreate(RESULT).setValue(result);
    } catch (FactoryException ex) {
        throw new ProcessException(ex.getMessage(), this, ex);
    } catch (TransformException ex) {
        throw new ProcessException(ex.getMessage(), this, ex);
    }
}
Also used : Geometry(org.locationtech.jts.geom.Geometry) ProcessException(org.geotoolkit.process.ProcessException) FactoryException(org.opengis.util.FactoryException) TransformException(org.opengis.referencing.operation.TransformException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Example 17 with ProcessException

use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.

the class Categorize method execute.

@Override
protected void execute() throws ProcessException {
    final GridCoverageResource source = getSource();
    final WritableGridCoverageResource destination = getDestination();
    try {
        final GridGeometry inputGG = source.getGridGeometry();
        final GridGeometry readGeom;
        Envelope env = getEnvelope();
        if (env == null) {
            env = inputGG.getEnvelope();
            readGeom = inputGG;
        } else {
            MathTransform gridToCRS = inputGG.getGridToCRS(PixelInCell.CELL_CORNER);
            GeographicBoundingBox bbox = null;
            try {
                bbox = ReferencingUtilities.findGeographicBBox(source).orElse(null);
            } catch (DataStoreException e) {
                /* This error is not directly related to data. It could be
                     * caused by malformed metadata. In which case, we just
                     * ignore it.
                     */
                LOGGER.log(Level.FINE, "Cannot deduce geographic extent from metadata.", e);
            }
            if (env.getCoordinateReferenceSystem() != null) {
                final CoordinateOperation op = CRS.findOperation(inputGG.getCoordinateReferenceSystem(), env.getCoordinateReferenceSystem(), bbox);
                gridToCRS = MathTransforms.concatenate(gridToCRS, op.getMathTransform());
                // Crop area of interest on source coverage area
                final GeneralEnvelope sourceEnv;
                try {
                    sourceEnv = Envelopes.transform(op, inputGG.getEnvelope());
                } catch (TransformException ex) {
                    throw new ProcessException("Cannot check input envelope validity against source coverage.", this, ex);
                }
                sourceEnv.intersect(env);
                env = sourceEnv;
            } else {
                final GeneralEnvelope tmpEnv = new GeneralEnvelope(env);
                tmpEnv.setCoordinateReferenceSystem(inputGG.getCoordinateReferenceSystem());
                // Crop area of interest on source coverage area
                tmpEnv.intersect(inputGG.getEnvelope());
                env = tmpEnv;
            }
            readGeom = new GridGeometry(PixelInCell.CELL_CORNER, gridToCRS, env, GridRoundingMode.ENCLOSING);
        }
        final GridGeometryIterator it = new GridGeometryIterator(readGeom);
        while (it.hasNext()) {
            final GridGeometry sliceGeom = it.next();
            final GeneralEnvelope expectedSliceEnvelope = GeneralEnvelope.castOrCopy(sliceGeom.getEnvelope());
            GridCoverage sourceCvg = source.read(sliceGeom);
            if (sourceCvg instanceof GridCoverageStack) {
                // Try to unravel expected slice
                final Optional<GridCoverage> slice = extractSlice((GridCoverageStack) sourceCvg, sliceGeom.getEnvelope());
                if (slice.isPresent()) {
                    sourceCvg = slice.get();
                }
            }
            // If the reader has not returned a coverage fitting queried
            // geometry, we have to resample input ourselves.
            GridCoverage source2D = sourceCvg;
            source2D = source2D.forConvertedValues(true);
            final boolean compliantCrs = Utilities.equalsApproximately(expectedSliceEnvelope.getCoordinateReferenceSystem(), source2D.getCoordinateReferenceSystem());
            final boolean compliantEnvelope = expectedSliceEnvelope.contains(source2D.getGridGeometry().getEnvelope(), true);
            if (!(compliantCrs && compliantEnvelope)) {
                source2D = resample(source2D, sliceGeom);
            }
            final RenderedImage slice = categorize(source2D.render(null));
            final GridCoverageBuilder builder = new GridCoverageBuilder();
            builder.setDomain(source2D.getGridGeometry());
            builder.setValues(slice);
            final GridCoverage resultCoverage = builder.build();
            destination.write(resultCoverage);
        }
    } catch (TransformException ex) {
        throw new ProcessException("Cannot adapt input geometry", this, ex);
    } catch (FactoryException ex) {
        throw new ProcessException("Failure on EPSG database use", this, ex);
    } catch (DataStoreException ex) {
        throw new ProcessException("Cannot access either input or output data source", this, ex);
    } catch (CancellationException ex) {
        throw new DismissProcessException("Process cancelled", this, ex);
    }
}
Also used : GridGeometryIterator(org.geotoolkit.coverage.grid.GridGeometryIterator) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) DataStoreException(org.apache.sis.storage.DataStoreException) MathTransform(org.opengis.referencing.operation.MathTransform) FactoryException(org.opengis.util.FactoryException) TransformException(org.opengis.referencing.operation.TransformException) CoordinateOperation(org.opengis.referencing.operation.CoordinateOperation) GeographicBoundingBox(org.opengis.metadata.extent.GeographicBoundingBox) Envelope(org.opengis.geometry.Envelope) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope) GridCoverageStack(org.geotoolkit.coverage.grid.GridCoverageStack) ProcessException(org.geotoolkit.process.ProcessException) DismissProcessException(org.geotoolkit.process.DismissProcessException) GridCoverage(org.apache.sis.coverage.grid.GridCoverage) GridCoverageBuilder(org.apache.sis.coverage.grid.GridCoverageBuilder) CancellationException(java.util.concurrent.CancellationException) GridCoverageResource(org.apache.sis.storage.GridCoverageResource) WritableGridCoverageResource(org.apache.sis.storage.WritableGridCoverageResource) WritableGridCoverageResource(org.apache.sis.storage.WritableGridCoverageResource) DismissProcessException(org.geotoolkit.process.DismissProcessException) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope) RenderedImage(java.awt.image.RenderedImage)

Example 18 with ProcessException

use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.

the class Compose method execute.

@Override
protected void execute() throws ProcessException {
    final List<ParameterValueGroup> imageParams = inputParameters.groups(LAYER_PARAM.getName().getCode());
    RenderedImage outImageReference = null;
    SampleDimension[] sampleDimensions = null;
    final int nbCoverage = imageParams.size();
    final GridCoverage[] inGridCoverages = new GridCoverage[nbCoverage];
    final PixelIterator[] inCursors = new PixelIterator[nbCoverage];
    final int[][] inSizes = new int[nbCoverage][2];
    final Geometry[] includeGeometries = new Geometry[nbCoverage];
    final Geometry[] excludeGeometries = new Geometry[nbCoverage];
    // extract coverages and geometries
    for (int i = 0; i < nbCoverage; i++) {
        final Parameters covParam = castOrWrap(imageParams.get(i));
        final GridCoverage coverage = covParam.getValue(COVERAGE_PARAM);
        // extract image informations
        inGridCoverages[i] = coverage;
        final RenderedImage covImg = coverage.render(null);
        inCursors[i] = PixelIterator.create(covImg);
        inSizes[i][0] = covImg.getWidth() - 1;
        inSizes[i][1] = covImg.getHeight() - 1;
        if (outImageReference == null) {
            outImageReference = coverage.render(null);
            sampleDimensions = coverage.getSampleDimensions().toArray(new SampleDimension[0]);
        }
        includeGeometries[i] = covParam.getValue(INCLUDE_PARAM);
        excludeGeometries[i] = covParam.getValue(EXCLUDE_PARAM);
    }
    // compute output grid
    GridGeometry outGridGeom = inputParameters.getValue(GRID_PARAM);
    if (outGridGeom == null) {
        try {
            outGridGeom = getOutputGridGeometry(inGridCoverages);
        } catch (TransformException ex) {
            throw new ProcessException(ex.getMessage(), this, ex);
        }
    }
    final CoordinateReferenceSystem outCrs = outGridGeom.getCoordinateReferenceSystem();
    final AffineTransform2D outGridToCrs = (AffineTransform2D) outGridGeom.getGridToCRS(PixelInCell.CELL_CORNER);
    final AffineTransform2D outCrsToGrid;
    try {
        outCrsToGrid = outGridToCrs.inverse();
    } catch (TransformException ex) {
        throw new ProcessException(ex.getMessage(), this, ex);
    }
    final int outWidth = Math.toIntExact(outGridGeom.getExtent().getSize(0));
    final int outHeight = Math.toIntExact(outGridGeom.getExtent().getSize(1));
    // convert and convert all geometries to output crs as a bit mask
    final WritableRaster[] clips = new WritableRaster[nbCoverage];
    for (int i = 0; i < nbCoverage; i++) {
        final GridGeometry g2d = inGridCoverages[i].getGridGeometry();
        final BufferedImage image = new BufferedImage(outWidth, outHeight, BufferedImage.TYPE_BYTE_BINARY);
        final CoordinateReferenceSystem coverageCrs = g2d.getCoordinateReferenceSystem();
        try {
            MathTransform covCrstoOutCrs = CRS.findOperation(coverageCrs, outCrs, null).getMathTransform();
            // paint in white valid area
            final Graphics2D g = (Graphics2D) image.getGraphics();
            // convert to output grid crs
            g.setTransform(outCrsToGrid);
            // set a clip to coverage envelope
            Geometry clip = GeometricUtilities.toJTSGeometry(g2d.getEnvelope(), WrapResolution.NONE);
            clip.setUserData(coverageCrs);
            g.setClip(new JTSGeometryJ2D(clip, covCrstoOutCrs));
            // set the valid area
            g.setColor(Color.WHITE);
            if (includeGeometries[i] == null) {
                g.setTransform(new AffineTransform());
                g.fillRect(0, 0, outWidth, outHeight);
                g.setTransform(outCrsToGrid);
            } else {
                g.fill(new JTSGeometryJ2D(includeGeometries[i], covCrstoOutCrs));
            }
            // remove exclusion geometry
            if (excludeGeometries[i] != null) {
                covCrstoOutCrs = CRS.findOperation(JTS.findCoordinateReferenceSystem(excludeGeometries[i]), outCrs, null).getMathTransform();
                g.setColor(Color.BLACK);
                g.fill(new JTSGeometryJ2D(excludeGeometries[i], covCrstoOutCrs));
            }
            g.dispose();
        } catch (Exception e) {
            throw new ProcessException(e.getMessage(), this, e);
        }
        clips[i] = image.getRaster();
    }
    // compute output grid crs to source coverage grid crs.
    final MathTransform2D[] outGridCSToSourceGridCS = new MathTransform2D[nbCoverage];
    final Rectangle outRect = new Rectangle(0, 0, outWidth, outHeight);
    for (int i = 0; i < nbCoverage; i++) {
        try {
            final GridGeometry g2d = inGridCoverages[i].getGridGeometry();
            final CoordinateReferenceSystem sourceCrs = g2d.getCoordinateReferenceSystem();
            final MathTransform outCrsToSourceCrs = CRS.findOperation(outCrs, sourceCrs, null).getMathTransform();
            final MathTransform sourceCrsToGrid = g2d.getGridToCRS(PixelInCell.CELL_CENTER).inverse();
            final MathTransform tmpTr = concatenate(outGridToCrs, outCrsToSourceCrs, sourceCrsToGrid);
            if (tmpTr instanceof MathTransform2D) {
                outGridCSToSourceGridCS[i] = (MathTransform2D) tmpTr;
            } else {
                throw new ProcessException("Cannot deduce 2D transform from given data.", this);
            }
        } catch (NoninvertibleTransformException | FactoryException e) {
            throw new ProcessException(e.getMessage(), this, e);
        }
    }
    final BufferedImage outImage = BufferedImages.createImage(outWidth, outHeight, outImageReference);
    final WritableRaster outRaster = outImage.getRaster();
    final double[] pixelBuffer = new double[outImage.getSampleModel().getNumBands()];
    final WritablePixelIterator outIterator = new PixelIterator.Builder().createWritable(outRaster);
    final java.awt.Point clipPos = new java.awt.Point();
    while (outIterator.next()) {
        final java.awt.Point outPos = outIterator.getPosition();
        for (int i = 0; i < clips.length; i++) {
            if (clips[i].getSample(outPos.x, outPos.y, 0) == 1) {
                try {
                    outGridCSToSourceGridCS[i].transform(outPos, clipPos);
                } catch (TransformException e) {
                    throw new ProcessException(e.getMessage(), this, e);
                }
                if (clipPos.x < 0 || clipPos.y < 0 || clipPos.x > inSizes[i][0] || clipPos.y > inSizes[i][1])
                    continue;
                inCursors[i].moveTo(clipPos.x, clipPos.y);
                inCursors[i].getPixel(pixelBuffer);
                outIterator.setPixel(pixelBuffer);
                break;
            }
        }
    }
    final GridCoverageBuilder gcb = new GridCoverageBuilder();
    gcb.setValues(outImage);
    gcb.setDomain(outGridGeom);
    if (sampleDimensions != null)
        gcb.setRanges(sampleDimensions);
    final GridCoverage gridCoverage2d = gcb.build();
    final ParameterValue<?> gridCoverageParamOut = outputParameters.parameter(COVERAGE_PARAM.getName().getCode());
    gridCoverageParamOut.setValue(gridCoverage2d);
}
Also used : MathTransform(org.opengis.referencing.operation.MathTransform) ParameterValueGroup(org.opengis.parameter.ParameterValueGroup) PixelIterator(org.apache.sis.image.PixelIterator) WritablePixelIterator(org.apache.sis.image.WritablePixelIterator) FactoryException(org.opengis.util.FactoryException) Rectangle(java.awt.Rectangle) JTSGeometryJ2D(org.geotoolkit.geometry.jts.awt.JTSGeometryJ2D) BufferedImage(java.awt.image.BufferedImage) WritableRaster(java.awt.image.WritableRaster) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) Parameters(org.apache.sis.parameter.Parameters) NoninvertibleTransformException(org.opengis.referencing.operation.NoninvertibleTransformException) TransformException(org.opengis.referencing.operation.TransformException) SampleDimension(org.apache.sis.coverage.SampleDimension) NoninvertibleTransformException(org.opengis.referencing.operation.NoninvertibleTransformException) ProcessException(org.geotoolkit.process.ProcessException) TransformException(org.opengis.referencing.operation.TransformException) IncompleteGridGeometryException(org.apache.sis.coverage.grid.IncompleteGridGeometryException) FactoryException(org.opengis.util.FactoryException) Graphics2D(java.awt.Graphics2D) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) Geometry(org.locationtech.jts.geom.Geometry) NoninvertibleTransformException(org.opengis.referencing.operation.NoninvertibleTransformException) ProcessException(org.geotoolkit.process.ProcessException) GridCoverage(org.apache.sis.coverage.grid.GridCoverage) WritablePixelIterator(org.apache.sis.image.WritablePixelIterator) GridCoverageBuilder(org.apache.sis.coverage.grid.GridCoverageBuilder) AffineTransform(java.awt.geom.AffineTransform) MathTransform2D(org.opengis.referencing.operation.MathTransform2D) RenderedImage(java.awt.image.RenderedImage) AffineTransform2D(org.apache.sis.internal.referencing.j2d.AffineTransform2D)

Example 19 with ProcessException

use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.

the class CoverageToFeaturesProcess method execute.

/**
 *  {@inheritDoc }
 */
@Override
protected void execute() throws ProcessException {
    try {
        final GridCoverageResource reader = inputParameters.getValue(CoverageToFeaturesDescriptor.READER_IN);
        final GridCoverage coverage = reader.read(null);
        final GridGeometry gridGeom = reader.getGridGeometry();
        final CoverageToFeatureCollection resultFeatureList = new CoverageToFeatureCollection(reader, gridGeom.getExtent(), coverage, gridGeom);
        outputParameters.getOrCreate(CoverageToFeaturesDescriptor.FEATURE_OUT).setValue(resultFeatureList);
    } catch (DataStoreException ex) {
        throw new ProcessException(ex.getMessage(), this, ex);
    }
}
Also used : GridGeometry(org.apache.sis.coverage.grid.GridGeometry) DataStoreException(org.apache.sis.storage.DataStoreException) ProcessException(org.geotoolkit.process.ProcessException) GridCoverage(org.apache.sis.coverage.grid.GridCoverage) GridCoverageResource(org.apache.sis.storage.GridCoverageResource)

Example 20 with ProcessException

use of org.geotoolkit.process.ProcessException in project geotoolkit by Geomatys.

the class LandsatResource method readGridSlice.

@Override
protected GridCoverage readGridSlice(GridGeometry resultGrid, int[] areaLower, int[] areaUpper, int[] subsampling, int... range) throws DataStoreException {
    GridGeometry geometry = getGridGeometry(getGridGeometry(), areaLower, areaUpper, subsampling);
    // -- get all needed band to build coverage (see Landsat spec)
    final int[] bandId = group.bands;
    final RenderedImage[] bands = new RenderedImage[bandId.length];
    try {
        int currentCov = 0;
        for (int i : bandId) {
            // -- get band name
            final String bandName = metadataParser.getValue(true, BAND_NAME_LABEL + i);
            // -- add to coverage name
            final Path band = parentDirectory.resolve(bandName);
            // -- reader config
            final TiffImageReader tiffReader = (TiffImageReader) TIFF_SPI.createReaderInstance();
            tiffReader.setInput(band);
            Rectangle rec = new Rectangle(areaLower[0], areaLower[1], areaUpper[0] - areaLower[0], areaUpper[1] - areaLower[1]);
            final ImageReadParam readParam = tiffReader.getDefaultReadParam();
            readParam.setSourceRegion(rec);
            readParam.setSourceSubsampling(subsampling[0], subsampling[1], 0, 0);
            try {
                BufferedImage read = tiffReader.read(0, readParam);
                bands[currentCov++] = read;
            } finally {
                tiffReader.dispose();
            }
        }
        final ProcessDescriptor desc = ProcessFinder.getProcessDescriptor("geotoolkit", "image:bandcombine");
        final ParameterValueGroup params = desc.getInputDescriptor().createValue();
        params.parameter("images").setValue(bands);
        final org.geotoolkit.process.Process process = desc.createProcess(params);
        final ParameterValueGroup result = process.call();
        final RenderedImage outImage = (RenderedImage) result.parameter("result").getValue();
        final GridCoverageBuilder gcb = new GridCoverageBuilder();
        gcb.setValues(outImage);
        gcb.setDomain(geometry);
        return gcb.build();
    } catch (IOException | NoSuchIdentifierException | ProcessException ex) {
        throw new DataStoreException(ex.getMessage(), ex);
    }
}
Also used : Path(java.nio.file.Path) GridGeometry(org.apache.sis.coverage.grid.GridGeometry) DataStoreException(org.apache.sis.storage.DataStoreException) ParameterValueGroup(org.opengis.parameter.ParameterValueGroup) Rectangle(java.awt.Rectangle) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) ImageReadParam(javax.imageio.ImageReadParam) ProcessException(org.geotoolkit.process.ProcessException) GridCoverageBuilder(org.apache.sis.coverage.grid.GridCoverageBuilder) NoSuchIdentifierException(org.opengis.util.NoSuchIdentifierException) ProcessDescriptor(org.geotoolkit.process.ProcessDescriptor) RenderedImage(java.awt.image.RenderedImage) TiffImageReader(org.geotoolkit.image.io.plugin.TiffImageReader)

Aggregations

ProcessException (org.geotoolkit.process.ProcessException)70 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)27 Geometry (org.locationtech.jts.geom.Geometry)26 FactoryException (org.opengis.util.FactoryException)24 TransformException (org.opengis.referencing.operation.TransformException)21 RenderedImage (java.awt.image.RenderedImage)15 DataStoreException (org.apache.sis.storage.DataStoreException)13 IOException (java.io.IOException)12 GridCoverage (org.apache.sis.coverage.grid.GridCoverage)12 GridGeometry (org.apache.sis.coverage.grid.GridGeometry)11 ProcessDescriptor (org.geotoolkit.process.ProcessDescriptor)11 ParameterValueGroup (org.opengis.parameter.ParameterValueGroup)11 BufferedImage (java.awt.image.BufferedImage)10 ArrayList (java.util.ArrayList)10 PixelIterator (org.apache.sis.image.PixelIterator)9 List (java.util.List)8 Parameters (org.apache.sis.parameter.Parameters)8 DismissProcessException (org.geotoolkit.process.DismissProcessException)8 WritablePixelIterator (org.apache.sis.image.WritablePixelIterator)7 GridCoverageResource (org.apache.sis.storage.GridCoverageResource)7