You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by ji...@apache.org on 2023/11/09 05:20:36 UTC
(sedona) branch master updated: [SEDONA-421] Add RS_Clip (#1078)
This is an automated email from the ASF dual-hosted git repository.
jiayu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sedona.git
The following commit(s) were added to refs/heads/master by this push:
new a996f8bc7 [SEDONA-421] Add RS_Clip (#1078)
a996f8bc7 is described below
commit a996f8bc792b8812c75b1b8d36d7dbcc6e076e7b
Author: Furqaan Khan <46...@users.noreply.github.com>
AuthorDate: Thu Nov 9 00:20:31 2023 -0500
[SEDONA-421] Add RS_Clip (#1078)
---
.../sedona/common/raster/RasterBandEditors.java | 139 +++++++++++++++++++++
.../apache/sedona/common/utils/RasterUtils.java | 27 ++--
.../common/raster/RasterBandEditorsTest.java | 45 +++++++
docs/api/sql/Raster-operators.md | 57 +++++++++
docs/image/clipped-raster.png | Bin 0 -> 8438 bytes
docs/image/cropped-raster.png | Bin 0 -> 4672 bytes
docs/image/original-raster-clip.png | Bin 0 -> 81411 bytes
.../scala/org/apache/sedona/sql/UDF/Catalog.scala | 1 +
.../expressions/raster/RasterBandEditors.scala | 10 ++
.../org/apache/sedona/sql/rasteralgebraTest.scala | 31 +++++
10 files changed, 303 insertions(+), 7 deletions(-)
diff --git a/common/src/main/java/org/apache/sedona/common/raster/RasterBandEditors.java b/common/src/main/java/org/apache/sedona/common/raster/RasterBandEditors.java
index fab78ccae..da37429c7 100644
--- a/common/src/main/java/org/apache/sedona/common/raster/RasterBandEditors.java
+++ b/common/src/main/java/org/apache/sedona/common/raster/RasterBandEditors.java
@@ -18,16 +18,26 @@
*/
package org.apache.sedona.common.raster;
+import org.apache.commons.lang3.ArrayUtils;
import org.apache.sedona.common.utils.RasterUtils;
import org.geotools.coverage.GridSampleDimension;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridEnvelope2D;
import org.geotools.coverage.grid.GridGeometry2D;
+import org.geotools.coverage.processing.operation.Crop;
import org.geotools.referencing.operation.transform.AffineTransform2D;
+import org.locationtech.jts.geom.Geometry;
import org.opengis.metadata.spatial.PixelOrientation;
+import org.opengis.parameter.ParameterValueGroup;
+import org.opengis.referencing.FactoryException;
+import org.opengis.referencing.operation.TransformException;
+import javax.media.jai.RasterFactory;
+import java.awt.geom.Point2D;
import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
import java.util.Arrays;
+import java.util.Collections;
public class RasterBandEditors {
public static GridCoverage2D setBandNoDataValue(GridCoverage2D raster, int bandIndex, double noDataValue) {
@@ -140,4 +150,133 @@ public class RasterBandEditors {
"Second raster having width of %d and height of %d", width1, height1, width2, height2));
}
}
+
+ /**
+ * Return a clipped raster with the specified ROI by the geometry
+ * @param raster Raster to clip
+ * @param band Band number to perform clipping
+ * @param geometry Specify ROI
+ * @param noDataValue no-Data value for empty cells
+ * @param crop Specifies to keep the original extent or not
+ * @return A clip Raster with defined ROI by the geometry
+ */
+ public static GridCoverage2D clip(GridCoverage2D raster, int band, Geometry geometry, double noDataValue, boolean crop) throws FactoryException, TransformException {
+
+ // Selecting the band from original raster
+ RasterUtils.ensureBand(raster, band);
+ GridCoverage2D singleBandRaster = RasterBandAccessors.getBand(raster, new int[]{band});
+
+ // Crop the raster
+ // this will shrink the extent of the raster to the geometry
+ Crop cropObject = new Crop();
+ ParameterValueGroup parameters = cropObject.getParameters();
+ parameters.parameter("Source").setValue(singleBandRaster);
+ parameters.parameter(Crop.PARAMNAME_DEST_NODATA).setValue(new double[]{noDataValue});
+ parameters.parameter(Crop.PARAMNAME_ROI).setValue(geometry);
+
+ GridCoverage2D newRaster = (GridCoverage2D) cropObject.doOperation(parameters, null);
+
+ if (!crop) {
+ double[] metadataOriginal = RasterAccessors.metadata(raster);
+ int widthOriginalRaster = (int) metadataOriginal[2], heightOriginalRaster = (int) metadataOriginal[3];
+ Raster rasterData = RasterUtils.getRaster(raster.getRenderedImage());
+
+
+ // create a new raster and set a default value that's the no-data value
+ String bandType = RasterBandAccessors.getBandType(raster, 1);
+ int dataTypeCode = RasterUtils.getDataTypeCode(RasterBandAccessors.getBandType(raster, 1));
+ boolean isDataTypeIntegral = RasterUtils.isDataTypeIntegral(dataTypeCode);
+ WritableRaster resultRaster = RasterFactory.createBandedRaster(dataTypeCode, widthOriginalRaster, heightOriginalRaster, 1, null);
+ int sizeOfArray = widthOriginalRaster * heightOriginalRaster;
+ if (isDataTypeIntegral) {
+ int[] array = ArrayUtils.toPrimitive(Collections.nCopies(sizeOfArray, (int) noDataValue).toArray(new Integer[sizeOfArray]));
+ resultRaster.setSamples(0, 0, widthOriginalRaster, heightOriginalRaster, 0, array);
+ } else {
+ double[] array = ArrayUtils.toPrimitive(Collections.nCopies(sizeOfArray, noDataValue).toArray(new Double[sizeOfArray]));
+ resultRaster.setSamples(0, 0, widthOriginalRaster, heightOriginalRaster, 0, array);
+ }
+
+ // rasterize the geometry to iterate over the clipped raster
+ GridCoverage2D rasterized = RasterConstructors.asRaster(geometry, raster, bandType, 150);
+ Raster rasterizedData = RasterUtils.getRaster(rasterized.getRenderedImage());
+ double[] metadataRasterized = RasterAccessors.metadata(rasterized);
+ int widthRasterized = (int) metadataRasterized[2], heightRasterized = (int) metadataRasterized[3];
+
+ for (int j = 0; j < heightRasterized; j++) {
+ for(int i = 0; i < widthRasterized; i++) {
+ Point2D point = RasterUtils.getWorldCornerCoordinates(rasterized, i, j);
+ int[] rasterCoord = RasterUtils.getGridCoordinatesFromWorld(raster, point.getX(), point.getY());
+ int x = Math.abs(rasterCoord[0]), y = Math.abs(rasterCoord[1]);
+
+ if (rasterizedData.getPixel(i, j, (int[]) null)[0] == 0) {
+ continue;
+ }
+
+ if (isDataTypeIntegral) {
+ int[] pixelValue = rasterData.getPixel(x, y, (int[]) null);
+
+ resultRaster.setPixel(x, y, new int[]{pixelValue[band - 1]});
+ } else {
+ double[] pixelValue = rasterData.getPixel(x, y, (double[]) null);
+
+ resultRaster.setPixel(x, y, new double[]{pixelValue[band - 1]});
+ }
+ }
+ }
+ newRaster = RasterUtils.create(resultRaster, raster.getGridGeometry(), newRaster.getSampleDimensions());
+ }
+
+ return newRaster;
+ }
+
+ /**
+ * Return a clipped raster with the specified ROI by the geometry.
+ * @param raster Raster to clip
+ * @param band Band number to perform clipping
+ * @param geometry Specify ROI
+ * @param noDataValue no-Data value for empty cells
+ * @return A clip Raster with defined ROI by the geometry
+ */
+ public static GridCoverage2D clip(GridCoverage2D raster, int band, Geometry geometry, double noDataValue) throws FactoryException, TransformException {
+ return clip(raster, band, geometry, noDataValue, true);
+ }
+
+ /**
+ * Return a clipped raster with the specified ROI by the geometry. No-data value will be taken as the lowest possible value for the data type and crop will be `true`.
+ * @param raster Raster to clip
+ * @param band Band number to perform clipping
+ * @param geometry Specify ROI
+ * @return A clip Raster with defined ROI by the geometry
+ */
+ public static GridCoverage2D clip(GridCoverage2D raster, int band, Geometry geometry) throws FactoryException, TransformException {
+ boolean isDataTypeIntegral = RasterUtils.isDataTypeIntegral(RasterUtils.getDataTypeCode(RasterBandAccessors.getBandType(raster, band)));
+
+ if (isDataTypeIntegral) {
+ double noDataValue = Integer.MIN_VALUE;
+ return clip(raster, band, geometry, noDataValue, true);
+ } else {
+ double noDataValue = Double.MIN_VALUE;
+ return clip(raster, band, geometry, noDataValue, true);
+ }
+ }
+
+// /**
+// * Return a clipped raster with the specified ROI by the geometry.
+// * @param raster Raster to clip
+// * @param band Band number to perform clipping
+// * @param geometry Specify ROI
+// * @param crop Specifies to keep the original extent or not
+// * @return A clip Raster with defined ROI by the geometry
+// */
+// public static GridCoverage2D clip(GridCoverage2D raster, int band, Geometry geometry, boolean crop) {
+// boolean isDataTypeIntegral = RasterUtils.isDataTypeIntegral(RasterUtils.getDataTypeCode(RasterBandAccessors.getBandType(raster, band)));
+//
+// if (isDataTypeIntegral) {
+// double noDataValue = Integer.MIN_VALUE;
+// return clip(raster, band, geometry, noDataValue, crop);
+// } else {
+// double noDataValue = Double.MIN_VALUE;
+// return clip(raster, band, geometry, noDataValue, crop);
+// }
+// }
}
diff --git a/common/src/main/java/org/apache/sedona/common/utils/RasterUtils.java b/common/src/main/java/org/apache/sedona/common/utils/RasterUtils.java
index 5b639783a..1f157279c 100644
--- a/common/src/main/java/org/apache/sedona/common/utils/RasterUtils.java
+++ b/common/src/main/java/org/apache/sedona/common/utils/RasterUtils.java
@@ -332,19 +332,32 @@ public class RasterUtils {
return geometry;
}
+ /**
+ * Converts data types to data type codes
+ * @param s pixel data type possible values {D, I, B, F, S, US} <br><br>
+ * Update: add support to convert RS_BandPixelType data type string to data type code possible values: <br>
+ * {REAL_64BITS, SIGNED_32BITS, UNSIGNED_8BITS, REAL_32BITS, SIGNED_16BITS, UNSIGNED_16BITS}
+ * @return Data type code
+ */
public static int getDataTypeCode(String s) {
- switch (s.toLowerCase()) {
- case "d":
+ switch (s.toUpperCase()) {
+ case "D":
+ case "REAL_64BITS":
return 5;
- case "i":
+ case "I":
+ case "SIGNED_32BITS":
return 3;
- case "b":
+ case "B":
+ case "UNSIGNED_8BITS":
return 0;
- case "f":
+ case "F":
+ case "REAL_32BITS":
return 4;
- case "s":
+ case "S":
+ case "SIGNED_16BITS":
return 2;
- case "us":
+ case "US":
+ case "UNSIGNED_16BITS":
return 1;
}
return 5; // defaulting to double
diff --git a/common/src/test/java/org/apache/sedona/common/raster/RasterBandEditorsTest.java b/common/src/test/java/org/apache/sedona/common/raster/RasterBandEditorsTest.java
index 09ae12b93..0901593bc 100644
--- a/common/src/test/java/org/apache/sedona/common/raster/RasterBandEditorsTest.java
+++ b/common/src/test/java/org/apache/sedona/common/raster/RasterBandEditorsTest.java
@@ -18,12 +18,20 @@
*/
package org.apache.sedona.common.raster;
+import org.apache.sedona.common.Constructors;
+import org.apache.sedona.common.utils.RasterUtils;
import org.geotools.coverage.grid.GridCoverage2D;
import org.junit.Test;
+import org.locationtech.jts.geom.Geometry;
+import org.locationtech.jts.io.ParseException;
import org.opengis.referencing.FactoryException;
+import org.opengis.referencing.operation.TransformException;
+import java.awt.geom.Point2D;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@@ -69,6 +77,43 @@ public class RasterBandEditorsTest extends RasterTestBase{
assertEquals(444, (double) RasterBandAccessors.getBandNoDataValue(grid, 2), 0.1d);
}
+ @Test
+ public void testClip() throws IOException, FactoryException, TransformException, ParseException {
+ GridCoverage2D raster = rasterFromGeoTiff(resourceFolder + "raster_geotiff_color/FAA_UTM18N_NAD83.tif");
+ String polygon = "POLYGON ((236722 4204770, 243900 4204770, 243900 4197590, 221170 4197590, 236722 4204770))";
+ Geometry geom = Constructors.geomFromWKT(polygon, RasterAccessors.srid(raster));
+
+ GridCoverage2D clippedRaster = RasterBandEditors.clip(raster, 1, geom, 200, false);
+ double[] clippedMetadata = Arrays.stream(RasterAccessors.metadata(clippedRaster), 0, 9).toArray();
+ double[] originalMetadata = Arrays.stream(RasterAccessors.metadata(raster), 0, 9).toArray();
+ assertArrayEquals(originalMetadata, clippedMetadata, 0.01d);
+
+ String actual = String.valueOf(clippedRaster.getSampleDimensions()[0]);
+ String expected = String.valueOf(raster.getSampleDimensions()[0]);
+ assertEquals(expected, actual);
+
+ List<Geometry> points = new ArrayList<>();
+ points.add(Constructors.geomFromWKT("POINT(223802 4.21769e+06)", 26918));
+ points.add(Constructors.geomFromWKT("POINT(224759 4.20453e+06)", 26918));
+ points.add(Constructors.geomFromWKT("POINT(237201 4.20429e+06)", 26918));
+ points.add(Constructors.geomFromWKT("POINT(237919 4.20357e+06)", 26918));
+ points.add(Constructors.geomFromWKT("POINT(254668 4.21769e+06)", 26918));
+ double[] actualValues = PixelFunctions.values(clippedRaster, points, 1).stream().mapToDouble(d -> d).toArray();
+ double[] expectedValues = new double[] {200.0, 200.0, 0.0, 0.0, 200.0};
+ assertArrayEquals(expectedValues, actualValues, 0.001d);
+
+ GridCoverage2D croppedRaster = RasterBandEditors.clip(raster, 1, geom, 200, true);
+ points = new ArrayList<>();
+ points.add(Constructors.geomFromWKT("POINT(236842 4.20465e+06)", 26918));
+ points.add(Constructors.geomFromWKT("POINT(236961 4.20453e+06)", 26918));
+ points.add(Constructors.geomFromWKT("POINT(237201 4.20429e+06)", 26918));
+ points.add(Constructors.geomFromWKT("POINT(237919 4.20357e+06)", 26918));
+ points.add(Constructors.geomFromWKT("POINT(223802 4.20465e+06)", 26918));
+ actualValues = PixelFunctions.values(croppedRaster, points, 1).stream().mapToDouble(d -> d).toArray();
+ expectedValues = new double[] {0.0, 0.0, 0.0, 0.0, 200.0};
+ assertArrayEquals(expectedValues, actualValues, 0.001d);
+ }
+
@Test
public void testAddBandWithEmptyRaster() throws FactoryException {
double[][] rasterData1 = new double[][] {
diff --git a/docs/api/sql/Raster-operators.md b/docs/api/sql/Raster-operators.md
index 3bafeb448..02ee063b3 100644
--- a/docs/api/sql/Raster-operators.md
+++ b/docs/api/sql/Raster-operators.md
@@ -1063,6 +1063,63 @@ Output:
GridCoverage2D["g...
```
+### RS_Clip
+
+Introduction: Returns a raster that is clipped by the given geometry.
+
+If `crop` is not specified then it will default to `true`, meaning it will make the resulting raster shrink to the geometry's extent and if `noDataValue` is not specified then the resulting raster will have the minimum possible value for the band pixel data type.
+
+!!!note
+ When `crop` is `true`, no new raster is created - instead a viewpoint to the source raster is returned, and when `false`, a new raster is generated.
+
+Format:
+
+```
+RS_Clip(raster: Raster, band: Integer, geom: Geometry, noDataValue: Double, crop: Boolean)
+```
+
+```
+RS_Clip(raster: Raster, band: Integer, geom: Geometry, noDataValue: Double)
+```
+
+```
+RS_Clip(raster: Raster, band: Integer, geom: Geometry)
+```
+
+Since: `v1.5.1`
+
+Original Raster:
+
+<img alt="Original raster" src="../../../image/original-raster-clip.png" width="400"/>
+
+Spark SQL Example:
+
+```sql
+SELECT RS_Clip(
+ RS_FromGeoTiff(content), 1,
+ ST_GeomFromWKT('POLYGON ((236722 4204770, 243900 4204770, 243900 4197590, 221170 4197590, 236722 4204770))'),
+ 200, true
+ )
+```
+
+Output:
+
+<img alt="Cropped raster" src="../../../image/cropped-raster.png" width="400"/>
+
+Spark SQL Example:
+
+```sql
+SELECT RS_Clip(
+ RS_FromGeoTiff(content), 1,
+ ST_GeomFromWKT('POLYGON ((236722 4204770, 243900 4204770, 243900 4197590, 221170 4197590, 236722 4204770))'),
+ 200, false
+ )
+```
+
+Output:
+
+<img alt="Clipped raster" src="../../../image/clipped-raster.png" width="400"/>
+
### RS_MetaData
Introduction: Returns the metadata of the raster as an array of double. The array contains the following values:
diff --git a/docs/image/clipped-raster.png b/docs/image/clipped-raster.png
new file mode 100644
index 000000000..b88943c9f
Binary files /dev/null and b/docs/image/clipped-raster.png differ
diff --git a/docs/image/cropped-raster.png b/docs/image/cropped-raster.png
new file mode 100644
index 000000000..4942cf736
Binary files /dev/null and b/docs/image/cropped-raster.png differ
diff --git a/docs/image/original-raster-clip.png b/docs/image/original-raster-clip.png
new file mode 100644
index 000000000..a6dd1c759
Binary files /dev/null and b/docs/image/original-raster-clip.png differ
diff --git a/spark/common/src/main/scala/org/apache/sedona/sql/UDF/Catalog.scala b/spark/common/src/main/scala/org/apache/sedona/sql/UDF/Catalog.scala
index 92238b742..75f30016c 100644
--- a/spark/common/src/main/scala/org/apache/sedona/sql/UDF/Catalog.scala
+++ b/spark/common/src/main/scala/org/apache/sedona/sql/UDF/Catalog.scala
@@ -232,6 +232,7 @@ object Catalog {
function[RS_PixelAsPolygon](),
function[RS_PixelAsCentroid](),
function[RS_Count](),
+ function[RS_Clip](),
function[RS_Band](),
function[RS_AddBand](),
function[RS_SummaryStats](),
diff --git a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/raster/RasterBandEditors.scala b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/raster/RasterBandEditors.scala
index fa85469e1..00a45dc25 100644
--- a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/raster/RasterBandEditors.scala
+++ b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/raster/RasterBandEditors.scala
@@ -41,3 +41,13 @@ case class RS_AddBand(inputExpressions: Seq[Expression]) extends InferredExpress
copy(inputExpressions = newChildren)
}
}
+
+case class RS_Clip(inputExpressions: Seq[Expression]) extends InferredExpression(
+ inferrableFunction5(RasterBandEditors.clip),
+ inferrableFunction4(RasterBandEditors.clip),
+ inferrableFunction3(RasterBandEditors.clip)
+) {
+ protected def withNewChildrenInternal(newChildren: IndexedSeq[Expression]) = {
+ copy(inputExpressions = newChildren)
+ }
+}
diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/rasteralgebraTest.scala b/spark/common/src/test/scala/org/apache/sedona/sql/rasteralgebraTest.scala
index ba4767c4c..eb37f1425 100644
--- a/spark/common/src/test/scala/org/apache/sedona/sql/rasteralgebraTest.scala
+++ b/spark/common/src/test/scala/org/apache/sedona/sql/rasteralgebraTest.scala
@@ -524,6 +524,37 @@ class rasteralgebraTest extends TestBaseScala with BeforeAndAfter with GivenWhen
assert(result.get(1) == null)
}
+ it("Passed RS_Clip with raster") {
+ val df = sparkSession.read.format("binaryFile").load(resourceFolder + "raster_geotiff_color/FAA_UTM18N_NAD83.tif")
+ .selectExpr("RS_FromGeoTiff(content) as raster",
+ "ST_GeomFromWKT('POLYGON ((236722 4204770, 243900 4204770, 243900 4197590, 221170 4197590, 236722 4204770))') as geom")
+ val clippedDf = df.selectExpr("RS_Clip(raster, 1, geom, 200, false) as clipped")
+
+ val clippedMetadata = df.selectExpr("RS_Metadata(raster)").first().getSeq(0).slice(0, 9)
+ val originalMetadata = clippedDf.selectExpr("RS_Metadata(clipped)").first().getSeq(0).slice(0, 9)
+ assertTrue(originalMetadata.equals(clippedMetadata))
+
+ var actualValues = clippedDf.selectExpr(
+ "RS_Values(clipped, " +
+ "Array(ST_GeomFromWKT('POINT(223802 4.21769e+06)'),ST_GeomFromWKT('POINT(224759 4.20453e+06)')," +
+ "ST_GeomFromWKT('POINT(237201 4.20429e+06)'),ST_GeomFromWKT('POINT(237919 4.20357e+06)')," +
+ "ST_GeomFromWKT('POINT(254668 4.21769e+06)')), 1)"
+ ).first().get(0)
+ var expectedValues = Seq(200.0, 200.0, 0.0, 0.0, 200.0)
+ assertTrue(expectedValues.equals(actualValues))
+
+ val croppedDf = df.selectExpr("RS_Clip(raster, 1, geom, 200, false) as cropped")
+ actualValues = croppedDf.selectExpr(
+ "RS_Values(cropped, " +
+ "Array(ST_GeomFromWKT('POINT(236842 4.20465e+06)'),ST_GeomFromWKT('POINT(236961 4.20453e+06)')," +
+ "ST_GeomFromWKT('POINT(237201 4.20429e+06)'),ST_GeomFromWKT('POINT(237919 4.20357e+06)')," +
+ "ST_GeomFromWKT('POINT(223802 4.20465e+06)')), 1)"
+ ).first().get(0)
+ expectedValues = Seq(0.0, 0.0, 0.0, 0.0, 200.0)
+ assertTrue(expectedValues.equals(actualValues))
+
+ }
+
it("Passed RS_AsGeoTiff") {
val df = sparkSession.read.format("binaryFile").load(resourceFolder + "raster/test1.tiff")
val resultRaw = df.selectExpr("RS_FromGeoTiff(content) as raster").first().get(0)