org.geotools.geometry.Envelope2D Java Examples

The following examples show how to use org.geotools.geometry.Envelope2D. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OmsLasConverter.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private void createBboxGeometry( CoordinateReferenceSystem crs, File lasFile, SimpleFeatureCollection outGeodata )
        throws Exception {
    final ReferencedEnvelope3D envelope = lasReader.getHeader().getDataEnvelope();
    ReferencedEnvelope env2d = new ReferencedEnvelope(envelope);
    final Polygon polygon = FeatureUtilities.envelopeToPolygon(new Envelope2D(env2d));

    final SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("lasdataenvelope");
    b.setCRS(crs);
    b.add("the_geom", Polygon.class);
    b.add("id", String.class);
    final SimpleFeatureType type = b.buildFeatureType();

    final SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    final Object[] values = new Object[]{polygon, lasFile.getName()};
    builder.addAll(values);
    final SimpleFeature feature = builder.buildFeature(null);
    ((DefaultFeatureCollection) outGeodata).add(feature);
    OmsVectorWriter.writeVector(outFile, outGeodata);
}
 
Example #2
Source File: FeatureUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a {@link Polygon} from an {@link Envelope}.
 * 
 * @param envelope the envelope to convert.
 * @return the created polygon.
 */
public static Polygon envelopeToPolygon( Envelope2D envelope ) {
    double w = envelope.getMinX();
    double e = envelope.getMaxX();
    double s = envelope.getMinY();
    double n = envelope.getMaxY();

    Coordinate[] coords = new Coordinate[5];
    coords[0] = new Coordinate(w, n);
    coords[1] = new Coordinate(e, n);
    coords[2] = new Coordinate(e, s);
    coords[3] = new Coordinate(w, s);
    coords[4] = new Coordinate(w, n);

    GeometryFactory gf = GeometryUtilities.gf();
    LinearRing linearRing = gf.createLinearRing(coords);
    Polygon polygon = gf.createPolygon(linearRing, null);
    return polygon;
}
 
Example #3
Source File: SceneFeatureIteratorTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Test
public void testIterate() throws IOException, CQLException {
  final boolean onlyScenesSinceLastRun = false;
  final boolean useCachedScenes = true;
  final boolean nBestScenesByPathRow = false;
  final int nBestScenes = 1;
  final Filter cqlFilter = CQL.toFilter("BBOX(shape,-76.6,42.34,-76.4,42.54) and band='BQA'");
  final String workspaceDir = Tests.WORKSPACE_DIR;

  final List<SimpleFeature> features = new ArrayList<>();
  try (SceneFeatureIterator iterator =
      new SceneFeatureIterator(
          onlyScenesSinceLastRun,
          useCachedScenes,
          nBestScenesByPathRow,
          nBestScenes,
          cqlFilter,
          workspaceDir)) {
    while (iterator.hasNext()) {
      features.add(iterator.next());
    }
  }

  assertEquals(features.size(), 1);
  assertThat(
      features,
      everyItem(
          allOf(
              hasProperties(),
              inBounds(
                  new Envelope2D(
                      new DirectPosition2D(-76.6, 42.34),
                      new DirectPosition2D(-76.4, 42.54))))));
}
 
Example #4
Source File: Raster.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public GridGeometry2D getGridGeometry() {
    if (gridGeometry == null) {
        Envelope envelope = new Envelope2D(crs, west, south, east - west, north - south);
        GridEnvelope2D gridRange = new GridEnvelope2D(0, 0, cols, rows);
        gridGeometry = new GridGeometry2D(gridRange, envelope);
    }
    return gridGeometry;
}
 
Example #5
Source File: TestScanLineRasterizer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    elevationData = HMTestMaps.mapData;
    elevationCoverage = CoverageUtilities.buildCoverage("elevation", elevationData, ep, crs, true);
    Envelope2D envelope = elevationCoverage.getEnvelope2D();
    polygon = FeatureUtilities.envelopeToPolygon(envelope);
}
 
Example #6
Source File: JGTProcessingRegion.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new instance of {@link JGTProcessingRegion} from an {@link Envelope2D}
 * .
 * 
 * @param envelope2D
 *            the envelope2D from which to take the setting from.
 */
public JGTProcessingRegion( Envelope2D envelope2D ) {
    west = envelope2D.getMinX();
    east = envelope2D.getMaxX();
    south = envelope2D.getMinY();
    north = envelope2D.getMaxY();
    we_res = envelope2D.getHeight();
    ns_res = envelope2D.getWidth();

    fixRowsAndCols();
    fixResolution();
}
 
Example #7
Source File: PrintUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static String toString( GridCoverage2D coverage ) {
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(coverage);
    StringBuilder sb = new StringBuilder();
    sb.append(regionMap.toStringJGT()).append("\n");
    Envelope2D envelope2d = coverage.getEnvelope2D();
    Envelope jtsEnvelope = envelope2D2Envelope(envelope2d);
    String envelope2wkt = envelope2WKT(jtsEnvelope);
    sb.append("WKT bounds: \n");
    sb.append(envelope2wkt);
    return sb.toString();
}
 
Example #8
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a {@link GridCoverage2D coverage} from the {@link WritableRaster writable raster} and the necessary geographic Information.
 * 
 * @param name the name of the coverage.
 * @param writableRaster the raster containing the data.
 * @param envelopeParams the map of boundary parameters.
 * @param crs the {@link CoordinateReferenceSystem}.
 * @return the {@link GridCoverage2D coverage}.
 */
public static GridCoverage2D buildCoverage( String name, WritableRaster writableRaster,
        HashMap<String, Double> envelopeParams, CoordinateReferenceSystem crs ) {
    double west = envelopeParams.get(WEST);
    double south = envelopeParams.get(SOUTH);
    double east = envelopeParams.get(EAST);
    double north = envelopeParams.get(NORTH);
    Envelope2D writeEnvelope = new Envelope2D(crs, west, south, east - west, north - south);
    GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);

    GridCoverage2D coverage2D = factory.create(name, writableRaster, writeEnvelope);
    return coverage2D;
}
 
Example #9
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a {@link GridCoverage2D coverage} from the {@link RenderedImage image} and the necessary geographic Information.
 * 
 * @param name the name of the coverage.
 * @param renderedImage the image containing the data.
 * @param envelopeParams the map of boundary parameters.
 * @param crs the {@link CoordinateReferenceSystem}.
 * @return the {@link GridCoverage2D coverage}.
 */
public static GridCoverage2D buildCoverage( String name, RenderedImage renderedImage, HashMap<String, Double> envelopeParams,
        CoordinateReferenceSystem crs ) {

    double west = envelopeParams.get(WEST);
    double south = envelopeParams.get(SOUTH);
    double east = envelopeParams.get(EAST);
    double north = envelopeParams.get(NORTH);
    Envelope2D writeEnvelope = new Envelope2D(crs, west, south, east - west, north - south);
    GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);

    GridCoverage2D coverage2D = factory.create(name, renderedImage, writeEnvelope);
    return coverage2D;
}
 
Example #10
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static GridGeometry2D gridGeometryFromRegionValues( double north, double south, double east, double west, int cols,
        int rows, CoordinateReferenceSystem crs ) {
    Envelope envelope = new Envelope2D(crs, west, south, east - west, north - south);
    GridEnvelope2D gridRange = new GridEnvelope2D(0, 0, cols, rows);
    GridGeometry2D gridGeometry2D = new GridGeometry2D(gridRange, envelope);
    return gridGeometry2D;
}
 
Example #11
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the cols and rows ranges to use to loop the original gridcoverage.
 * 
 * @param gridCoverage the coverage.
 * @param subregion the sub region of the coverage to get the cols and rows to loop on.
 * @return the array of looping values in the form [minCol, maxCol, minRow, maxRow].
 * @throws Exception
 */
public static int[] getLoopColsRowsForSubregion( GridCoverage2D gridCoverage, Envelope2D subregion ) throws Exception {
    GridGeometry2D gridGeometry = gridCoverage.getGridGeometry();
    GridEnvelope2D subRegionGrid = gridGeometry.worldToGrid(subregion);
    int minCol = subRegionGrid.x;
    int maxCol = subRegionGrid.x + subRegionGrid.width;
    int minRow = subRegionGrid.y;
    int maxRow = subRegionGrid.y + subRegionGrid.height;
    return new int[]{minCol, maxCol, minRow, maxRow};
}
 
Example #12
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a bounds polygon of a {@link GridCoverage2D}.
 * 
 * @param gridCoverage the coverage to use.
 * @return the bounding polygon.
 */
public static Polygon getRegionPolygon( GridCoverage2D gridCoverage ) {
    Envelope2D env = gridCoverage.getEnvelope2D();
    Coordinate[] c = new Coordinate[]{new Coordinate(env.getMinX(), env.getMinY()),
            new Coordinate(env.getMinX(), env.getMaxY()), new Coordinate(env.getMaxX(), env.getMaxY()),
            new Coordinate(env.getMaxX(), env.getMinY()), new Coordinate(env.getMinX(), env.getMinY())};
    GeometryFactory gf = GeometryUtilities.gf();
    LinearRing linearRing = gf.createLinearRing(c);
    Polygon polygon = gf.createPolygon(linearRing, null);
    return polygon;
}
 
Example #13
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a subcoverage given a template coverage and an envelope.
 * 
 * @param template the template coverage used for the resolution.
 * @param subregion the envelope to extract to the new coverage. This should
 *                  be snapped on the resolution of the coverage, in order to avoid 
 *                  shifts.
 * @param value the value to set the new raster to, if not <code>null</code>. 
 * @param writableRasterHolder an array of length 1 to place the writable raster in, that 
 *                  was can be used to populate the coverage. If <code>null</code>, it is ignored.
 * @return the new coverage.
 */
public static GridCoverage2D createSubCoverageFromTemplate( GridCoverage2D template, Envelope2D subregion, Double value,
        WritableRaster[] writableRasterHolder ) {
    RegionMap regionMap = getRegionParamsFromGridCoverage(template);
    double xRes = regionMap.getXres();
    double yRes = regionMap.getYres();

    double west = subregion.getMinX();
    double south = subregion.getMinY();
    double east = subregion.getMaxX();
    double north = subregion.getMaxY();

    int cols = (int) ((east - west) / xRes);
    int rows = (int) ((north - south) / yRes);
    ComponentSampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_DOUBLE, cols, rows, 1, cols, new int[]{0});

    WritableRaster writableRaster = RasterFactory.createWritableRaster(sampleModel, null);
    if (value != null) {
        // autobox only once
        double v = value;
        for( int y = 0; y < rows; y++ ) {
            for( int x = 0; x < cols; x++ ) {
                writableRaster.setSample(x, y, 0, v);
            }
        }
    }
    if (writableRasterHolder != null)
        writableRasterHolder[0] = writableRaster;
    Envelope2D writeEnvelope = new Envelope2D(template.getCoordinateReferenceSystem(), west, south, east - west,
            north - south);
    GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);
    GridCoverage2D coverage2D = factory.create("newraster", writableRaster, writeEnvelope);
    return coverage2D;
}
 
Example #14
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new {@link GridCoverage2D} using an existing as template.
 * 
 * @param template the template to use.
 * @param value the value to set the new raster to, if not <code>null</code>.
 * @param writableRasterHolder an array of length 1 to place the writable raster in, that 
 *                  was can be used to populate the coverage. If <code>null</code>, it is ignored.
 * @return the new coverage.
 */
public static GridCoverage2D createCoverageFromTemplate( GridCoverage2D template, Double value,
        WritableRaster[] writableRasterHolder ) {
    RegionMap regionMap = getRegionParamsFromGridCoverage(template);

    double west = regionMap.getWest();
    double south = regionMap.getSouth();
    double east = regionMap.getEast();
    double north = regionMap.getNorth();
    int cols = regionMap.getCols();
    int rows = regionMap.getRows();
    ComponentSampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_DOUBLE, cols, rows, 1, cols, new int[]{0});

    WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, null);
    if (value != null) {
        // autobox only once
        double v = value;
        for( int y = 0; y < rows; y++ ) {
            for( int x = 0; x < cols; x++ ) {
                raster.setSample(x, y, 0, v);
            }
        }
    }
    if (writableRasterHolder != null) {
        writableRasterHolder[0] = raster;
    }

    Envelope2D writeEnvelope = new Envelope2D(template.getCoordinateReferenceSystem(), west, south, east - west,
            north - south);
    GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);
    GridCoverage2D coverage2D = factory.create("newraster", raster, writeEnvelope);
    return coverage2D;
}
 
Example #15
Source File: PrintUtilities.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public static org.locationtech.jts.geom.Envelope envelope2D2Envelope( Envelope2D envelope2d ) {
    org.locationtech.jts.geom.Envelope jtsEnv = new org.locationtech.jts.geom.Envelope(envelope2d.getMinX(),
            envelope2d.getMaxX(), envelope2d.getMinY(), envelope2d.getMaxY());
    return jtsEnv;
}
 
Example #16
Source File: OmsGeomorphon.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Calculate a simple line of sight, given two coordinates on a raster.
 * 
 * @param regionMap
 * @param elevIter
 * @param gridGeometry
 * @param startCoordinate
 * @param endCoordinate
 * @return the last visible point, starting from the startCoordinate.
 * @throws TransformException
 */
public static ProfilePoint getLastVisiblePoint( RegionMap regionMap, RandomIter elevIter, GridGeometry2D gridGeometry,
        Coordinate startCoordinate, Coordinate endCoordinate ) throws TransformException {
    Envelope2D envelope2d = gridGeometry.getEnvelope2D();
    ProfilePoint lastVisible = null;
    double minX = envelope2d.getMinX();
    double maxX = envelope2d.getMaxX();
    double minY = envelope2d.getMinY();
    double maxY = envelope2d.getMaxY();

    if (endCoordinate.x >= minX && //
            endCoordinate.x <= maxX && //
            endCoordinate.y >= minY && //
            endCoordinate.y <= maxY//
    ) {
        List<ProfilePoint> profile = CoverageUtilities.doProfile(elevIter, gridGeometry, startCoordinate, endCoordinate);

        ProfilePoint first = profile.get(0);
        double viewerelev = first.getElevation();

        ProfilePoint secondPoint = profile.get(1);
        double lastMax = secondPoint.getElevation() - viewerelev;
        double lastMaxFactor = lastMax / secondPoint.getProgressive();
        lastVisible = secondPoint;

        for( int i = 2; i < profile.size(); i++ ) {
            ProfilePoint currentPoint = profile.get(i);
            double currentElev = currentPoint.getElevation() - viewerelev;
            double currentProg = currentPoint.getProgressive();
            // the maximum value that it can reach. If it is bigger, it is the new max
            double possibleMax = currentProg * lastMaxFactor;
            if (currentElev >= possibleMax) {
                // new max found, recalculate line of sight and set this as last seen point
                lastMax = currentElev;
                lastMaxFactor = lastMax / currentProg;
                lastVisible = currentPoint;
            }
        }
    }

    return lastVisible;
}
 
Example #17
Source File: LasOnDtmBuildingsExtractor.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inLas, inDtm, outBuildings);

    SimpleFeatureCollection buildingsFC = null;
    GridCoverage2D inDtmGC = null;
    try (ALasDataManager lasHandler = ALasDataManager.getDataManager(new File(inLas), inDtmGC, 0, null)) {
        lasHandler.open();

        ReferencedEnvelope3D e = lasHandler.getEnvelope3D();

        if (pRasterResolution != null) {
            OmsRasterReader reader = new OmsRasterReader();
            reader.file = inDtm;
            reader.pNorth = e.getMaxY();
            reader.pSouth = e.getMinY();
            reader.pWest = e.getMinX();
            reader.pEast = e.getMaxX();
            reader.pXres = pRasterResolution;
            reader.pYres = pRasterResolution;
            reader.process();
            inDtmGC = reader.outRaster;
        } else {
            inDtmGC = getRaster(inDtm);
            RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inDtmGC);
            pRasterResolution = regionMap.getXres();
        }

        Envelope2D envelope2d = inDtmGC.getEnvelope2D();
        Polygon regionPolygon = FeatureUtilities.envelopeToPolygon(envelope2d);

        WritableRaster[] buildingsHolder = new WritableRaster[1];
        GridCoverage2D newBuildingsRaster = CoverageUtilities.createCoverageFromTemplate(inDtmGC, 1.0, buildingsHolder);
        GridGeometry2D gridGeometry = newBuildingsRaster.getGridGeometry();

        java.awt.Point p = new java.awt.Point();
        IHMProgressMonitor pm = new LogProgressMonitor();
        pm.beginTask("Reading points...", IHMProgressMonitor.UNKNOWN);
        List<LasRecord> pointsInGeometry = lasHandler.getPointsInGeometry(regionPolygon, true);
        pm.done();
        pm.beginTask("Buildings filtering...", (int) pointsInGeometry.size());
        for( LasRecord dot : pointsInGeometry ) {
            Coordinate c = new Coordinate(dot.x, dot.y);
            if (!envelope2d.contains(dot.x, dot.y)) {
                continue;
            }

            double dtmValue = CoverageUtilities.getValue(inDtmGC, c);
            double height = abs(dot.z - dtmValue);
            CoverageUtilities.colRowFromCoordinate(c, gridGeometry, p);
            if (height < pDtmThres) {
                buildingsHolder[0].setSample(p.x, p.y, 0, doubleNovalue);
            }
            pm.worked(1);
        }
        pm.done();

        OmsMorpher morpher = new OmsMorpher();
        morpher.pm = pm;
        morpher.inMap = newBuildingsRaster;
        morpher.pMode = Variables.OPEN;
        morpher.process();
        newBuildingsRaster = morpher.outMap;

        OmsVectorizer buildingsVectorizer = new OmsVectorizer();
        buildingsVectorizer.pm = pm;
        buildingsVectorizer.inRaster = newBuildingsRaster;
        buildingsVectorizer.doRemoveHoles = true;
        double minAreaInCells = pMinArea / pRasterResolution / pRasterResolution;
        buildingsVectorizer.pThres = minAreaInCells;
        buildingsVectorizer.fDefault = "rast";
        buildingsVectorizer.process();

        buildingsFC = buildingsVectorizer.outVector;
        dumpVector(buildingsFC, outBuildings);
        if (doSmoothing && outCleanBuildings != null) {
            // smooth
            SimpleFeatureCollection smoothedFC = smoothBuildings(pDensifyResolution, buildingsFC);

            // remove trees
            DefaultFeatureCollection removedAndSmoothedFC = removeNonBuildings(lasHandler, smoothedFC, inDtmGC,
                    pBuildingsBuffer);

            dumpVector(removedAndSmoothedFC, outCleanBuildings);
        }
    }

}
 
Example #18
Source File: SceneFeatureIteratorTest.java    From geowave with Apache License 2.0 4 votes vote down vote up
public void testIterate(final String providerName)
    throws IOException, CQLException, ParseException, NoSuchAuthorityCodeException,
    FactoryException, MalformedURLException, GeneralSecurityException {

  final Sentinel2ImageryProvider provider = Sentinel2ImageryProvider.getProvider(providerName);
  if (provider == null) {
    throw new RuntimeException("Unable to find '" + providerName + "' Sentinel2 provider");
  }

  final String collection = provider.collections()[0];
  final String platform = "";
  final String location = "T30TWM";
  final Date startDate = DateUtilities.parseISO("2018-01-28T00:00:00Z");
  final Date endDate = DateUtilities.parseISO("2018-01-30T00:00:00Z");
  final int orbitNumber = 0;
  final int relativeOrbitNumber = 0;
  final Filter cqlFilter = CQL.toFilter("BBOX(shape,-1.8274,42.3253,-1.6256,42.4735)");
  final String workspaceDir = Tests.WORKSPACE_DIR;

  final List<SimpleFeature> features = new ArrayList<>();
  try (SceneFeatureIterator iterator =
      new SceneFeatureIterator(
          providerName,
          collection,
          platform,
          location,
          startDate,
          endDate,
          orbitNumber,
          relativeOrbitNumber,
          cqlFilter,
          workspaceDir)) {
    while (iterator.hasNext()) {
      features.add(iterator.next());
    }
  }

  assertEquals(features.size(), 1);
  assertThat(
      features,
      everyItem(
          allOf(
              hasProperties(),
              inBounds(
                  new Envelope2D(
                      new DirectPosition2D(-1.828, 42.325),
                      new DirectPosition2D(-1.624, 42.474))))));
}