This is an automated email from the ASF dual-hosted git repository. asf-gitbox-commits pushed a commit to branch geoapi-4.0 in repository https://gitbox.apache.org/repos/asf/sis.git
commit 3c7ca622e05ce4c2fbe900583efd2eb8c06c34ec Author: Martin Desruisseaux <[email protected]> AuthorDate: Tue Nov 17 01:29:11 2026 +0100 Add `ImageProcessor.aggregate(...) methods`. --- .../coverage/MismatchedCoverageRangeException.java | 5 +- .../sis/coverage/grid/AggregatedGridCoverage.java | 180 +++++++++++++++++++ .../sis/coverage/grid/GridCoverageBuilder.java | 28 ++- .../sis/coverage/grid/GridCoverageProcessor.java | 193 +++++++++++++++++---- .../org/apache/sis/coverage/grid/GridExtent.java | 38 +++- .../org/apache/sis/coverage/grid/GridGeometry.java | 42 +++-- .../main/org/apache/sis/image/AggregatedImage.java | 23 ++- .../main/org/apache/sis/image/DataType.java | 4 +- .../main/org/apache/sis/image/ImageProcessor.java | 2 + .../test/org/apache/sis/image/DataTypeTest.java | 16 ++ .../iso/extent/DefaultGeographicBoundingBox.java | 4 +- 11 files changed, 449 insertions(+), 86 deletions(-) diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/MismatchedCoverageRangeException.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/MismatchedCoverageRangeException.java index e33a20db49..60fa97066a 100644 --- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/MismatchedCoverageRangeException.java +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/MismatchedCoverageRangeException.java @@ -18,8 +18,9 @@ package org.apache.sis.coverage; /** - * Thrown when the number of bands or sample dimensions specified to a method - * is not equal to the number expected by a coverage. + * Thrown when the bands or sample dimensions given to a method do not match the expectations. + * It may be because an illegal number of sample dimensions have been given, + * or because the sample dimensions of two grid coverages are not the same. * * @author Martin Desruisseaux (Geomatys) * @version 1.0 diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/AggregatedGridCoverage.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/AggregatedGridCoverage.java new file mode 100644 index 0000000000..7f68c4c9b9 --- /dev/null +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/AggregatedGridCoverage.java @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.sis.coverage.grid; + +import java.util.List; +import java.awt.Rectangle; +import java.awt.image.RenderedImage; +import org.opengis.util.FactoryException; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.operation.TransformException; +import org.opengis.referencing.operation.MathTransform; +import org.opengis.referencing.operation.Matrix; +import org.apache.sis.coverage.MismatchedCoverageRangeException; +import org.apache.sis.coverage.SampleDimension; +import org.apache.sis.image.AggregatedImage; +import org.apache.sis.image.ImageProcessor; +import org.apache.sis.image.internal.shared.ImageUtilities; +import org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox; +import org.apache.sis.referencing.CRS; +import org.apache.sis.referencing.operation.transform.MathTransforms; + + +/** + * A grid coverage which is the aggregation of data from other grid coverages. + * Current implementation supports only the two-dimensional case returned as {@link GridCoverage2D}. + * This class is added as a place-holder for a future version supporting the multi-dimensional case. + * + * @author Martin Desruisseaux (Geomatys) + */ +final class AggregatedGridCoverage { + /** + * Do not allow instantiation of this class (for now). + */ + private AggregatedGridCoverage() { + } + + /** + * Implementation of {@link GridCoverageProcessor#aggregate(GridCoverage, GridGeometry)}. + * This method computes transform from <var>Source Grid</var> to <var>Target Grid</var>. + * If the target {@link GridGeometry} is incomplete, this method provides default values + * for the missing properties. + * + * @param sources the grid coverages to aggregates. + * @param target the desired geometry of returned grid coverage. May be incomplete. + * @param processor the processor to use for executing the aggregation of images. + * @return a grid coverage with the characteristics specified in the given grid geometry. + * @throws IncompleteGridGeometryException if the source grid geometry is missing an information. + * @throws TransformException if some coordinates cannot be transformed to the specified target. + * + * @todo Current implementation always returns {@link GridCoverage2D} because multi-dimensional + * aggregation is not yet supported. + */ + static GridCoverage create(final GridCoverage[] sources, GridGeometry target, ImageProcessor processor) + throws TransformException, FactoryException + { + // The template is used only for its sample dimensions. + GridCoverage template = sources[0]; + for (int i=1; i<sources.length; i++) { + final GridCoverage c = sources[i]; + final List<SampleDimension> sd2 = c.getSampleDimensions(); + final List<SampleDimension> sd1 = template.getSampleDimensions(); + final int n = Math.min(sd1.size(), sd2.size()); + if (!sd1.subList(0, n).equals(sd2.subList(0, n))) { + throw new MismatchedCoverageRangeException(); + } + if (sd2.size() > sd1.size()) { + template = c; + } + } + /* + * If the target grid geometry does not specify a CRS, try to find a good choice for the CRSs of all sources. + * This search computes the union of all geographic bounding boxes as a side effect, because the search for a + * CRS depends on the area of interest. + */ + boolean modified = false; + final CoordinateReferenceSystem crs; + if (target.isDefined(GridGeometry.CRS)) { + crs = target.getCoordinateReferenceSystem(); + } else { + final var area = new DefaultGeographicBoundingBox(); + final var all = new CoordinateReferenceSystem[sources.length]; + for (int i=0; i<sources.length; i++) { + final GridGeometry c = sources[i].getGridGeometry(); + if (c.isDefined(GridGeometry.CRS)) { + all[i] = c.getCoordinateReferenceSystem(); + } + c.getGeographicExtent().ifPresent((box) -> { + if (area.isEmpty()) area.setBounds(box); + else area.add(box); + }); + } + crs = CRS.suggestCommonTarget(area.isEmpty() ? null : area, all); + modified = true; + } + /* + * If the target grid geometry does not specify a "grid to CRS" transform, + * search for a linear approximation of the grid with coarsest resolution. + */ + MathTransform gridToCRS = null; + if (!target.isDefined(GridGeometry.GRID_TO_CRS)) { + double max = 0; + for (int i=0; i<sources.length; i++) { + final GridGeometry c = sources[i].getGridGeometry(); + if (crs != null && c.isDefined(GridGeometry.CRS | GridGeometry.GRID_TO_CRS)) { + MathTransform linear = MathTransforms.concatenate( + c.getGridToCRS(PixelInCell.CELL_CORNER), + c.createChangeOfCRS(crs).getMathTransform()); + Matrix matrix = MathTransforms.getMatrix(linear); + if (matrix == null) { + // Transform is not linear, try to get an approximation. + if (!c.isDefined(GridGeometry.EXTENT)) continue; + linear = c.getExtent().tangentAtPOI(linear, PixelInCell.CELL_CORNER); + matrix = MathTransforms.getMatrix(linear); + } + double sum =0; + for (int y = matrix.getNumRow() - 1; --y >= 0;) { // Skip last row. + for (int x = matrix.getNumCol() - 1; --x >= 0;) { // Skip last column. + double v = matrix.getElement(y, x); + if (Double.isFinite(v)) sum += v*v; + } + } + if (sum > max) { + max = sum; + gridToCRS = linear; + modified = true; + } + } + } + } + if (gridToCRS == null) { + // Fallback, intentional `IncompleteGridGeometryException` if not defined. + gridToCRS = target.getGridToCRS(PixelInCell.CELL_CORNER); + } + /* + * Get the image bounds from the extent. If none, we will let `AggregatedImage` + * compute and extent itself and use its result for a new `GridGeometry`. + */ + GridExtent extent = null; + Rectangle bounds = null; + if (target.isDefined(GridGeometry.EXTENT)) { + extent = target.getExtent(); + bounds = extent.toRectangle(true); + } + if (modified) { + target = new GridGeometry(extent, PixelInCell.CELL_CORNER, gridToCRS, crs); + } + /* + * Build the list of source images, execute the aggregation, then wraps the result. + */ + final var images = new AggregatedImage.Source[sources.length]; + for (int i=0; i<sources.length; i++) { + final GridCoverage c = sources[i]; + final MathTransform tr = c.getGridGeometry().createTransformTo(target, PixelInCell.CELL_CORNER); + images[i] = new AggregatedImage.Source(c.render(null), tr); + } + processor = processor.clone(); + processor.setFillValues(template.getBackground()); + final RenderedImage image = processor.aggregate(bounds, images); + if (extent == null) { + bounds = ImageUtilities.getBounds(image); + extent = new GridExtent(bounds); + target = new GridGeometry(extent, PixelInCell.CELL_CORNER, gridToCRS, crs); + } + return new GridCoverage2D(template, target, extent, image); + } +} diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageBuilder.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageBuilder.java index ef0cde8b41..b4d64cbe22 100644 --- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageBuilder.java +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageBuilder.java @@ -615,35 +615,27 @@ public class GridCoverageBuilder { * @return an image computed from the {@link #calcAsDoubles} or {@link #calcAsIntegers} function. */ private RenderedImage computeImage(final GridGeometry grid, final List<? extends SampleDimension> bands, final int numBands) { - final int xmin, ymin, width, height, tileWidth, tileHeight; - if (imageBounds != null) { - xmin = imageBounds.x; - ymin = imageBounds.y; - width = imageBounds.width; - height = imageBounds.height; - } else { - final GridExtent extent = grid.getExtent(); - final int[] imageAxes = extent.getSubspaceDimensions(GridCoverage.BIDIMENSIONAL); - xmin = Math.toIntExact(extent.getLow (imageAxes[0])); - ymin = Math.toIntExact(extent.getLow (imageAxes[1])); - width = Math.toIntExact(extent.getSize(imageAxes[0])); - height = Math.toIntExact(extent.getSize(imageAxes[1])); + Rectangle bounds = imageBounds; + if (bounds == null) { + bounds = grid.getExtent().toRectangle(false); } Dimension tiling = tileSize; if (tiling == null) { - tiling = ImageLayout.DEFAULT.allowPartialTiles(false).suggestTileSize(width, height); + tiling = ImageLayout.DEFAULT.allowPartialTiles(false).suggestTileSize(bounds.width, bounds.height); } - final int numXTiles = JDK18.ceilDiv(width, tileWidth = tiling.width); - final int numYTiles = JDK18.ceilDiv(height, tileHeight = tiling.height); + final int tileWidth, tileHeight; + final int numXTiles = JDK18.ceilDiv(bounds.width, tileWidth = tiling.width); + final int numYTiles = JDK18.ceilDiv(bounds.height, tileHeight = tiling.height); final var sm = new BandedSampleModel(dataType.toDataBufferType(), tileWidth, tileHeight, numBands); final var location = new Point(); final var tiles = new WritableRaster[Math.multiplyExact(numXTiles, numYTiles)]; + final int xmin = bounds.x; + final int ymin = bounds.y; for (int i=0; i<tiles.length; i++) { location.x = xmin + (i % numXTiles) * tileWidth; location.y = ymin + (i / numXTiles) * tileHeight; tiles[i] = WritableRaster.createWritableRaster(sm, location); } - final var bounds = new Rectangle(xmin, ymin, width, height); final var data = (WritableRenderedImage) createImage(sm, bands, bounds, tiles); final WritablePixelIterator i = WritablePixelIterator.create(data); if (calcAsDoubles != null) { @@ -763,7 +755,7 @@ public class GridCoverageBuilder { */ private static void verifyGridExtent(final GridExtent extent, final int... expectedSize) { final int[] imageAxes = extent.getSubspaceDimensions(expectedSize.length); - for (int i=0; i<expectedSize.length; i++) { + for (int i=0; i < expectedSize.length; i++) { final int imageSize = expectedSize[i]; final long gridSize = extent.getSize(imageAxes[i]); if (imageSize != gridSize) { diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageProcessor.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageProcessor.java index f5ee1197ad..da20566246 100644 --- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageProcessor.java +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridCoverageProcessor.java @@ -29,6 +29,7 @@ import java.lang.reflect.InaccessibleObjectException; import java.awt.Shape; import java.awt.Rectangle; import java.awt.image.RenderedImage; +import java.awt.image.WritableRenderedImage; import javax.measure.Quantity; import org.opengis.util.FactoryException; import org.opengis.metadata.spatial.DimensionNameType; @@ -45,6 +46,7 @@ import org.apache.sis.image.DataType; import org.apache.sis.image.Colorizer; import org.apache.sis.image.PlanarImage; import org.apache.sis.image.ImageProcessor; +import org.apache.sis.image.Aggregation; import org.apache.sis.image.Interpolation; import org.apache.sis.coverage.internal.shared.SampleDimensions; import org.apache.sis.coverage.internal.shared.BandAggregateArgument; @@ -85,7 +87,7 @@ import org.apache.sis.measure.NumberRange; * * @author Martin Desruisseaux (Geomatys) * @author Alexis Manin (Geomatys) - * @version 1.5 + * @version 1.8 * * @see org.apache.sis.image.ImageProcessor * @@ -162,6 +164,7 @@ public class GridCoverageProcessor implements Cloneable { * @return interpolation method to use in resampling operations. * * @see ImageProcessor#getInterpolation() + * @see #resample(GridCoverage, CoordinateReferenceSystem) */ public Interpolation getInterpolation() { return imageProcessor.getInterpolation(); @@ -179,6 +182,35 @@ public class GridCoverageProcessor implements Cloneable { imageProcessor.setInterpolation(method); } + /** + * Returns the aggregation method to use for aggregating operations. + * The default implementation delegates to the image processor. + * + * @return aggregation method to use in aggregating operations. + * + * @see ImageProcessor#getAggregation() + * @see #aggregate(GridCoverage, CoordinateReferenceSystem) + * + * @since SIS 1.8 + */ + public Aggregation getAggregation() { + return imageProcessor.getAggregation(); + } + + /** + * Sets the aggregation method to use for aggregating operations. + * The default implementation delegates to the image processor. + * + * @param method aggregation method to use in aggregating operations. + * + * @see ImageProcessor#setAggregation(Aggregation) + * + * @since SIS 1.8 + */ + public void setAggregation(final Aggregation method) { + imageProcessor.setAggregation(method); + } + /** * Returns the values to use for pixels that cannot be computed. * The default implementation delegates to the image processor. @@ -356,8 +388,7 @@ public class GridCoverageProcessor implements Cloneable { * If {@code maskInside} is {@code false}, then the mask is reversed: * the pixels set to fill values are the ones outside the ROI. * - * <h4>Properties used</h4> - * This operation uses the following properties in addition to method parameters: + * <p>This operation uses the following properties in addition to method parameters:</p> * <ul> * <li>{@linkplain #getFillValues() Fill values} values to assign to pixels inside/outside the region of interest.</li> * </ul> @@ -390,7 +421,7 @@ public class GridCoverageProcessor implements Cloneable { * If the {@code converters} array length is less than the number of source sample dimensions, * then all sample dimensions at index ≥ {@code converters.length} will be ignored. * - * <h4>Sample dimensions customization</h4> + * <h4>Customizing the result of sample dimension conversions</h4> * By default, this method creates new sample dimensions with the same names and categories than in the * previous coverage, but with {@linkplain org.apache.sis.coverage.Category#getSampleRange() sample ranges} * converted using the given converters and with {@linkplain SampleDimension#getUnits() units of measurement} @@ -399,16 +430,15 @@ public class GridCoverageProcessor implements Cloneable { * The {@code sampleDimensionModifier} function can {@linkplain SampleDimension.Builder#setName(CharSequence) * change the sample dimension name} or {@linkplain SampleDimension.Builder#categories() rebuild the categories}. * - * <h4>Result relationship with source</h4> - * If the source coverage is backed by a {@link java.awt.image.WritableRenderedImage}, - * then changes in the source coverage are reflected in the returned coverage and conversely. - * - * <h4>Properties used</h4> - * This operation uses the following properties in addition to method parameters: + * <p>This operation uses the following properties in addition to method parameters:</p> * <ul> * <li>{@linkplain #getColorizer() Colorizer} for customizing the rendered image color model.</li> * </ul> * + * <p><b>Result relationship with source:</b> + * If the source coverage is backed by a {@link WritableRenderedImage} or {@link PlanarImage}, + * then changes in the source coverage are reflected in the returned coverage and conversely.</p> + * * @param source the coverage for which to convert sample values. * @param converters the transfer functions to apply on each sample dimension of the source coverage. * @param sampleDimensionModifier a callback for modifying the {@link SampleDimension.Builder} default @@ -426,8 +456,8 @@ public class GridCoverageProcessor implements Cloneable { ArgumentChecks.ensureNonNull("converters", converters); final List<SampleDimension> sourceBands = source.getSampleDimensions(); ArgumentChecks.ensureCountBetween("converters", true, 1, sourceBands.size(), converters.length); - final SampleDimension[] targetBands = new SampleDimension[converters.length]; - final SampleDimension.Builder builder = new SampleDimension.Builder(); + final var targetBands = new SampleDimension[converters.length]; + final var builder = new SampleDimension.Builder(); if (sampleDimensionModifier == null) { sampleDimensionModifier = SampleDimension.Builder::build; } @@ -469,8 +499,7 @@ public class GridCoverageProcessor implements Cloneable { * of this {@code translate(…)} method into a single translation.</li> * </ul> * - * <h4>Properties used</h4> - * This operation uses the following properties in addition to method parameters: + * <p>This operation uses the following properties in addition to method parameters:</p> * <ul> * <li>(none)</li> * </ul> @@ -561,8 +590,7 @@ public class GridCoverageProcessor implements Cloneable { * by {@code translate(…)} when possible.</li> * </ul> * - * <h4>Properties used</h4> - * This operation uses the following properties in addition to method parameters: + * <p>This operation uses the following properties in addition to method parameters:</p> * <ul> * <li>{@linkplain #getInterpolation() Interpolation method} (nearest neighbor, bilinear, <i>etc</i>).</li> * <li>{@linkplain #getFillValues() Fill values} for pixels outside source image.</li> @@ -574,7 +602,7 @@ public class GridCoverageProcessor implements Cloneable { * @param target the desired geometry of returned grid coverage. May be incomplete. * @return a grid coverage with the characteristics specified in the given grid geometry. * @throws IncompleteGridGeometryException if the source grid geometry is missing an information. - * It may be the source CRS, the source extent, <i>etc.</i> depending on context. + * It may be the source <abbr>CRS</abbr>, the source extent, <i>etc.</i> depending on context. * @throws TransformException if some coordinates cannot be transformed to the specified target. * * @see ImageProcessor#resample(RenderedImage, Rectangle, MathTransform) @@ -587,7 +615,7 @@ public class GridCoverageProcessor implements Cloneable { allowSourceReplacement = optimizations.contains(Optimization.REPLACE_SOURCE); allowOperationReplacement = optimizations.contains(Optimization.REPLACE_OPERATION); } - final boolean isConverted = source == source.forConvertedValues(true); + final boolean isConverted = (source == source.forConvertedValues(true)); /* * If the source coverage is already the result of a previous "resample" or "translate" operation, * use the original data in order to avoid interpolating values that are already interpolated. @@ -596,7 +624,7 @@ public class GridCoverageProcessor implements Cloneable { if (ResampledGridCoverage.equivalent(source.getGridGeometry(), target)) { return source; } else if (allowSourceReplacement && source instanceof DerivedGridCoverage) { - final DerivedGridCoverage derived = (DerivedGridCoverage) source; + final var derived = (DerivedGridCoverage) source; if (derived.isNotRepleacable()) break; source = derived.source; } else { @@ -618,12 +646,8 @@ public class GridCoverageProcessor implements Cloneable { // `ResampledGridCoverage` will create itself a clone of `imageProcessor`. resampled = ResampledGridCoverage.create(source, target, imageProcessor, allowOperationReplacement); } catch (IllegalGridGeometryException e) { - final Throwable cause = e.getCause(); - if (cause instanceof TransformException) { - throw (TransformException) cause; - } else { - throw e; - } + rethrowIfTransformException(e.getCause()); + throw e; } catch (FactoryException e) { throw new TransformFactoryException(e); } @@ -645,6 +669,8 @@ public class GridCoverageProcessor implements Cloneable { * @throws IncompleteGridGeometryException if the source grid geometry is missing an information. * @throws TransformException if some coordinates cannot be transformed to the specified target. * + * @see #aggregate(GridCoverage, CoordinateReferenceSystem) + * * @since SIS 1.3 */ public GridCoverage resample(final GridCoverage source, final CoordinateReferenceSystem target) throws TransformException { @@ -653,6 +679,104 @@ public class GridCoverageProcessor implements Cloneable { return resample(source, new GridGeometry(null, PixelInCell.CELL_CENTER, null, target)); } + /** + * Creates a new coverage with aggregated values of one or many source grid coverages. + * The desired properties are specified by the {@link GridGeometry} argument, which may be incomplete. + * The missing grid geometry components are completed as below: + * + * <table class="sis"> + * <caption>Default values for undefined grid geometry components</caption> + * <tr> + * <th>Component</th> + * <th>Default value</th> + * </tr><tr> + * <td>{@linkplain GridGeometry#getExtent() Grid extent}</td> + * <td>A default size preserving resolution at source + * {@linkplain GridExtent#getPointOfInterest(PixelInCell) point of interest}.</td> + * </tr><tr> + * <td>{@linkplain GridGeometry#getGridToCRS Grid to CRS transform}</td> + * <td>Whatever it takes for fitting data inside the supplied extent.</td> + * </tr><tr> + * <td>{@linkplain GridGeometry#getCoordinateReferenceSystem() Coordinate reference system}</td> + * <td>Same as source coverage.</td> + * </tr> + * </table> + * + * <p>This operation uses the following properties in addition to method parameters:</p> + * <ul> + * <li>{@linkplain #getAggregation() Aggregation method} (weighted average, <i>etc</i>).</li> + * <li>{@linkplain #getFillValues() Fill values} for sample values not covered by a source.</li> + * <li>{@linkplain #getPositionalAccuracyHints() Positional accuracy hints} + * for enabling faster aggregation at the cost of lower precision.</li> + * </ul> + * + * <p><b>Performance note:</b> + * Contrary to {@code resample(…)}, this operation computes all tiles immediately when one tile is requested. + * For very large images, {@link #resample(GridCoverage, GridGeometry) resample(…)} is preferred because it + * defers computation on a tile-by-tile basis instead of computing the whole image.</p> + * + * @param target the desired geometry of returned grid coverage. May be incomplete. + * @param sources the grid coverages to aggregate. + * @return a grid coverage with the characteristics specified in the given grid geometry. + * @throws IncompleteGridGeometryException if the source grid geometry is missing an information. + * It may be the source <abbr>CRS</abbr>, the source extent, <i>etc.</i> depending on context. + * @throws TransformException if some coordinates cannot be transformed to the specified target. + * + * @see ImageProcessor#aggregate(RenderedImage, Rectangle, MathTransform) + * + * @since SIS 1.8 + */ + public GridCoverage aggregate(final GridGeometry target, GridCoverage... sources) throws TransformException { + ArgumentChecks.ensureNonNull ("target", target); + ArgumentChecks.ensureNonEmpty("sources", sources); + sources = sources.clone(); + boolean isConverted = false; + for (int i=0; i<sources.length; i++) { + final GridCoverage source = sources[i]; + ArgumentChecks.ensureNonNullElement("sources", i, source); + isConverted |= (source == (sources[i] = source.forConvertedValues(true))); + } + final GridCoverage aggregated; + try { + // `AggregatedGridCoverage` will create itself a clone of `imageProcessor`. + aggregated = AggregatedGridCoverage.create(sources, target, imageProcessor); + } catch (IllegalGridGeometryException e) { + rethrowIfTransformException(e.getCause()); + throw e; + } catch (FactoryException e) { + throw new TransformFactoryException(e); + } + return aggregated.forConvertedValues(isConverted); + } + + /** + * Creates a new coverage with values aggregated in a different coordinate reference system. + * The grid extent and "grid to CRS" transform are determined automatically + * with default values preserving the resolution of source coverage at its + * {@linkplain GridExtent#getPointOfInterest(PixelInCell) point of interest}. + * + * <p>This method is an alternative to {@link #resample(GridCoverage, CoordinateReferenceSystem)} + * which uses the {@link MathTransform} in the opposite direction. + * This method may succeed when {@code resample(…)} fails if the transform is difficult to inverse. + * However, this operation may be slower and consume more memory for a less smooth result. + * See {@link #aggregate(GridGeometry, GridCoverage...)} for more information about aggregations.</p> + * + * @param source the grid coverage to aggregate. + * @param target the desired coordinate reference system. + * @return a grid coverage with the given coordinate reference system. + * @throws IncompleteGridGeometryException if the source grid geometry is missing an information. + * @throws TransformException if some coordinates cannot be transformed to the specified target. + * + * @see #resample(GridCoverage, CoordinateReferenceSystem) + * + * @since SIS 1.8 + */ + public GridCoverage aggregate(final GridCoverage source, final CoordinateReferenceSystem target) throws TransformException { + ArgumentChecks.ensureNonNull("source", source); + ArgumentChecks.ensureNonNull("target", target); + return aggregate(new GridGeometry(null, PixelInCell.CELL_CORNER, null, target), source); + } + /** * Appends the specified grid dimensions after the dimensions of the given source coverage. * This method is typically invoked for adding a vertical or temporal axis to a two-dimensional coverage. @@ -700,9 +824,9 @@ public class GridCoverageProcessor implements Cloneable { * It also has the desirable side-effect to increase the chances that slices share the same * "grid to CRS" transform. */ - final long index = Numerics.roundAndClamp(lower / span); - final long[] indices = new long[] {index}; - final GridExtent extent = new GridExtent(GridExtent.typeFromAxes(crs, 1), indices, indices, true); + final long index = Numerics.roundAndClamp(lower / span); + final var indices = new long[] {index}; + final var extent = new GridExtent(GridExtent.typeFromAxes(crs, 1), indices, indices, true); final MathTransform gridToCRS = MathTransforms.linear(span, Math.fma(index, -span, lower)); return appendDimensions(source, new GridGeometry(extent, PixelInCell.CELL_CORNER, gridToCRS, crs)); } @@ -947,8 +1071,7 @@ public class GridCoverageProcessor implements Cloneable { * RenderedImage visualization = processor.visualize(source, slice); * } * - * <h4>Properties used</h4> - * This operation uses the following properties in addition to method parameters: + * <p>This operation uses the following properties in addition to method parameters:</p> * <ul> * <li>{@linkplain #getColorizer() Colorizer} for customizing the rendered image color model.</li> * </ul> @@ -975,6 +1098,16 @@ public class GridCoverageProcessor implements Cloneable { } } + /** + * Retrows the given exception if it is an instance of {@link TransformException}. + * This is used for unwrapping unchecked exception used as wrapper for a checked exception. + */ + private static void rethrowIfTransformException(final Throwable cause) throws TransformException { + if (cause instanceof TransformException) { + throw (TransformException) cause; + } + } + /** * Invoked when an ignorable exception occurred. * diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridExtent.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridExtent.java index 1e4dad52fd..44e4676e01 100644 --- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridExtent.java +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridExtent.java @@ -1042,6 +1042,18 @@ public class GridExtent implements GridEnvelope, LenientComparable, Serializable return gridToCRS.derivative(new DirectPositionView.Double(getPointOfInterest(anchor))); } + /** + * Returns the tangent of the given transform at the point of interest. + * + * @param gridToCRS the transform for which to take the tangent. + * @param anchor the convention to be used for conversion to "real world" coordinates. + * @return tangent of the given transform at the point of interest. + * @throws TransformException if the tangent cannot be computed. + */ + final LinearTransform tangentAtPOI(final MathTransform gridToCRS, final PixelInCell anchor) throws TransformException { + return MathTransforms.tangent(gridToCRS, new DirectPositionView.Double(getPointOfInterest(anchor))); + } + /** * Returns the grid coordinates for all dimensions where the grid has a size of 1. * Keys are dimensions as values from 0 inclusive to {@link #getDimension()} exclusive. @@ -1107,7 +1119,7 @@ public class GridExtent implements GridEnvelope, LenientComparable, Serializable * @param numDim number of dimensions of the sub-space. * @return indices of sub-space dimensions, in increasing order in an array of length {@code numDim}. * @throws SubspaceNotSpecifiedException if there is more than {@code numDim} dimensions having a size greater than 1. - * @throws CannotEvaluateException if this grid extent does not have at least {@code numDim} dimensions. + * @throws CannotEvaluateException if this grid extent has less than {@code numDim} dimensions. * * @see #getDegreesOfFreedom() */ @@ -1301,6 +1313,30 @@ public class GridExtent implements GridEnvelope, LenientComparable, Serializable return copy; } + /** + * Returns this extent as a rectangle. If this extent has more than two dimensions, + * at most two of them can have a size greater than 1. + * + * @param atZero whether to force the rectangle to start at (0, 0). + * @return a rectangle initialized with this extent in two dimensions. + * @throws SubspaceNotSpecifiedException if there is more than 2 dimensions having a size greater than 1. + * @throws CannotEvaluateException if this grid extent has less than 2 dimensions. + * @throws ArithmeticException if the two-dimensional extent cannot be represented by 32-bits integers. + * + * @since SIS 1.8 + */ + public Rectangle toRectangle(final boolean atZero) { + final int[] selected = getSubspaceDimensions(GridCoverage.BIDIMENSIONAL); + final var bounds = new Rectangle( + Math.toIntExact(getSize(selected[0])), + Math.toIntExact(getSize(selected[1]))); + if (!atZero) { + bounds.x = Math.toIntExact(getLow(selected[0])); + bounds.x = Math.toIntExact(getLow(selected[1])); + } + return bounds; + } + /** * Transforms this grid extent to a "real world" envelope using the given transform. * The given transform shall map <em>cell corners</em> to real world coordinates. diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridGeometry.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridGeometry.java index 5715e1cc1f..8b1c950242 100644 --- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridGeometry.java +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/GridGeometry.java @@ -67,7 +67,6 @@ import org.apache.sis.referencing.operation.transform.PassThroughTransform; import org.apache.sis.referencing.operation.transform.TransformFactoryException; import org.apache.sis.referencing.factory.InvalidGeodeticParameterException; import org.apache.sis.referencing.internal.shared.ExtendedPrecisionMatrix; -import org.apache.sis.referencing.internal.shared.DirectPositionView; import org.apache.sis.referencing.internal.shared.TemporalAccessor; import org.apache.sis.referencing.internal.shared.AxisDirections; import org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox; @@ -460,10 +459,10 @@ public class GridGeometry implements LenientComparable, Serializable { * smallest values (closest to negative infinity).</li> * </ul> * - * <h4>API note</h4> + * <p><b><abbr>API</abbr> note:</b> * There is no default value for {@code anchor} because experience shows that images shifted by ½ pixel * (with pixels that may be tens of kilometres large) is a recurrent problem. We want to encourage developers - * to always think about wether their <i>grid to CRS</i> transform is mapping pixel corner or center. + * to always think about wether their <i>grid to CRS</i> transform is mapping pixel corner or center.</p> * * <div class="warning"><b>Upcoming API generalization:</b> * the {@code extent} type of this method may be changed to {@code GridEnvelope} interface in a future Apache SIS version. @@ -645,10 +644,10 @@ public class GridGeometry implements LenientComparable, Serializable { * For grid geometries describing preexisting data, it is safer and more flexible to use one of * the constructors expecting a {@link MathTransform} argument.</p> * - * <h4>Dimension order</h4> + * <p><b>Dimension order:</b> * The given envelope shall always declare dimensions in same order as the given extent. * This constructor may reorder axes if {@code orientation} is {@link GridOrientation#DISPLAY}, - * but in such case this constructor will derive a new envelope and a new CRS from the given envelope. + * but in such case this constructor will derive a new envelope and a new CRS from the given envelope.</p> * * @param extent the valid extent of grid coordinates, or {@code null} if unknown. * @param envelope the envelope together with CRS of the "real world" coordinates, or {@code null} if unknown. @@ -961,10 +960,10 @@ public class GridGeometry implements LenientComparable, Serializable { * with inclusive lower coordinates and <strong>exclusive</strong> upper coordinates.</li> * </ul> * - * <h4>API note</h4> + * <p><b><abbr>API</abbr> note:</b> * There is no default value for {@code anchor} because experience shows that images shifted by ½ pixel * (with pixels that may be tens of kilometres large) is a recurrent problem. We want to encourage developers - * to always think about wether the desired <i>grid to CRS</i> transform shall map pixel corner or center. + * to always think about wether the desired <i>grid to CRS</i> transform shall map pixel corner or center.</p> * * @param anchor the cell part to map (center or corner). * @return the conversion from grid coordinates to "real world" coordinates (never {@code null}). @@ -1005,8 +1004,7 @@ public class GridGeometry implements LenientComparable, Serializable { if (tr instanceof LinearTransform) { return (LinearTransform) tr; } - return MathTransforms.linear(MathTransforms.getMatrix(tr, - new DirectPositionView.Double(getExtent().getPointOfInterest(anchor)))); + return getExtent().tangentAtPOI(tr, anchor); } /* @@ -1146,10 +1144,10 @@ public class GridGeometry implements LenientComparable, Serializable { * This is computed from the {@linkplain #getEnvelope() envelope} if the coordinate reference system * contains an horizontal component such as a geographic or projected CRS. * - * <h4>API note</h4> + * <p><b><abbr>API</abbr> note:</b> * This method does not throw {@link IncompleteGridGeometryException} because the geographic extent * may be absent even with a complete grid geometry. Grid geometries are not required to have a - * spatial component on Earth surface, since a raster could be a vertical profile for example. + * spatial component on Earth surface, since a raster could be a vertical profile for example.</p> * * @return the geographic bounding box in "real world" coordinates. */ @@ -1623,8 +1621,8 @@ public class GridGeometry implements LenientComparable, Serializable { * sets the {@linkplain GridExtent#getSize(int) grid size} to 1 in all dimensions specified by a <i>slice point</i>, * but does not remove those dimensions from the grid geometry. For dimensionality reduction, see {@link #selectDimensions(int[])}.</p> * - * <h4>Example</h4> - * For clipping this grid geometry to a sub-area, one can use: + * <p><b>Example:</b> + * For clipping this grid geometry to a sub-area, one can use:</p> * * {@snippet lang="java" : * GridGeometry gg = ...; @@ -1646,10 +1644,10 @@ public class GridGeometry implements LenientComparable, Serializable { * for compensating the grid change. * The grid geometry {@link #getEnvelope() envelope} is preserved after upsampling. * - * <h4>Number of arguments</h4> + * <p><b>Number of arguments:</b> * The {@code periods} array length should be equal to the {@linkplain #getDimension() number of grid dimensions}. * If the array is shorter, missing values default to 1 (i.e. samplings in unspecified dimensions are unchanged). - * If the array is longer, extraneous values are ignored. + * If the array is longer, extraneous values are ignored.</p> * * @param periods the upsampling factors for each dimension of this grid geometry. * @return the upsampled grid geometry, or {@code this} is upsampling results in the same extent. @@ -1709,10 +1707,10 @@ public class GridGeometry implements LenientComparable, Serializable { * The "grid to CRS" transforms are adjusted accordingly in order to map to the same * "real world" coordinates. * - * <h4>Number of arguments</h4> + * <p><b>Number of arguments:</b> * The {@code translation} array length should be equal to the {@linkplain #getDimension() number of dimensions}. * If the array is shorter, missing values default to 0 (i.e. no translation in unspecified dimensions). - * If the array is longer, extraneous values are ignored. + * If the array is longer, extraneous values are ignored.</p> * * @param translation translation to apply on each grid axis in order. * @return a grid geometry whose coordinates (both low and high ones) and @@ -1866,7 +1864,7 @@ public class GridGeometry implements LenientComparable, Serializable { * of the name given by the {@code datum} argument.</li> * </ul> * - * <h4>Usage in context of image pyramids</h4> + * <h4>Default grid <abbr>CRS</abbr> of image pyramids</h4> * The "grid to <abbr>CRS</abbr>" information is sometime missing, for example because a file * is an ordinary <abbr>TIFF</abbr> file instead of GeoTIFF, or because of encoding error. * Missing "grid to <abbr>CRS</abbr>" information usually causes missing grid resolution, @@ -1916,13 +1914,13 @@ public class GridGeometry implements LenientComparable, Serializable { * then this method creates an {@link org.opengis.referencing.crs.EngineeringCRS} instance * associated with an engineering datum identified by the given {@code name}. * - * <h4>Recommendation about the name</h4> + * <p><b>Recommendation about the name:</b> * The {@code name} argument is not very important when this method creates {@link DerivedCRS} instances, * because the datum is inherited from the real world <abbr>CRS</abbr>. However, if this method fallbacks * on {@link EngineeringCRS}, then the {@code name} argument become the only way to determine whether * a coordinate operation is possible between two such engineering <abbr>CRS</abbr>s. * It is recommended to use an identifier which is unique for the grid. It may be, for example, derived - * from the {@linkplain org.apache.sis.storage.GridCoverageResource#getIdentifier() resource identifier}. + * from the {@linkplain org.apache.sis.storage.GridCoverageResource#getIdentifier() resource identifier}.</p> * * <p><b>Alternative:</b> if the target grid geometry is known in advance, * {@link #createTransformTo(GridGeometry, PixelInCell)} can provide a @@ -2205,11 +2203,11 @@ public class GridGeometry implements LenientComparable, Serializable { * This method may conservatively return {@code false} if an accurate answer would be too expensive * (because of the last point in above list), or if the coordinates cannot be transformed. * - * <h4>Usage</h4> + * <p><b>Usage:</b> * This method behavior is well defined when the two grids are members of the same image mosaic or pyramid: * same <abbr>CRS</abbr> together with "grid to <abbr>CRS</abbr>" transforms that differ only by scale and * translation factors with integer values. - * For other cases, this method should be considered as merely a hint because of above approximations. + * For other cases, this method should be considered as merely a hint because of above approximations.</p> * * @param other the other grid geometry to test for inclusion. * @return whether the other grid geometry is contained in this grid geometry. diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java index f1e772fb8a..ec30889625 100644 --- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java @@ -742,6 +742,10 @@ images: while (imageIndex < upperImageIndex) { final MathTransform fromSource = sources[imageIndex].fromSource; final RenderedImage source = sources[imageIndex].source; final double[][] coordinates = new double[2][(source.getTileWidth() + 1) * BIDIMENSIONAL]; + final int srcMinX = source.getMinX(); + final int srcMinY = source.getMinY(); + final int srcMaxX = Math.addExact(srcMinX, source.getWidth()); + final int srcMaxY = Math.addExact(srcMinY, source.getHeight()); final int srcMinTileX = source.getMinTileX(); final int srcMinTileY = source.getMinTileY(); final int srcNumTileX = source.getNumXTiles(); @@ -770,19 +774,20 @@ images: while (imageIndex < upperImageIndex) { } } /* - * We will iterate over all pixels of a single tile of a source image. - * For each pixel, the coordinates of the 4 corners will be transformed - * to coordinates of a bounding box in the target image (conceptually, - * actual implementation tries to be more efficient). + * We will iterate over all pixels of a single tile of a source image, + * clipped to the image bounds because tiles in the last row and column + * may extend beyond the image. For each pixel, coordinates of 4 corners + * will be transformed to coordinates of a bounding box in target image + * (conceptually, actual implementation tries to be more efficient). */ final Raster tile = source.getTile(srcMinTileX + (srcTileIndex % srcNumTileX), srcMinTileY + (srcTileIndex / srcNumTileX)); final int numBands = Math.min(tile.getNumBands(), effectiveNumBands); - final int scanline = tile.getWidth() + 1; // +1 become xmax will be inclusive. - final int xmin = tile.getMinX(); - final int ymin = tile.getMinY(); - final int xmax = Math.addExact(xmin, scanline - 1); - final int ymax = Math.addExact(ymin, tile.getHeight()); + final int xmin = Math.max(srcMinX, tile.getMinX()); + final int ymin = Math.max(srcMinY, tile.getMinY()); + final int xmax = Math.min(srcMaxX, Math.addExact(tile.getMinX(), tile.getWidth())); + final int ymax = Math.min(srcMaxY, Math.addExact(tile.getMinY(), tile.getHeight())); + final int scanline = xmax - xmin + 1; // +1 because xmax will be inclusive. double[] xyBottom = coordinates[ymax & 1]; for (int i=0, x=xmin; x <= xmax; x++) { // Really the <= comparator. xyBottom[i++] = x; diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/DataType.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/DataType.java index bdfca9e9b7..25845966f9 100644 --- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/DataType.java +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/DataType.java @@ -38,7 +38,7 @@ import static org.apache.sis.util.internal.shared.Numerics.MAX_INTEGER_CONVERTIB * except that this enumeration distinguishes signed and unsigned 32 bits integers. * * @author Martin Desruisseaux (Geomatys) - * @version 1.5 + * @version 1.8 * * @see org.apache.sis.math.NumberType * @@ -214,7 +214,7 @@ public enum DataType { * If a bounds is NaN, fallback on TYPE_FLOAT. */ final DataType type; - if (min >= -0.5 && max < 0xFFFFFFFF + 0.5) { + if (min >= -0.5 && max < 0xFFFFFFFFL + 0.5) { type = (max < 0xFF + 0.5) ? BYTE : (max < 0xFFFF + 0.5) ? USHORT : UINT; } else if (min >= Short.MIN_VALUE - 0.5 && max < Short.MAX_VALUE + 0.5) { type = SHORT; diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java index 0081916b28..1aa2bf0dcb 100644 --- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java +++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java @@ -1328,6 +1328,8 @@ public class ImageProcessor implements Cloneable { * @param sources the images to aggregate with their transforms from <em>source</em> to <em>new</em> image. * @return aggregation of pixel values of all given source images. * + * @see GridCoverageProcessor#aggregate(GridGeometry, GridCoverage...) + * * @since SIS 1.8 */ @SuppressWarnings("LocalVariableHidesMemberVariable") diff --git a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/DataTypeTest.java b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/DataTypeTest.java index 73919a6edb..3b11f8d639 100644 --- a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/DataTypeTest.java +++ b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/DataTypeTest.java @@ -21,6 +21,7 @@ import java.awt.image.RasterFormatException; import java.awt.image.SampleModel; import java.awt.image.BandedSampleModel; import java.awt.image.SinglePixelPackedSampleModel; +import org.apache.sis.measure.NumberRange; // Test dependencies import org.junit.jupiter.api.Test; @@ -146,6 +147,21 @@ public final class DataTypeTest extends TestCase { assertMessageContains(e, "signed", "true"); } + /** + * Tests {@link DataType#forRange(NumberRange, boolean)}. + */ + @Test + public void testForRange() { + assertEquals(DataType.BYTE, DataType.forRange(NumberRange.create((short) 0, true, (short) 255, true), true)); + assertEquals(DataType.USHORT, DataType.forRange(NumberRange.create(0, true, 0xFFFF, true), true)); + assertEquals(DataType.UINT, DataType.forRange(NumberRange.create(0, true, 0x10000, true), true)); + assertEquals(DataType.SHORT, DataType.forRange(NumberRange.create(-1, true, 255, true), true)); + assertEquals(DataType.INT, DataType.forRange(NumberRange.create(-1, true, 0xFFFF, true), true)); + assertEquals(DataType.BYTE, DataType.forRange(NumberRange.create(0d, true, 255d, true), true)); + assertEquals(DataType.FLOAT, DataType.forRange(NumberRange.create(0f, true, 255f, true), false)); + assertEquals(DataType.DOUBLE, DataType.forRange(NumberRange.create(0d, true, 255d, true), false)); + } + /** * Tests {@link DataType#forBands(SampleModel)}. */ diff --git a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/iso/extent/DefaultGeographicBoundingBox.java b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/iso/extent/DefaultGeographicBoundingBox.java index 2ce6d0cc4e..f7ca7c4f84 100644 --- a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/iso/extent/DefaultGeographicBoundingBox.java +++ b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/iso/extent/DefaultGeographicBoundingBox.java @@ -631,11 +631,11 @@ public class DefaultGeographicBoundingBox extends AbstractGeographicExtent imple * In both cases, if either this box or the specified box has {@linkplain Double#NaN NaN} bounds, * then the corresponding bounds of the result will bet set to NaN. * - * <h4>Comparison with other API</h4> + * <h4>Interpretation of NaN in geographic bounding box compared to envelopes</h4> * This class is stricter about NaN values than other classes like {@link org.apache.sis.geometry.GeneralEnvelope}. * The reason is that computations on {@code GeographicBoundingBox} instances are rare ({@code Envelope} instances * are preferred for this purpose). Usually, {@code GeographicBoundingBox} values come directly from some metadata - * structure. Consequently, NaN values in {@code GeographicBoundingBox} means <q>information is unknown</q> + * structure. Therefore, NaN values in {@code GeographicBoundingBox} means <q>information is unknown</q> * more often than <q>not yet calculated</q>. * * @param box the geographic bounding box to add to this box.
