/**
   * Creates a {@link GridCoverage} for the provided {@link PlanarImage} using the {@link
   * #raster2Model} that was provided for this coverage.
   *
   * <p>This method is vital when working with coverages that have a raster to model transformation
   * that is not a simple scale and translate.
   *
   * @param coverageName
   * @param image contains the data for the coverage to create.
   * @param raster2Model is the {@link MathTransform} that maps from the raster space to the model
   *     space.
   * @return a {@link GridCoverage}
   * @throws IOException
   */
  protected final GridCoverage2D createImageCoverage(
      String coverageName, PlanarImage image, MathTransform raster2Model) throws IOException {

    // creating bands
    final SampleModel sm = image.getSampleModel();
    final ColorModel cm = image.getColorModel();
    final int numBands = sm.getNumBands();
    final GridSampleDimension[] bands = new GridSampleDimension[numBands];
    // setting bands names.
    for (int i = 0; i < numBands; i++) {
      final ColorInterpretation colorInterpretation = TypeMap.getColorInterpretation(cm, i);
      if (colorInterpretation == null) throw new IOException("Unrecognized sample dimension type");
      bands[i] = new GridSampleDimension(colorInterpretation.name()).geophysics(true);
    }
    // creating coverage
    if (raster2Model != null) {
      return coverageFactory.create(
          coverageName,
          image,
          getCoordinateReferenceSystem(coverageName),
          raster2Model,
          bands,
          null,
          null);
    }
    return coverageFactory.create(
        coverageName,
        image,
        new GeneralEnvelope(getOriginalEnvelope(coverageName)),
        bands,
        null,
        null);
  }
  public static void main(String[] args) throws Exception {
    URL imageURL = RasterTutorial.class.getResource("image.png");

    BufferedImage image = ImageIO.read(imageURL);

    // coordinates of our raster image, in lat/lon
    double minx = -92.36918018580701;
    double miny = -49.043520894708884;

    double maxx = -42.25153935511384;
    double maxy = 2.1002762835725868;

    CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
    ReferencedEnvelope envelope = new ReferencedEnvelope(minx, maxx, miny, maxy, crs);

    String name = "GridCoverage";

    GridCoverageFactory factory = new GridCoverageFactory();
    GridCoverage2D gridCoverage = (GridCoverage2D) factory.create(name, image, envelope);

    CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:24882");

    RenderingHints hints = new RenderingHints(Hints.LENIENT_DATUM_SHIFT, Boolean.TRUE);
    CoverageProcessor processor = new CoverageProcessor(hints);

    ParameterValueGroup param = processor.getOperation("Resample").getParameters();
    param.parameter("Source").setValue(gridCoverage);
    param.parameter("CoordinateReferenceSystem").setValue(targetCRS);
    param.parameter("InterpolationType").setValue("NearestNeighbor");

    GridCoverage2D reprojected = (GridCoverage2D) processor.doOperation(param);

    ViewerOld.show(gridCoverage, "Normal Grid Coverage");
    ViewerOld.show(reprojected, "Reprojected Grid Coverage");
  }
Esempio n. 3
0
  /**
   * Performs a translation using the "Resample" operation.
   *
   * @param grid the {@link GridCoverage2D} to apply the translation on.
   * @throws NoninvertibleTransformException If a "grid to CRS" transform is not invertible.
   */
  private void doTranslation(GridCoverage2D grid) throws NoninvertibleTransformException {
    final int transX = -253;
    final int transY = -456;
    final double scaleX = 0.04;
    final double scaleY = -0.04;
    final ParameterBlock block =
        new ParameterBlock()
            .addSource(grid.getRenderedImage())
            .add((float) transX)
            .add((float) transY);
    RenderedImage image = JAI.create("Translate", block);
    assertEquals("Incorrect X translation", transX, image.getMinX());
    assertEquals("Incorrect Y translation", transY, image.getMinY());

    /*
     * Create a grid coverage from the translated image but with the same envelope.
     * Consequently, the 'gridToCoordinateSystem' should be translated by the same
     * amount, with the opposite sign.
     */
    AffineTransform expected = getAffineTransform(grid);
    assertNotNull(expected);
    expected = new AffineTransform(expected); // Get a mutable instance.
    final GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);
    grid =
        factory.create(
            "Translated",
            image,
            grid.getEnvelope(),
            grid.getSampleDimensions(),
            new GridCoverage2D[] {grid},
            grid.getProperties());
    expected.translate(-transX, -transY);
    assertTransformEquals(expected, getAffineTransform(grid));

    /*
     * Apply the "Resample" operation with a specific 'gridToCoordinateSystem' transform.
     * The envelope is left unchanged. The "Resample" operation should compute automatically
     * new image bounds.
     */
    final AffineTransform at = AffineTransform.getScaleInstance(scaleX, scaleY);
    final MathTransform tr = ProjectiveTransform.create(at);
    // account for the half pixel correction between the two spaces since we are talking raster here
    // but the resample will talk model!
    final MathTransform correctedTransform =
        PixelTranslation.translate(tr, PixelInCell.CELL_CORNER, PixelInCell.CELL_CENTER);
    final GridGeometry2D geometry = new GridGeometry2D(null, correctedTransform, null);
    final GridCoverage2D newGrid =
        (GridCoverage2D)
            Operations.DEFAULT.resample(grid, grid.getCoordinateReferenceSystem(), geometry, null);
    assertEquals(correctedTransform, getAffineTransform(newGrid));
    image = newGrid.getRenderedImage();
    expected.preConcatenate(at.createInverse());
    final Point point = new Point(transX, transY);
    assertSame(point, expected.transform(point, point)); // Round toward neareast integer
  }
  /**
   * 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;
  }
    private GridCoverage2D execute() throws Exception {

      initialize();

      // check that initialization was successful
      if (colorMap == null) {
        return null;
      }

      for (LinkedList<SimpleFeature> baselineFeatures : baselineFeaturesMap.values()) {
        processBaselineFeatures(baselineFeatures);
      }

      GridCoverageFactory gcf = new GridCoverageFactory();
      return gcf.create(
          getClass().getSimpleName() + "-" + UUID.randomUUID().toString(), image, coverageEnvelope);
    }
  private GridCoverage2D convertImageToGridCoverage(
      ReferencedEnvelope requestBBox, BufferedImage image) throws RenderException {
    Envelope env = requestBBox;
    GeneralEnvelope gtEnv =
        new GeneralEnvelope(
            new double[] {env.getMinX(), env.getMinY()},
            new double[] {env.getMaxX(), env.getMaxY()});

    try {
      gtEnv.setCoordinateReferenceSystem(requestBBox.getCoordinateReferenceSystem());
    } catch (Exception e) {
      throw wrapException(e);
    }

    GridCoverageFactory factory = new GridCoverageFactory();

    GridCoverage2D gc =
        (GridCoverage2D) factory.create("GridCoverage", image, gtEnv); // $NON-NLS-1$
    return gc;
  }
Esempio n. 7
0
  /** 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]);
  }
Esempio n. 8
0
  /**
   * Tests the "Resample" operation with a stereographic coordinate system on a paletted image
   *
   * @throws FactoryException
   * @throws NoSuchAuthorityCodeException
   */
  @Test
  public void testReprojectPalette() throws NoSuchAuthorityCodeException, FactoryException {

    // do it again, make sure the image does not turn black since
    GridCoverage2D input = ushortCoverage;
    // Create a Palette image from the input coverage
    RenderedImage src = input.getRenderedImage();
    ImageWorker iw = new ImageWorker(src).rescaleToBytes().forceIndexColorModel(false);
    src = iw.getRenderedOperation();

    // Setting Force ReplaceIndexColorModel and CoverageProcessingView as SAME
    Hints hints = GeoTools.getDefaultHints().clone();
    hints.put(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, true);
    hints.put(Hints.COVERAGE_PROCESSING_VIEW, ViewType.SAME);

    // Create a new GridCoverage
    GridCoverageFactory factory = new GridCoverageFactory(hints);
    GridCoverage2D palette = factory.create("test", src, input.getEnvelope());

    CoordinateReferenceSystem targetCRS = CRS.parseWKT(GOOGLE_MERCATOR_WKT);
    GridCoverage2D coverage_ = project(palette, targetCRS, null, "bilinear", hints, 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);

    // Ensure the CRS is correct
    CoordinateReferenceSystem targetCoverageCRS = coverage_.getCoordinateReferenceSystem();
    Assert.assertTrue(CRS.equalsIgnoreMetadata(targetCRS, targetCoverageCRS));
  }
  /**
   * @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$
    }
  }