@Test public void testMissingNullValuesInCoverageDimensions() throws IOException { CoverageInfo ci = getCatalog().getCoverageByName(getLayerId(MockData.TASMANIA_DEM)); List<CoverageDimensionInfo> dimensions = ci.getDimensions(); // legacy layers have no null value list dimensions.get(0).getNullValues().clear(); getCatalog().save(ci); // and now go back and ask for the reader ci = getCatalog().getCoverageByName(getLayerId(MockData.TASMANIA_DEM)); GridCoverageReader reader = ci.getGridCoverageReader(null, null); GridCoverage2D gc = null; try { // check that we maintain the native info if we don't have any gc = (GridCoverage2D) reader.read(null); assertEquals(-9999d, (Double) gc.getProperty("GC_NODATA"), 0d); } finally { if (gc != null) { RenderedImage ri = gc.getRenderedImage(); if (gc instanceof GridCoverage2D) { ((GridCoverage2D) gc).dispose(true); } if (ri instanceof PlanarImage) { ImageUtilities.disposePlanarImageChain((PlanarImage) ri); } } } }
public void testRasterReaderResOnly() throws Exception { double[][] mapData1 = new double[][] { // {NaN, 850.0, 900.0, 1200.0, 1500.0}, // {410.0, 700.0, 800.0, 490.0, 1500.0}, // {600.0, 750.0, 770.0, 1000.0, 1500.0}, // {910.0, 1001.0, 1200.0, 1300.0, 1500.0} // }; double[][] mapData2 = new double[][] { // {800.0, 1000.0, 1200.0, 1300.0, 1450.0}, // {500.0, 700.0, 800.0, 900.0, 1100.0}, // {450.0, 430.0, 600.0, 800.0, 450.0}, // {600.0, 750.0, 780.0, 1000.0, 1250.0} // }; double xres = 60.0; double yres = 60.0; OmsRasterReader reader = new OmsRasterReader(); reader.pXres = xres; reader.pYres = yres; reader.file = arcPath; reader.process(); GridCoverage2D readCoverage = reader.outRaster; checkMatrixEqual(readCoverage.getRenderedImage(), mapData1); reader = new OmsRasterReader(); reader.pXres = xres; reader.pYres = yres; reader.file = grassPath; reader.process(); readCoverage = reader.outRaster; checkMatrixEqual(readCoverage.getRenderedImage(), mapData2); }
public void handleSampleDimensionNilValues(GridCoverage2D gc2d, double[] nodataValues) { start("swe:nilValues"); start("swe:NilValues"); if (nodataValues != null && nodataValues.length > 0) { for (double nodata : nodataValues) { final AttributesImpl nodataAttr = new AttributesImpl(); nodataAttr.addAttribute( "", "reason", "reason", "", "http://www.opengis.net/def/nil/OGC/0/unknown"); element("swe:nilValue", String.valueOf(nodata), nodataAttr); } } else if (gc2d != null) { // do we have already a a NO_DATA value at hand? if (gc2d.getProperties().containsKey("GC_NODATA")) { String nodata = (String) gc2d.getProperties().get("GC_NODATA"); // TODO test me final AttributesImpl nodataAttr = new AttributesImpl(); nodataAttr.addAttribute( "", "reason", "reason", "", "http://www.opengis.net/def/nil/OGC/0/unknown"); element("swe:nilValue", nodata, nodataAttr); } else { // let's suggest some meaningful value from the data type of the underlying image Number nodata = CoverageUtilities.suggestNoDataValue( gc2d.getRenderedImage().getSampleModel().getDataType()); final AttributesImpl nodataAttr = new AttributesImpl(); nodataAttr.addAttribute( "", "reason", "reason", "", "http://www.opengis.net/def/nil/OGC/0/unknown"); element("swe:nilValue", nodata.toString(), nodataAttr); } } end("swe:NilValues"); end("swe:nilValues"); }
private void assertItalyFootprints() throws NoSuchAuthorityCodeException, FactoryException, IOException { GridCoverage2D coverage = readCoverage(); // RenderedImageBrowser.showChain(coverage.getRenderedImage()); // System.in.read(); // check the footprints have been applied by pocking the output image byte[] pixel = new byte[3]; // Mar Ionio, should be black coverage.evaluate(new DirectPosition2D(16.87, 40.19), pixel); assertEquals(0, pixel[0]); assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); // Golfo di La Spezia, should be black coverage.evaluate(new DirectPosition2D(9.12, 44.25), pixel); assertEquals(0, pixel[0]); assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); // Sardinia, not black coverage.evaluate(new DirectPosition2D(9, 40), pixel); assertTrue(pixel[0] + pixel[1] + pixel[2] > 0); // Piedmont, not black coverage.evaluate(new DirectPosition2D(8, 45), pixel); assertTrue(pixel[0] + pixel[1] + pixel[2] > 0); }
public static GridCoverage2D removeNovalues(GridCoverage2D geodata) { // need to adapt it, for now do it dirty HashMap<String, Double> params = getRegionParamsFromGridCoverage(geodata); int height = params.get(ROWS).intValue(); int width = params.get(COLS).intValue(); WritableRaster tmpWR = createDoubleWritableRaster(width, height, null, null, null); WritableRandomIter tmpIter = RandomIterFactory.createWritable(tmpWR, null); RenderedImage readRI = geodata.getRenderedImage(); RandomIter readIter = RandomIterFactory.create(readRI, null); for (int r = 0; r < height; r++) { for (int c = 0; c < width; c++) { double value = readIter.getSampleDouble(c, r, 0); if (Double.isNaN(value) || Float.isNaN((float) value) || Math.abs(value - -9999.0) < .0000001) { tmpIter.setSample(c, r, 0, Double.NaN); } else { tmpIter.setSample(c, r, 0, value); } } } geodata = buildCoverage("newcoverage", tmpWR, params, geodata.getCoordinateReferenceSystem()); return geodata; }
public void testCoverageContents() throws Exception { final Long processId = issueProcessAndWaitForTermination(); final String request = RESTLET_PATH + "/" + processId.longValue(); final MockHttpServletResponse response = getAsServletResponse(request); assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus())); assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType())); final ByteArrayInputStream responseStream = getBinaryInputStream(response); File dataDirectoryRoot = super.getTestData().getDataDirectoryRoot(); File file = new File(dataDirectoryRoot, "testCoverageContents.zip"); super.getTestData().copyTo(responseStream, file.getName()); ZipFile zipFile = new ZipFile(file); try { // TODO: change this expectation once we normalize the raster file name String rasterName = RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff"; ZipEntry nextEntry = zipFile.getEntry(rasterName); assertNotNull(nextEntry); InputStream coverageInputStream = zipFile.getInputStream(nextEntry); // Use a file, geotiffreader might not work well reading out of a plain input stream File covFile = new File(file.getParentFile(), "coverage.tiff"); IOUtils.copy(coverageInputStream, covFile); GeoTiffReader geoTiffReader = new GeoTiffReader(covFile); GridCoverage2D coverage = geoTiffReader.read(null); CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem(); assertEquals(CRS.decode("EPSG:4326", true), crs); } finally { zipFile.close(); } }
@Test public void testElevationSecond() throws Exception { String request = getWaterTempElevationRequest("100.0"); MockHttpServletResponse response = postAsServletResponse("wcs", request); assertEquals("image/tiff", response.getContentType()); // save File tiffFile = File.createTempFile("wcs", "", new File("target")); IOUtils.copy(getBinaryInputStream(response), new FileOutputStream(tiffFile)); // make sure we can read the coverage back GeoTiffReader reader = new GeoTiffReader(tiffFile); GridCoverage2D result = reader.read(null); /* gdallocationinfo NCOM_wattemp_100_20081101T0000000_12.tiff 10 10 Report: Location: (10P,10L) Band 1: Value: 13.337999683572 */ // check a pixel double[] pixel = new double[1]; result.getRenderedImage().getData().getPixel(10, 10, pixel); assertEquals(13.337999683572, pixel[0], 1e-6); tiffFile.delete(); }
public static HashMap<String, Double> getRegionParamsFromGridCoverage( GridCoverage2D gridCoverage) { HashMap<String, Double> envelopeParams = new HashMap<String, Double>(); Envelope envelope = gridCoverage.getEnvelope(); DirectPosition lowerCorner = envelope.getLowerCorner(); double[] westSouth = lowerCorner.getCoordinate(); DirectPosition upperCorner = envelope.getUpperCorner(); double[] eastNorth = upperCorner.getCoordinate(); GridGeometry2D gridGeometry = gridCoverage.getGridGeometry(); GridEnvelope2D gridRange = gridGeometry.getGridRange2D(); int height = gridRange.height; int width = gridRange.width; AffineTransform gridToCRS = (AffineTransform) gridGeometry.getGridToCRS(); double xRes = XAffineTransform.getScaleX0(gridToCRS); double yRes = XAffineTransform.getScaleY0(gridToCRS); envelopeParams.put(NORTH, eastNorth[1]); envelopeParams.put(SOUTH, westSouth[1]); envelopeParams.put(WEST, westSouth[0]); envelopeParams.put(EAST, eastNorth[0]); envelopeParams.put(XRES, xRes); envelopeParams.put(YRES, yRes); envelopeParams.put(ROWS, (double) height); envelopeParams.put(COLS, (double) width); return envelopeParams; }
/** * Tests the "Resample" operation with a stereographic coordinate system. * * @throws FactoryException * @throws NoSuchAuthorityCodeException */ @Test public void testReproject() throws NoSuchAuthorityCodeException, FactoryException { // do it again, make sure the image does not turn black since GridCoverage2D coverage_ = project(ushortCoverage, CRS.parseWKT(GOOGLE_MERCATOR_WKT), null, "nearest", null, true); // reproject the ushort and check that things did not go bad, that is it turned black coverage_ = (GridCoverage2D) Operations.DEFAULT.extrema(coverage_); Object minimums = coverage_.getProperty(Extrema.GT_SYNTHETIC_PROPERTY_MINIMUM); Assert.assertTrue(minimums instanceof double[]); final double[] mins = (double[]) minimums; Object maximums = coverage_.getProperty(Extrema.GT_SYNTHETIC_PROPERTY_MAXIMUM); Assert.assertTrue(maximums instanceof double[]); final double[] max = (double[]) maximums; boolean fail = true; for (int i = 0; i < mins.length; i++) if (mins[i] != max[i] && max[i] > 0) fail = false; Assert.assertFalse("Reprojection failed", fail); // exception in case the target crs does not comply with the target gg crs try { // we supplied both crs and target gg in different crs, we get an exception backS assertEquals( "Warp", showProjected( coverage, CRS.parseWKT(GOOGLE_MERCATOR_WKT), coverage.getGridGeometry(), null, true)); Assert.assertTrue( "We should not be allowed to set different crs for target crs and target gg", false); } catch (Exception e) { // ok! } }
private void checkTimeCurrent(MockHttpServletResponse response) throws IOException, FileNotFoundException, DataSourceException { // save File tiffFile = File.createTempFile("wcs", "", new File("target")); IOUtils.copy(getBinaryInputStream(response), new FileOutputStream(tiffFile)); // make sure we can read the coverage back GeoTiffReader reader = new GeoTiffReader(tiffFile); GridCoverage2D result = reader.read(null); /* gdallocationinfo NCOM_wattemp_000_20081101T0000000_12.tiff 10 10 Report: Location: (10P,10L) Band 1: Value: 18.2849999185419 */ // check a pixel double[] pixel = new double[1]; result.getRenderedImage().getData().getPixel(10, 10, pixel); assertEquals(18.2849999185419, pixel[0], 1e-6); tiffFile.delete(); }
@Test public void testGoogleWorld() throws Exception { File world = TestData.copy(this, "geotiff/world.tiff"); RenderedImage image = ImageIO.read(world); final CoordinateReferenceSystem wgs84 = CRS.decode("EPSG:4326", true); Envelope2D envelope = new Envelope2D(wgs84, -180, -90, 360, 180); GridCoverage2D gcFullWorld = new GridCoverageFactory().create("world", image, envelope); // crop, we cannot reproject it fully to the google projection final Envelope2D cropEnvelope = new Envelope2D(wgs84, -180, -80, 360, 160); GridCoverage2D gcCropWorld = (GridCoverage2D) Operations.DEFAULT.crop(gcFullWorld, cropEnvelope); // resample Hints.putSystemDefault(Hints.RESAMPLE_TOLERANCE, 0d); GridCoverage2D gcResampled = (GridCoverage2D) Operations.DEFAULT.resample( gcCropWorld, CRS.decode("EPSG:3857"), null, Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); File expected = new File("src/test/resources/org/geotools/image/test-data/google-reproject.png"); // allow one row of difference ImageAssert.assertEquals(expected, gcResampled.getRenderedImage(), 600); }
@Test public void NetCDFProjectedEnvelopeTest() throws NoSuchAuthorityCodeException, FactoryException, IOException, ParseException { File mosaic = new File(TestData.file(this, "."), "NetCDFProjection"); if (mosaic.exists()) { FileUtils.deleteDirectory(mosaic); } assertTrue(mosaic.mkdirs()); File file = TestData.file(this, "wind.nc"); FileUtils.copyFileToDirectory(file, mosaic); file = new File(mosaic, "wind.nc"); // Get format final NetCDFReader reader = new NetCDFReader(file, null); try { String[] names = reader.getGridCoverageNames(); String coverageName = names[0]; // subsetting the envelope final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(coverageName); final CoordinateReferenceSystem epsg3857 = CRS.decode("EPSG:3857", true); final GeneralEnvelope projectedEnvelope = CRS.transform(originalEnvelope, epsg3857); gg.setValue( new GridGeometry2D(new GridEnvelope2D(new Rectangle(0, 0, 30, 30)), projectedEnvelope)); GeneralParameterValue[] values = new GeneralParameterValue[] {gg}; GridCoverage2D coverage = reader.read(coverageName, values); // reader doesn't perform reprojection. It simply transforms reprojected envelope // to native envelope so BBOX and CRS should be wgs84 CoordinateReferenceSystem coverageCRS = coverage.getCoordinateReferenceSystem(); final int code = CRS.lookupEpsgCode(coverageCRS, false); assertEquals(4326, code); Extent extent = coverageCRS.getDomainOfValidity(); Collection<? extends GeographicExtent> geoElements = extent.getGeographicElements(); GeographicExtent geographicExtent = geoElements.iterator().next(); GeographicBoundingBoxImpl impl = (GeographicBoundingBoxImpl) geographicExtent; // Getting the coverage Envelope for coordinates check Envelope coverageEnvelope = coverage.getEnvelope(); assertTrue(impl.getEastBoundLongitude() >= coverageEnvelope.getMaximum(0)); assertTrue(impl.getWestBoundLongitude() <= coverageEnvelope.getMinimum(0)); assertTrue(impl.getNorthBoundLatitude() >= coverageEnvelope.getMaximum(1)); assertTrue(impl.getSouthBoundLatitude() <= coverageEnvelope.getMinimum(1)); } catch (Throwable t) { throw new RuntimeException(t); } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } } }
/** * Test using this netcdf image: data: LAI= 20,20,20,30,30, 40,40,40,50,50, 60,60,60,70,70, * 80,80,80,90,90; lon= 10,15,20,25,30; lat= 70,60,50,40; * * @throws IOException */ @Test public void testHDF5Image() throws IOException, FactoryException { final File testURL = TestData.file(this, "2DLatLonCoverage.nc"); // Get format // final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(testURL.toURI().toURL(), null); final NetCDFReader reader = new NetCDFReader(testURL, null); // assertNotNull(format); assertNotNull(reader); try { String[] names = reader.getGridCoverageNames(); assertNotNull(names); assertEquals(2, names.length); assertEquals("ROOT/LEVEL1/V2", names[1]); GridCoverage2D grid = reader.read("ROOT/LAI", null); assertNotNull(grid); byte[] byteValue = grid.evaluate(new DirectPosition2D(DefaultGeographicCRS.WGS84, 12, 70), new byte[1]); assertEquals(20, byteValue[0]); byteValue = grid.evaluate(new DirectPosition2D(DefaultGeographicCRS.WGS84, 23, 40), new byte[1]); assertEquals(90, byteValue[0]); } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } } }
@Test public void testInsetsBorder() throws Exception { // copy the footprints mosaic over FileUtils.copyDirectory(footprintsSource, testMosaic); Properties p = new Properties(); p.put(MultiLevelROIProviderFactory.INSET_PROPERTY, "0.1"); saveFootprintProperties(p); GridCoverage2D coverage = readCoverage(); // check the footprints have been applied by pocking the output image byte[] pixel = new byte[3]; // Close to San Marino, black if we have the insets coverage.evaluate(new DirectPosition2D(12.54, 44.03), pixel); assertEquals(0, pixel[0]); assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); // Golfo di La Spezia, should be black coverage.evaluate(new DirectPosition2D(9.12, 44.25), pixel); assertEquals(0, pixel[0]); assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); // Sardinia, not black coverage.evaluate(new DirectPosition2D(9, 40), pixel); assertTrue(pixel[0] + pixel[1] + pixel[2] > 0); // Piedmont, not black coverage.evaluate(new DirectPosition2D(8, 45), pixel); assertTrue(pixel[0] + pixel[1] + pixel[2] > 0); disposeCoverage(coverage); }
public CoverageResponse update(CoverageUpdateRequest writeRequest, ProgressListener progress) { ensureNotDisposed(); access.globalLock.writeLock().lock(); final DefaultCoverageResponseImpl response = new DefaultCoverageResponseImpl(); response.setRequest(writeRequest); try { // reader final GeoTiffWriter writer = new GeoTiffWriter(this.access.input); // get the data final GridCoverage2D coverage = (GridCoverage2D) writeRequest.getData().iterator().next(); writer.write(coverage, null); writer.dispose(); response.addResult(coverage); response.setStatus(Status.SUCCESS); // update the access Info info = getInfo(null); info.setExtent((GeneralEnvelope) coverage.getGridGeometry().getEnvelope()); info.setGeometry(coverage.getGridGeometry()); } catch (Throwable e) { response.addException(new GeoTiffException(null, "IO error", e)); } finally { this.access.globalLock.writeLock().unlock(); } return response; }
@Override public CloseableIterator<GeoWaveData<GridCoverage>> toGeoWaveData( final File input, final Collection<ByteArrayId> primaryIndexIds, final String globalVisibility) { final AbstractGridFormat format = GridFormatFinder.findFormat(input); final GridCoverage2DReader reader = format.getReader(input); if (reader == null) { LOGGER.error("Unable to get reader instance, getReader returned null"); return new Wrapper(Collections.emptyIterator()); } try { final GridCoverage2D coverage = reader.read(null); if (coverage != null) { final Map<String, String> metadata = new HashMap<String, String>(); final String coverageName = coverage.getName().toString(); final String[] mdNames = reader.getMetadataNames(coverageName); if ((mdNames != null) && (mdNames.length > 0)) { for (final String mdName : mdNames) { metadata.put(mdName, reader.getMetadataValue(coverageName, mdName)); } } final RasterDataAdapter adapter = new RasterDataAdapter( input.getName(), metadata, coverage, optionProvider.getTileSize(), optionProvider.isBuildPyramid()); final List<GeoWaveData<GridCoverage>> coverages = new ArrayList<GeoWaveData<GridCoverage>>(); coverages.add(new GeoWaveData<GridCoverage>(adapter, primaryIndexIds, coverage)); return new Wrapper(coverages.iterator()) { @Override public void close() throws IOException { reader.dispose(); } }; } else { LOGGER.warn( "Null grid coverage from file '" + input.getAbsolutePath() + "' for discovered geotools format '" + format.getName() + "'"); } } catch (final IOException e) { LOGGER.warn( "Unable to read grid coverage of file '" + input.getAbsolutePath() + "' for discovered geotools format '" + format.getName() + "'", e); } return new Wrapper(Collections.emptyIterator()); }
/** * Dispose the provided coverage for good. * * @param coverage */ private void disposeCoverage(GridCoverage2D coverage) { if (coverage == null) { return; } final RenderedImage im = coverage.getRenderedImage(); ImageUtilities.disposePlanarImageChain(PlanarImage.wrapRenderedImage(im)); coverage.dispose(true); }
/** * Creates a {@link SimpleFeatureType} that exposes a coverage as a collections of feature points, * mapping the centre of each pixel as a point plus all the bands as attributes. * * <p>The FID is the long that combines x+y*width. * * @param gc2d the {@link GridCoverage2D} to wrap. * @param geometryClass the class for the geometry. * @return a {@link SimpleFeatureType} or <code>null</code> in case we are unable to wrap the * coverage */ public static SimpleFeatureType createFeatureType( final GridCoverage2D gc2d, final Class<? extends Geometry> geometryClass) { // checks Utilities.ensureNonNull("gc2d", gc2d); // building a feature type for this coverage final SimpleFeatureTypeBuilder ftBuilder = new SimpleFeatureTypeBuilder(); ftBuilder.setName(gc2d.getName().toString()); ftBuilder.setNamespaceURI("http://www.geotools.org/"); // CRS ftBuilder.setCRS(gc2d.getCoordinateReferenceSystem2D()); // ftBuilder.setCRS(DefaultEngineeringCRS.GENERIC_2D); // TYPE is as follows the_geom | band ftBuilder.setDefaultGeometry("the_geom"); ftBuilder.add("the_geom", geometryClass); if (!geometryClass.equals(Point.class)) { ftBuilder.add("value", Double.class); } else { // get sample type on bands final GridSampleDimension[] sampleDimensions = gc2d.getSampleDimensions(); for (GridSampleDimension sd : sampleDimensions) { final SampleDimensionType sdType = sd.getSampleDimensionType(); final int dataBuffType = TypeMap.getDataBufferType(sdType); // TODO I think this should be a public utility inside the FeatureUtilities class @SuppressWarnings("rawtypes") final Class bandClass; switch (dataBuffType) { case DataBuffer.TYPE_BYTE: bandClass = Byte.class; break; case DataBuffer.TYPE_DOUBLE: bandClass = Double.class; break; case DataBuffer.TYPE_FLOAT: bandClass = Float.class; break; case DataBuffer.TYPE_INT: bandClass = Integer.class; break; case DataBuffer.TYPE_SHORT: case DataBuffer.TYPE_USHORT: bandClass = Short.class; break; case DataBuffer.TYPE_UNDEFINED: default: return null; } ftBuilder.add(sd.getDescription().toString(), bandClass); } } return ftBuilder.buildFeatureType(); }
/** * Tests the "Multiply" operation. * * @throws IOException */ @Test public void testMultiply() throws IOException { final GridCoverage2D shortCoverage = EXAMPLES.get(5); final GridCoverage2D floatCoverage = EXAMPLES.get(4); final GridCoverage2D result = doOp("Multiply", shortCoverage, floatCoverage); final RenderedImage image = result.getRenderedImage(); final RenderedImage extrema = ExtremaDescriptor.create(image, null, 1, 1, false, 1, null); double[][] minMax = (double[][]) extrema.getProperty("Extrema"); assertEquals(minMax[0][0], 0.0, DELTA); assertEquals(minMax[1][0], 6.5272192E7, DELTA); }
@Test public void testDomainSubsetRxRy() throws Exception { // get base coverage final GridCoverage baseCoverage = catalog.getCoverageByName(TASMANIA_BM.getLocalPart()).getGridCoverage(null, null); final AffineTransform2D expectedTx = (AffineTransform2D) baseCoverage.getGridGeometry().getGridToCRS(); final GeneralEnvelope originalEnvelope = (GeneralEnvelope) baseCoverage.getEnvelope(); final GeneralEnvelope newEnvelope = new GeneralEnvelope(originalEnvelope); newEnvelope.setEnvelope( originalEnvelope.getMinimum(0), originalEnvelope.getMaximum(1) - originalEnvelope.getSpan(1) / 2, originalEnvelope.getMinimum(0) + originalEnvelope.getSpan(0) / 2, originalEnvelope.getMaximum(1)); final MathTransform cornerWorldToGrid = PixelTranslation.translate(expectedTx, PixelInCell.CELL_CENTER, PixelInCell.CELL_CORNER); final GeneralGridEnvelope expectedGridEnvelope = new GeneralGridEnvelope( CRS.transform(cornerWorldToGrid.inverse(), newEnvelope), PixelInCell.CELL_CORNER, false); final StringBuilder envelopeBuilder = new StringBuilder(); envelopeBuilder.append(newEnvelope.getMinimum(0)).append(","); envelopeBuilder.append(newEnvelope.getMinimum(1)).append(","); envelopeBuilder.append(newEnvelope.getMaximum(0)).append(","); envelopeBuilder.append(newEnvelope.getMaximum(1)); Map<String, Object> raw = baseMap(); final String layerID = getLayerId(TASMANIA_BM); raw.put("sourcecoverage", layerID); raw.put("version", "1.0.0"); raw.put("format", "image/geotiff"); raw.put("BBox", envelopeBuilder.toString()); raw.put("crs", "EPSG:4326"); raw.put("resx", Double.toString(expectedTx.getScaleX())); raw.put("resy", Double.toString(Math.abs(expectedTx.getScaleY()))); final GridCoverage[] coverages = executeGetCoverageKvp(raw); final GridCoverage2D result = (GridCoverage2D) coverages[0]; assertTrue(coverages.length == 1); final AffineTransform2D tx = (AffineTransform2D) result.getGridGeometry().getGridToCRS(); assertEquals("resx", expectedTx.getScaleX(), tx.getScaleX(), 1E-6); assertEquals("resx", Math.abs(expectedTx.getScaleY()), Math.abs(tx.getScaleY()), 1E-6); final GridEnvelope gridEnvelope = result.getGridGeometry().getGridRange(); assertEquals("w", 180, gridEnvelope.getSpan(0)); assertEquals("h", 180, gridEnvelope.getSpan(1)); assertEquals("grid envelope", expectedGridEnvelope, gridEnvelope); // dispose CoverageCleanerCallback.disposeCoverage(baseCoverage); CoverageCleanerCallback.disposeCoverage(coverages[0]); }
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; }
/** * <strong>Cropping</strong><br> * The crop operation is responsible for selecting geographic subareas of the source coverage. * * @param coverage Coverage * @param sourceEnvelope GeneralEnvelope * @param sourceCRS CoordinateReferenceSystem * @param destinationEnvelopeInSourceCRS GeneralEnvelope * @return GridCoverage2D * @throws WcsException */ public static GridCoverage2D crop( final Coverage coverage, final GeneralEnvelope sourceEnvelope, final CoordinateReferenceSystem sourceCRS, final GeneralEnvelope destinationEnvelopeInSourceCRS, final Boolean conserveEnvelope) throws WcsException { // /////////////////////////////////////////////////////////////////// // // CROP // // // /////////////////////////////////////////////////////////////////// final GridCoverage2D croppedGridCoverage; // intersect the envelopes final GeneralEnvelope intersectionEnvelope = new GeneralEnvelope(destinationEnvelopeInSourceCRS); intersectionEnvelope.setCoordinateReferenceSystem(sourceCRS); intersectionEnvelope.intersect((GeneralEnvelope) sourceEnvelope); // dow we have something to show? if (intersectionEnvelope.isEmpty()) { throw new WcsException("The Intersection is null. Check the requested BBOX!"); } if (!intersectionEnvelope.equals((GeneralEnvelope) sourceEnvelope)) { // get the cropped grid geometry // final GridGeometry2D cropGridGeometry = getCroppedGridGeometry( // intersectionEnvelope, gridCoverage); /* Operations.DEFAULT.crop(coverage, intersectionEnvelope) */ final ParameterValueGroup param = (ParameterValueGroup) cropParams.clone(); param.parameter("Source").setValue(coverage); param.parameter("Envelope").setValue(intersectionEnvelope); // param.parameter("ConserveEnvelope").setValue(conserveEnvelope); croppedGridCoverage = (GridCoverage2D) cropFactory.doOperation(param, hints); } else { croppedGridCoverage = (GridCoverage2D) coverage; } // prefetch to be faster afterwards. // This step is important since at this stage we might be loading tiles // from disk croppedGridCoverage.prefetch(intersectionEnvelope.toRectangle2D()); return croppedGridCoverage; }
private void encodeAsDataBlocks(GridCoverage2D gc2d) { start("gml:DataBlock"); start("gml:rangeParameters"); end("gml:rangeParameters"); start("tupleList"); // walk through the coverage and spit it out! final RenderedImage raster = gc2d.getRenderedImage(); final int numBands = raster.getSampleModel().getNumBands(); final int dataType = raster.getSampleModel().getDataType(); final double[] valuesD = new double[numBands]; final int[] valuesI = new int[numBands]; RectIter iterator = RectIterFactory.create(raster, PlanarImage.wrapRenderedImage(raster).getBounds()); iterator.startLines(); while (!iterator.finishedLines()) { iterator.startPixels(); while (!iterator.finishedPixels()) { switch (dataType) { case DataBuffer.TYPE_BYTE: case DataBuffer.TYPE_INT: case DataBuffer.TYPE_SHORT: case DataBuffer.TYPE_USHORT: iterator.getPixel(valuesI); for (int i = 0; i < numBands; i++) { // spit out chars(String.valueOf(valuesI[i])); if (i + 1 < numBands) { chars(","); } } break; case DataBuffer.TYPE_DOUBLE: case DataBuffer.TYPE_FLOAT: iterator.getPixel(valuesD); for (int i = 0; i < numBands; i++) { // spit out chars(String.valueOf(valuesD[i])); if (i + 1 < numBands) { chars(","); } } break; default: break; } // space as sample separator chars(" "); iterator.nextPixel(); } iterator.nextLine(); chars("\n"); } end("tupleList"); end("gml:DataBlock"); }
public void testRasterReaderAll() throws Exception { OmsRasterReader reader = new OmsRasterReader(); reader.file = arcPath; reader.fileNovalue = -9999.0; reader.geodataNovalue = Double.NaN; reader.process(); GridCoverage2D readCoverage = reader.outRaster; checkMatrixEqual(readCoverage.getRenderedImage(), HMTestMaps.mapData); reader = new OmsRasterReader(); reader.file = grassPath; reader.fileNovalue = -9999.0; reader.geodataNovalue = Double.NaN; reader.process(); readCoverage = reader.outRaster; checkMatrixEqual(readCoverage.getRenderedImage(), HMTestMaps.mapData); }
public void testTca() throws Exception { HashMap<String, Double> envelopeParams = HMTestMaps.envelopeParams; CoordinateReferenceSystem crs = HMTestMaps.crs; double[][] flowData = HMTestMaps.flowData; GridCoverage2D flowCoverage = CoverageUtilities.buildCoverage("flow", flowData, envelopeParams, crs, true); OmsMarkoutlets moutlet = new OmsMarkoutlets(); moutlet.inFlow = flowCoverage; moutlet.pm = pm; moutlet.process(); GridCoverage2D markoutletCoverage = moutlet.outFlow; checkMatrixEqual(markoutletCoverage.getRenderedImage(), HMTestMaps.mflowData); }
public void testRasterReaderBoundsOnly() throws Exception { double[][] mapData = new double[][] { // {1000, 1000, 1200, 1250, 1300, 1350, 1450}, // {750, 850, 860, 900, 1000, 1200, 1250}, // {700, 750, 800, 850, 900, 1000, 1100}, // {650, 700, 750, 800, 850, 490, 450}, // {430, 500, 600, 700, 800, 500, 450}, // {700, 750, 760, 770, 850, 1000, 1150} // }; double n = 5140020.0; double s = 5139840.0; double w = 1640710.0; double e = 1640920.0; double xres = 30.0; double yres = 30.0; OmsRasterReader reader = new OmsRasterReader(); reader.file = arcPath; reader.pNorth = n; reader.pSouth = s; reader.pWest = w; reader.pEast = e; reader.pXres = xres; reader.pYres = yres; reader.process(); GridCoverage2D readCoverage = reader.outRaster; checkMatrixEqual(readCoverage.getRenderedImage(), mapData); reader = new OmsRasterReader(); reader.file = grassPath; reader.pNorth = n; reader.pSouth = s; reader.pWest = w; reader.pEast = e; reader.pXres = xres; reader.pYres = yres; reader.process(); readCoverage = reader.outRaster; checkMatrixEqual(readCoverage.getRenderedImage(), mapData); }
/** * Read data from a GRASS raster to be data of the layer. * * @param pm a progress monitor. * @param activeRegion the {@link JGrassRegion region} from which the data are read. * @param locationCrs the {@link CoordinateReferenceSystem} of the original GRASS data. * @return a {@link RandomIter} to iterate over the read data. * @throws IOException * @throws FactoryException * @throws TransformException */ public RandomIter getData( IProgressMonitorJGrass pm, JGrassRegion activeRegion, CoordinateReferenceSystem locationCrs) throws IOException, FactoryException, TransformException { File rasterFile = new File(rasterPaths[0]); // FIXME should be true to use rowcol for subsampling GrassCoverageReader tmp = new GrassCoverageReader(null, null, true, false, pm); tmp.setInput(rasterFile); GrassCoverageReadParam gcReadParam = new GrassCoverageReadParam(activeRegion); GridCoverage2D gridCoverage2D = tmp.read(gcReadParam); GridCoverage2D gridCoverage2DLatlong = (GridCoverage2D) Operations.DEFAULT.resample(gridCoverage2D, DefaultGeographicCRS.WGS84); RenderedImage renderedImage = gridCoverage2DLatlong.getRenderedImage(); RandomIter randomIter = RandomIterFactory.create(renderedImage, null); return randomIter; }
/** * Encodes the RangeType as per the GML spec of the provided {@link GridCoverage2D} * * <p>e.g.: * * <pre>{@code * <gmlcov:rangeType> * <swe:DataRecord> * <swe:field name="singleBand"> * <swe:Quantity definition="http://www.opengis.net/def/property/OGC/0/Radiance"> * <gml:description>Panchromatic Channel</gml:description> * <gml:name>single band</gml:name> * <swe:uom code="W/cm2"/> * <swe:constraint> * <swe:AllowedValues> * <swe:interval>0 255</swe:interval> * <swe:significantFigures>3</swe:significantFigures> * </swe:AllowedValues> * </swe:constraint> * </swe:Quantity> * </swe:field> * </swe:DataRecord> * </gmlcov:rangeType> * }</pre> * * @param gc2d the {@link GridCoverage2D} for which to encode the RangeType. */ public void handleRangeType(GridCoverage2D gc2d) { start("gml:rangeType"); start("swe:DataRecord"); // get bands final SampleDimension[] bands = gc2d.getSampleDimensions(); // handle bands for (SampleDimension sd : bands) { final AttributesImpl fieldAttr = new AttributesImpl(); fieldAttr.addAttribute( "", "name", "name", "", sd.getDescription().toString()); // TODO NCNAME? TODO Use Band[i] convention? start("swe:field", fieldAttr); start("swe:Quantity"); // Description start("swe:description"); chars(sd.getDescription().toString()); // TODO can we make up something better?? end("swe:description"); // UoM final AttributesImpl uomAttr = new AttributesImpl(); final Unit<?> uom = sd.getUnits(); uomAttr.addAttribute( "", "code", "code", "", uom == null ? "W.m-2.Sr-1" : UnitFormat.getInstance().format(uom)); start("swe:uom", uomAttr); end("swe:uom"); // constraint on values start("swe:constraint"); start("swe:AllowedValues"); handleSampleDimensionRange(sd); // TODO make this generic end("swe:AllowedValues"); end("swe:constraint"); // nil values handleSampleDimensionNilValues(gc2d, sd.getNoDataValues()); end("swe:Quantity"); end("swe:field"); } end("swe:DataRecord"); end("gml:rangeType"); }
/** Tests that flipping axis on a coverage whose origin is not (0,0) works as expected */ @Test public void testFlipTranslated() throws Exception { // build a translated image SampleModel sm = RasterFactory.createPixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, 256, 256, 3); ColorModel cm = PlanarImage.createColorModel(sm); TiledImage ti = new TiledImage(-10, -10, 5, 5, 0, 0, sm, cm); Graphics2D g = ti.createGraphics(); g.setColor(Color.GREEN); g.fillRect(-10, -10, 5, 5); g.dispose(); // build a coverage around it CoordinateReferenceSystem wgs84LatLon = CRS.decode("EPSG:4326"); final GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null); GridCoverage2D coverage = factory.create("translated", ti, new Envelope2D(wgs84LatLon, 3, 5, 6, 8)); // verify we're good int[] pixel = new int[3]; coverage.evaluate((DirectPosition) new DirectPosition2D(4, 6), pixel); assertEquals(0, pixel[0]); assertEquals(255, pixel[1]); assertEquals(0, pixel[2]); // now reproject flipping the axis CoordinateReferenceSystem wgs84LonLat = CRS.decode("EPSG:4326", true); GridGeometry gg = new GridGeometry2D( new GridEnvelope2D(-10, -10, 5, 5), (Envelope) new Envelope2D(wgs84LonLat, 5, 3, 8, 6)); GridCoverage2D flipped = (GridCoverage2D) Operations.DEFAULT.resample( coverage, wgs84LonLat, gg, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); // before the fix the pixel would have been black flipped.evaluate((DirectPosition) new DirectPosition2D(6, 4), pixel); assertEquals(0, pixel[0]); assertEquals(255, pixel[1]); assertEquals(0, pixel[2]); }
public void testHillshade() throws Exception { double[][] elevationData = HMTestMaps.mapData; HashMap<String, Double> envelopeParams = HMTestMaps.envelopeParams; CoordinateReferenceSystem crs = HMTestMaps.crs3004; GridCoverage2D elevationCoverage = CoverageUtilities.buildCoverage("elevation", elevationData, envelopeParams, crs, true); OmsHillshade hillshade = new OmsHillshade(); hillshade.inElev = elevationCoverage; hillshade.pElev = 45.0; hillshade.pAzimuth = 315; hillshade.pm = pm; hillshade.process(); GridCoverage2D hillshadeCoverage = hillshade.outHill; checkMatrixEqual(hillshadeCoverage.getRenderedImage(), HMTestMaps.outHillshade, 0.1); }