@Test public void getEnvelope2D() { ReferencedEnvelope refEnv = new ReferencedEnvelope(-10, 10, -5, 5, DefaultGeographicCRS.WGS84); Envelope2D env2D = JTS.getEnvelope2D(refEnv, refEnv.getCoordinateReferenceSystem()); CRS.equalsIgnoreMetadata( refEnv.getCoordinateReferenceSystem(), env2D.getCoordinateReferenceSystem()); assertTrue(env2D.boundsEquals(refEnv, 0, 1, TOL)); }
/** @param ev */ @Override public void onMouseReleased(MapMouseEvent ev) { // avoid the zooming window at the time scroll button pan action. if (dragged && !ev.getPoint().equals(startDragPos) && ev.getButton() != java.awt.event.MouseEvent.BUTTON2) { dragged = false; Envelope2D env = new Envelope2D(); env.setFrameFromDiagonal(startDragPos, ev.getWorldPos()); this.onRectangleFinished(env); } }
/** * Zoom out by the currently set increment, with the map centred at the location (in world coords) * of the mouse click * * @param ev the mouse event */ @Override public void onMouseClicked(MapMouseEvent ev) { if (!isTriggerMouseButton(ev)) { return; } Rectangle paneArea = getMapPane().getBounds(); DirectPosition2D mapPos = ev.getMapPosition(); double scale = getMapPane().getWorldToScreenTransform().getScaleX(); double newScale = scale / zoom; DirectPosition2D corner = new DirectPosition2D( mapPos.getX() - 0.5d * paneArea.width / newScale, mapPos.getY() + 0.5d * paneArea.height / newScale); Envelope2D newMapArea = new Envelope2D(); newMapArea.setFrameFromCenter(mapPos, corner); getMapPane().setDisplayArea(newMapArea); }
public static JGrassRegion getJGrassRegionFromGridCoverage(GridCoverage2D gridCoverage2D) throws InvalidGridGeometryException, TransformException { Envelope2D env = gridCoverage2D.getEnvelope2D(); GridEnvelope2D worldToGrid = gridCoverage2D.getGridGeometry().worldToGrid(env); double xRes = env.getWidth() / worldToGrid.getWidth(); double yRes = env.getHeight() / worldToGrid.getHeight(); JGrassRegion region = new JGrassRegion(env.getMinX(), env.getMaxX(), env.getMinY(), env.getMaxY(), xRes, yRes); return region; }
/** * Applies a crop operation to a coverage. * * @see * org.geotools.coverage.processing.AbstractOperation#doOperation(org.opengis.parameter.ParameterValueGroup, * org.geotools.factory.Hints) */ @SuppressWarnings("unchecked") public Coverage doOperation(ParameterValueGroup parameters, Hints hints) { final Geometry cropRoi; // extracted from parameters GeneralEnvelope cropEnvelope = null; // extracted from parameters final GridCoverage2D source; // extracted from parameters final double roiTolerance = parameters.parameter(Crop.PARAMNAME_ROITOLERANCE).doubleValue(); final boolean forceMosaic = parameters.parameter(Crop.PARAMNAME_FORCEMOSAIC).booleanValue(); // ///////////////////////////////////////////////////////////////////// // // Assigning and checking input parameters // // /////////////////////////////////////////////////////////////////// // source coverage final ParameterValue sourceParameter = parameters.parameter("Source"); if (sourceParameter == null || !(sourceParameter.getValue() instanceof GridCoverage2D)) { throw new CannotCropException( Errors.format(ErrorKeys.NULL_PARAMETER_$2, "Source", GridCoverage2D.class.toString())); } source = (GridCoverage2D) sourceParameter.getValue(); // Check Envelope and ROI existence - we need at least one of them final ParameterValue envelopeParameter = parameters.parameter(PARAMNAME_ENVELOPE); final ParameterValue roiParameter = parameters.parameter(PARAMNAME_ROI); if ((envelopeParameter == null || envelopeParameter.getValue() == null) && (roiParameter == null || roiParameter.getValue() == null)) throw new CannotCropException( Errors.format( ErrorKeys.NULL_PARAMETER_$2, PARAMNAME_ENVELOPE, GeneralEnvelope.class.toString())); Object envelope = envelopeParameter.getValue(); if (envelope != null) { if (envelope instanceof GeneralEnvelope) { cropEnvelope = (GeneralEnvelope) envelope; } else if (envelope instanceof Envelope) { cropEnvelope = new GeneralEnvelope((Envelope) envelope); } } // may be null // Check crop ROI try { cropRoi = IntersectUtils.unrollGeometries( (Geometry) roiParameter.getValue()); // may throw if format not correct } catch (IllegalArgumentException ex) { throw new CannotCropException( Errors.format(ErrorKeys.ILLEGAL_ARGUMENT_$2, PARAMNAME_ROI, ex.getMessage()), ex); } // Setting a GeneralEnvelope from ROI if needed if (cropRoi != null && cropEnvelope == null) { Envelope e2d = JTS.getEnvelope2D(cropRoi.getEnvelopeInternal(), source.getCoordinateReferenceSystem()); cropEnvelope = new GeneralEnvelope(e2d); } // ///////////////////////////////////////////////////////////////////// // // Initialization // // We take the crop envelope and the source envelope then we check their // crs and we also check if they ever overlap. // // ///////////////////////////////////////////////////////////////////// // envelope of the source coverage final Envelope2D sourceEnvelope = source.getEnvelope2D(); // crop envelope Envelope2D destinationEnvelope = new Envelope2D(cropEnvelope); CoordinateReferenceSystem sourceCRS = sourceEnvelope.getCoordinateReferenceSystem(); CoordinateReferenceSystem destinationCRS = destinationEnvelope.getCoordinateReferenceSystem(); if (destinationCRS == null) { // Do not change the user provided object - clone it first. final Envelope2D ge = new Envelope2D(destinationEnvelope); destinationCRS = source.getCoordinateReferenceSystem2D(); ge.setCoordinateReferenceSystem(destinationCRS); destinationEnvelope = ge; } // // // // Source and destination crs must be equals // // // if (!CRS.equalsIgnoreMetadata(sourceCRS, destinationCRS)) { throw new CannotCropException( Errors.format( ErrorKeys.MISMATCHED_ENVELOPE_CRS_$2, sourceCRS.getName().getCode(), destinationCRS.getName().getCode())); } if (cropRoi != null) { // TODO: check ROI SRID } // // // // Check the intersection and, if needed, do the crop operation. // // // final GeneralEnvelope intersectionEnvelope = new GeneralEnvelope((Envelope) destinationEnvelope); intersectionEnvelope.setCoordinateReferenceSystem(source.getCoordinateReferenceSystem()); // intersect the envelopes intersectionEnvelope.intersect(sourceEnvelope); if (intersectionEnvelope.isEmpty()) throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP)); // intersect the ROI with the intersection envelope and throw an error if they do not intersect if (cropRoi != null) { final Geometry jis = JTS.toGeometry( (com.vividsolutions.jts.geom.Envelope) new ReferencedEnvelope(intersectionEnvelope)); if (!IntersectUtils.intersects(cropRoi, jis)) throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP)); } // // // // Get the grid-to-world transform by keeping into account translation // of grid geometry constructor for respecting OGC PIXEL-IS-CENTER // ImageDatum assumption. // // // final AffineTransform sourceCornerGridToWorld = (AffineTransform) ((GridGeometry2D) source.getGridGeometry()).getGridToCRS(PixelInCell.CELL_CORNER); // // // // I set the tolerance as half the scale factor of the grid-to-world // transform. This should more or less means in most cases "don't bother // to crop if the new envelope is as close to the old one that we go // deep under pixel size." // // // final double tolerance = XAffineTransform.getScale(sourceCornerGridToWorld); if (cropRoi != null || !intersectionEnvelope.equals(sourceEnvelope, tolerance / 2.0, false)) { cropEnvelope = intersectionEnvelope.clone(); return buildResult( cropEnvelope, cropRoi, roiTolerance, forceMosaic, (hints instanceof Hints) ? (Hints) hints : new Hints(hints), source, sourceCornerGridToWorld); } else { // // // // Note that in case we don't crop at all, WE DO NOT UPDATE the // envelope. If we did we might end up doing multiple successive // crop without actually cropping the image but, still, we would // shrink the envelope each time. Just think about having a loop // that crops recursively the same coverage specifying each time an // envelope whose URC is only a a scale quarter close to the LLC of // the old one. We would never crop the raster but we would modify // the grid-to-world transform each time. // // // return source; } }
@Override protected Product readProductNodesImpl() throws IOException { final String s = getInput().toString(); final File file0 = new File(s); final File dir = file0.getParentFile(); final S2FilenameInfo fni0 = S2FilenameInfo.create(file0.getName()); if (fni0 == null) { throw new IOException(); } Header metadataHeader = null; final Map<Integer, BandInfo> fileMap = new HashMap<Integer, BandInfo>(); if (dir != null) { File[] files = dir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(Sentinel2ProductReaderPlugIn.JP2_EXT); } }); if (files != null) { for (File file : files) { int bandIndex = fni0.getBand(file.getName()); if (bandIndex >= 0 && bandIndex < WAVEBAND_INFOS.length) { final S2WavebandInfo wavebandInfo = WAVEBAND_INFOS[bandIndex]; BandInfo bandInfo = new BandInfo( file, bandIndex, wavebandInfo, imageLayouts[wavebandInfo.resolution.id]); fileMap.put(bandIndex, bandInfo); } } } File[] metadataFiles = dir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("MTD_") && name.endsWith(".xml"); } }); if (metadataFiles != null && metadataFiles.length > 0) { File metadataFile = metadataFiles[0]; try { metadataHeader = Header.parseHeader(metadataFile); } catch (JDOMException e) { BeamLogManager.getSystemLogger() .warning("Failed to parse metadata file: " + metadataFile); } } else { BeamLogManager.getSystemLogger().warning("No metadata file found"); } } final ArrayList<Integer> bandIndexes = new ArrayList<Integer>(fileMap.keySet()); Collections.sort(bandIndexes); if (bandIndexes.isEmpty()) { throw new IOException("No valid bands found."); } String prodType = "S2_MSI_" + fni0.procLevel; final Product product = new Product( String.format("%s_%s_%s", prodType, fni0.orbitNo, fni0.tileId), prodType, imageLayouts[S2Resolution.R10M.id].width, imageLayouts[S2Resolution.R10M.id].height); try { product.setStartTime(ProductData.UTC.parse(fni0.start, "yyyyMMddHHmmss")); } catch (ParseException e) { // warn } try { product.setEndTime(ProductData.UTC.parse(fni0.stop, "yyyyMMddHHmmss")); } catch (ParseException e) { // warn } if (metadataHeader != null) { SceneDescription sceneDescription = SceneDescription.create(metadataHeader); int tileIndex = sceneDescription.getTileIndex(fni0.tileId); Envelope2D tileEnvelope = sceneDescription.getTileEnvelope(tileIndex); Header.Tile tile = metadataHeader.getTileList().get(tileIndex); try { product.setGeoCoding( new CrsGeoCoding( tileEnvelope.getCoordinateReferenceSystem(), imageLayouts[S2Resolution.R10M.id].width, imageLayouts[S2Resolution.R10M.id].height, tile.tileGeometry10M.upperLeftX, tile.tileGeometry10M.upperLeftY, tile.tileGeometry10M.xDim, -tile.tileGeometry10M.yDim, 0.0, 0.0)); } catch (FactoryException e) { // todo - handle e } catch (TransformException e) { // todo - handle e } } for (Integer bandIndex : bandIndexes) { final BandInfo bandInfo = fileMap.get(bandIndex); final Band band = product.addBand(bandInfo.wavebandInfo.bandName, ProductData.TYPE_UINT16); band.setSpectralWavelength((float) bandInfo.wavebandInfo.centralWavelength); band.setSpectralBandwidth((float) bandInfo.wavebandInfo.bandWidth); band.setSpectralBandIndex(bandIndex); band.setSourceImage(new DefaultMultiLevelImage(new Jp2MultiLevelSource(bandInfo))); } product.setNumResolutionLevels(imageLayouts[0].numResolutions); return product; }
/** * @see net.refractions.udig.render.internal.wmsc.basic#renderTile(Graphics2D graphics, WMTTile * tile, CoordinateReferenceSystem crs, RasterSymbolizer style) * @param graphics * @param tile * @param style * @throws FactoryException * @throws TransformException * @throws RenderException */ private void renderTile( Graphics2D graphics, WMTTile tile, RasterSymbolizer style, WMTRenderJob renderJob) throws Exception { if (tile == null || tile.getBufferedImage() == null) { return; } // create a gridcoverage from the tile image GridCoverageFactory factory = new GridCoverageFactory(); // get the tile bounds in the CRS the tiles were drawn in ReferencedEnvelope tileBndsMercatorRef = renderJob.projectTileToTileProjectedCrs(tile.getExtent()); GridCoverage2D coverage = (GridCoverage2D) factory.create( "GridCoverage", tile.getBufferedImage(), tileBndsMercatorRef); // $NON-NLS-1$ Envelope2D coveragebounds = coverage.getEnvelope2D(); // bounds of tile ReferencedEnvelope bnds = new ReferencedEnvelope( coveragebounds.getMinX(), coveragebounds.getMaxX(), coveragebounds.getMinY(), coveragebounds.getMaxY(), renderJob.getCrsTilesProjected()); // reproject tile bounds to map CRS bnds = renderJob.projectTileProjectedToMapCrs(bnds); // determine screen coordinates of tiles Point upperLeft = getContext().worldToPixel(new Coordinate(bnds.getMinX(), bnds.getMinY())); Point bottomRight = getContext().worldToPixel(new Coordinate(bnds.getMaxX(), bnds.getMaxY())); Rectangle tileSize = new Rectangle(upperLeft); tileSize.add(bottomRight); // render try { CoordinateReferenceSystem crs = getContext().getCRS(); AffineTransform worldToScreen = RendererUtilities.worldToScreenTransform(bnds, tileSize, crs); GridCoverageRenderer paint = new GridCoverageRenderer(crs, bnds, tileSize, worldToScreen); paint.paint(graphics, coverage, style); if (TESTING) { // if(true){ /* for testing draw border around tiles */ graphics.setColor(Color.BLACK); graphics.drawLine( (int) tileSize.getMinX(), (int) tileSize.getMinY(), (int) tileSize.getMinX(), (int) tileSize.getMaxY()); graphics.drawLine( (int) tileSize.getMinX(), (int) tileSize.getMinY(), (int) tileSize.getMaxX(), (int) tileSize.getMinY()); graphics.drawLine( (int) tileSize.getMaxX(), (int) tileSize.getMinY(), (int) tileSize.getMaxX(), (int) tileSize.getMaxY()); graphics.drawLine( (int) tileSize.getMinX(), (int) tileSize.getMaxY(), (int) tileSize.getMaxX(), (int) tileSize.getMaxY()); graphics.drawString( tile.getId(), ((int) tileSize.getMaxX() - 113), ((int) tileSize.getMaxY() - 113)); } } catch (Throwable t) { WMTPlugin.log("Error Rendering tile. Painting Tile " + tile.getId(), t); // $NON-NLS-1$ } }
public void testTest1() throws Exception { double cellSize = 0.000249; Point _pt = (new GeometryFactory()).createPoint(new Coordinate(80.333326615, 41.826389655)); Envelope2D _e = new Envelope2D(null, _pt.getX(), _pt.getY(), cellSize, cellSize); System.out.println(_e.getX()); System.out.println(_e.getY()); System.out.println(_e.getWidth()); System.out.println(_e.getHeight()); String _wkt = "PROJCS[\"Asia_North_Albers_Equal_Area_Conic\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Albers\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",95.0],PARAMETER[\"Standard_Parallel_1\",15.0],PARAMETER[\"Standard_Parallel_2\",65.0],PARAMETER[\"Latitude_Of_Origin\",30.0],UNIT[\"Meter\",1.0]]"; CoordinateReferenceSystem _sourcePrj = CRS.decode("EPSG:4326", true); // CoordinateReferenceSystem _targetPrj = CRS.decode("EPSG:21416"); CoordinateReferenceSystem _targetPrj = CRS.parseWKT(_wkt); double _pixelArea = (new ProjectTransformModel(_sourcePrj, _targetPrj)) .calculate( Utilities.covertEnvelope2D( new Envelope2D(null, _pt.getX(), _pt.getY(), cellSize, cellSize))) .getArea(); double _pixelLen1 = (new ProjectTransformModel(_sourcePrj, _targetPrj)) .calculate( (new GeometryFactory()) .createLineString( new Coordinate[] { new Coordinate(80.333326615, 41.826389655), new Coordinate(80.333326615 + cellSize, 41.826389655) })) .getLength(); double _pixelLen2 = (new ProjectTransformModel(_sourcePrj, _targetPrj)) .calculate( (new GeometryFactory()) .createLineString( new Coordinate[] { new Coordinate(80.333326615, 41.826389655), new Coordinate(80.333326615, 41.826389655 + cellSize) })) .getLength(); // double _pixelArea = (new ProjectTransformModel("EPSG:4326", // "EPSG:32644")).calculate(Utilities.covertEnvelope2D(new Envelope2D(null, _pt.getX(), // _pt.getY(), cellSize, cellSize))).getArea(); System.out.println(_pixelArea); System.out.println(_pixelLen1); System.out.println(_pixelLen2); // Polygon _box = Utilities.covertEnvelope2D(new Envelope2D(null, _pt.getX(), _pt.getY(), // cellSize, cellSize)); Polygon _box = (Polygon) (new ProjectTransformModel(_sourcePrj, _targetPrj)) .calculate( Utilities.covertEnvelope2D( new Envelope2D(null, _pt.getX(), _pt.getY(), cellSize, cellSize))); SimpleFeatureTypeBuilder _builder = new SimpleFeatureTypeBuilder(); _builder.setName("project1.shp"); _builder.add("Shape", Polygon.class); _builder.add("Test", Double.class); FeatureType _ft = _builder.buildFeatureType(); FeatureCollection _fc = (CommonFactoryFinder.getFeatureCollections(GeoTools.getDefaultHints()).newCollection()); _fc.add(SimpleFeatureBuilder.build((SimpleFeatureType) _ft, new Object[] {_box, 10}, null)); ShapefileDataStore _fs = new ShapefileDataStore(new File("D:\\Temp\\data3\\20081010\\shp\\test.shp").toURL()); _fs.createSchema((SimpleFeatureType) _ft); FeatureStore _store = (FeatureStore) _fs.getFeatureSource(); _store.addFeatures(_fc); }