public PlanarImage gridToEmage(double[][] dataGrid, String imageName) throws IOException {
    // creates a gray-scale image of the values
    int width = dataGrid[0].length;
    int height = dataGrid.length;

    // Get the number of bands on the image.
    URL imgURL = new URL(Config.getProperty("imgURL"));
    PlanarImage dummyImage = JAI.create("URL", imgURL); // dummy loaded. date to be edited.
    SampleModel sm = dummyImage.getSampleModel();
    int nbands = sm.getNumBands();

    // We assume that we can get the pixels values in a integer array.
    double[] pixelTemp = new double[nbands];

    // Get an iterator for the image.
    RandomIterFactory.create(dummyImage, null);
    WritableRaster rasterData =
        RasterFactory.createBandedRaster(
            DataBuffer.TYPE_BYTE, width, height, nbands, new Point(0, 0));

    for (int i = 0; i < height; i++) {
      for (int j = 0; j < width; j++) {
        dataGrid[i][j] = (dataGrid[i][j] <= 255) ? dataGrid[i][j] : 255;

        pixelTemp[0] = dataGrid[i][j];
        pixelTemp[1] = dataGrid[i][j];
        pixelTemp[2] = dataGrid[i][j];

        rasterData.setPixel(j, i, pixelTemp);
      }
    }

    SampleModel sModel2 =
        RasterFactory.createBandedSampleModel(DataBuffer.TYPE_BYTE, width, height, nbands);

    // Try to create a compatible ColorModel - if the number of bands is
    // larger than 4, it will be null.
    ColorModel cModel2 = PlanarImage.createColorModel(sModel2);

    // Create a TiledImage using the sample and color models.
    TiledImage rectImage = new TiledImage(0, 0, width, height, 0, 0, sModel2, cModel2);

    // Set the data of the tiled image to be the raster.
    rectImage.setData(rasterData);

    // Save the image on a file.
    try {
      ImageIO.write(rectImage, "jpg", new File(imageName + ".jpg"));
      log.info("debug save image : " + imageName + ".jpg");

    } catch (IOException e) {
      log.error(e.getMessage());
      log.error("Error in rectifying  image");
    }

    return rectImage;
  }
  /**
   * Creates a {@link WritableRaster writable raster}.
   *
   * @param width width of the raster to create.
   * @param height height of the raster to create.
   * @param dataClass data type for the raster. If <code>null</code>, defaults to double.
   * @param sampleModel the samplemodel to use. If <code>null</code>, defaults to <code>
   *     new ComponentSampleModel(dataType, width, height, 1, width, new int[]{0});</code>.
   * @param value value to which to set the raster to. If null, the default of the raster creation
   *     is used, which is 0.
   * @return a {@link WritableRaster writable raster}.
   */
  public static WritableRaster createDoubleWritableRaster(
      int width, int height, Class<?> dataClass, SampleModel sampleModel, Double value) {
    int dataType = DataBuffer.TYPE_DOUBLE;
    if (dataClass != null) {
      if (dataClass.isAssignableFrom(Integer.class)) {
        dataType = DataBuffer.TYPE_INT;
      } else if (dataClass.isAssignableFrom(Float.class)) {
        dataType = DataBuffer.TYPE_FLOAT;
      } else if (dataClass.isAssignableFrom(Byte.class)) {
        dataType = DataBuffer.TYPE_BYTE;
      }
    }
    if (sampleModel == null) {
      sampleModel = new ComponentSampleModel(dataType, width, height, 1, width, new int[] {0});
    }

    WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, null);
    if (value != null) {
      // autobox only once
      double v = value;

      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          raster.setSample(x, y, 0, v);
        }
      }
    }
    return raster;
  }
Esempio n. 3
0
  public void create(
      final String name,
      final String filename,
      final AnalysisExtent ae,
      int dataType,
      final int numBands,
      final GProjection projection) {

    if (projection == null) {
      _projection = ProjectionUtils.getDefaultProjection();
    } else {
      _projection = projection;
    }

    if (dataType == DataBuffer.TYPE_DOUBLE) {
      dataType = DataBuffer.TYPE_FLOAT;
    }

    System.out.println(ae.getNX());
    System.out.println(ae.getNY());
    _raster = RasterFactory.createBandedRaster(dataType, ae.getNX(), ae.getNY(), numBands, null);

    _filename = filename;
    _name = name;
    _layerExtent = ae;
    _noDataValue = DEFAULT_NO_DATA_VALUE;
  }
 /**
  * Creates a test paletted image with translucency.
  *
  * @return
  */
 private static BufferedImage getSyntheticTranslucentIndexed() {
   final byte bb[] = new byte[256];
   for (int i = 0; i < 256; i++) bb[i] = (byte) i;
   final IndexColorModel icm = new IndexColorModel(8, 256, bb, bb, bb, bb);
   final WritableRaster raster =
       RasterFactory.createWritableRaster(icm.createCompatibleSampleModel(1024, 1024), null);
   for (int i = raster.getMinX(); i < raster.getMinX() + raster.getWidth(); i++)
     for (int j = raster.getMinY(); j < raster.getMinY() + raster.getHeight(); j++)
       raster.setSample(i, j, 0, (i + j) / 32);
   return new BufferedImage(icm, raster, false, null);
 }
  protected RenderedImage createRenderedImage(
      RenderedImage renderedImage, int height, int width, DataBuffer dataBuffer) {

    SampleModel sampleModel =
        RasterFactory.createPixelInterleavedSampleModel(
            DataBuffer.TYPE_BYTE, width, height, _NUM_OF_BANDS);
    ColorModel colorModel = PlanarImage.createColorModel(sampleModel);

    TiledImage tiledImage = new TiledImage(0, 0, width, height, 0, 0, sampleModel, colorModel);

    Raster raster = RasterFactory.createWritableRaster(sampleModel, dataBuffer, new Point(0, 0));

    tiledImage.setData(raster);

    /*javax.media.jai.JAI.create(
    	"filestore", tiledImage, "test.png", "PNG");

    printImage(renderedImage);
    printImage(tiledImage);}*/

    return tiledImage;
  }
Esempio n. 6
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]);
  }
 /**
  * Creates a simple 128x128 {@link RenderedImage} for testing purposes.
  *
  * @param maximum
  * @return
  */
 private static RenderedImage getSynthetic(final double maximum) {
   final int width = 128;
   final int height = 128;
   final WritableRaster raster =
       RasterFactory.createBandedRaster(DataBuffer.TYPE_DOUBLE, width, height, 1, null);
   final Random random = new Random();
   for (int y = 0; y < height; y++) {
     for (int x = 0; x < width; x++) {
       raster.setSample(x, y, 0, Math.ceil(random.nextDouble() * maximum));
     }
   }
   final ColorModel cm =
       new ComponentColorModelJAI(
           ColorSpace.getInstance(ColorSpace.CS_GRAY),
           false,
           false,
           Transparency.OPAQUE,
           DataBuffer.TYPE_DOUBLE);
   final BufferedImage image = new BufferedImage(cm, raster, false, null);
   return image;
 }
Esempio n. 8
0
  /**
   * Paint the image onto a Graphics object. The painting is performed tile-by-tile, and includes a
   * grey region covering the unused portion of image tiles as well as the general background. At
   * this point the image must be byte data.
   */
  public synchronized void paintComponent(Graphics g) {

    Graphics2D g2D = null;
    if (g instanceof Graphics2D) {
      g2D = (Graphics2D) g;
    } else {
      return;
    }

    // if source is null, it's just a component
    if (source == null) {
      g2D.setColor(getBackground());
      g2D.fillRect(0, 0, componentWidth, componentHeight);
      return;
    }

    int transX = -originX;
    int transY = -originY;

    // Get the clipping rectangle and translate it into image coordinates.
    Rectangle clipBounds = g.getClipBounds();

    if (clipBounds == null) {
      clipBounds = new Rectangle(0, 0, componentWidth, componentHeight);
    }

    // clear the background (clip it) [minimal optimization here]
    if (transX > 0
        || transY > 0
        || transX < (componentWidth - source.getWidth())
        || transY < (componentHeight - source.getHeight())) {
      g2D.setColor(getBackground());
      g2D.fillRect(0, 0, componentWidth, componentHeight);
    }

    clipBounds.translate(-transX, -transY);

    // Determine the extent of the clipping region in tile coordinates.
    int txmin, txmax, tymin, tymax;
    int ti, tj;

    txmin = XtoTileX(clipBounds.x);
    txmin = Math.max(txmin, minTileX);
    txmin = Math.min(txmin, maxTileX);

    txmax = XtoTileX(clipBounds.x + clipBounds.width - 1);
    txmax = Math.max(txmax, minTileX);
    txmax = Math.min(txmax, maxTileX);

    tymin = YtoTileY(clipBounds.y);
    tymin = Math.max(tymin, minTileY);
    tymin = Math.min(tymin, maxTileY);

    tymax = YtoTileY(clipBounds.y + clipBounds.height - 1);
    tymax = Math.max(tymax, minTileY);
    tymax = Math.min(tymax, maxTileY);
    Insets insets = getInsets();

    // Loop over tiles within the clipping region
    for (tj = tymin; tj <= tymax; tj++) {
      for (ti = txmin; ti <= txmax; ti++) {
        int tx = TileXtoX(ti);
        int ty = TileYtoY(tj);

        Raster tile = source.getTile(ti, tj);
        if (tile != null) {
          DataBuffer dataBuffer = tile.getDataBuffer();

          WritableRaster wr = tile.createWritableRaster(sampleModel, dataBuffer, null);

          BufferedImage bi =
              new BufferedImage(colorModel, wr, colorModel.isAlphaPremultiplied(), null);

          // correctly handles band offsets
          if (brightnessEnabled == true) {
            SampleModel sm =
                sampleModel.createCompatibleSampleModel(tile.getWidth(), tile.getHeight());

            WritableRaster raster = RasterFactory.createWritableRaster(sm, null);

            BufferedImage bimg =
                new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

            // don't move this code
            ByteLookupTable lutTable = new ByteLookupTable(0, lutData);
            LookupOp lookup = new LookupOp(lutTable, null);
            lookup.filter(bi, bimg);

            g2D.drawImage(bimg, biop, tx + transX + insets.left, ty + transY + insets.top);
          } else {
            AffineTransform transform;

            transform =
                AffineTransform.getTranslateInstance(
                    tx + transX + insets.left, ty + transY + insets.top);

            g2D.drawRenderedImage(bi, transform);
          }
        }
      }
    }
  }
  /*
   * Derive the image layout (tile grid, image bounds, ColorModel, and
   * SampleModel) by querying the IIP server.
   */
  private static ImageLayout layoutHelper(String URLSpec, int level, int subImage) {
    // Create an ImageLayout by construction or cloning.
    ImageLayout il = new ImageLayout();

    // Set the tile offsets to (0,0).
    il.setTileGridXOffset(0);
    il.setTileGridYOffset(0);

    // Set the tile dimensions.
    il.setTileWidth(TILE_SIZE);
    il.setTileHeight(TILE_SIZE);

    // Set the image origin to (0,0).
    il.setMinX(0);
    il.setMinY(0);

    // Retrieve the number of resolutions available and the maximum
    // width and height (the dimensions of resolution numRes - 1).
    int maxWidth = -1;
    int maxHeight = -1;
    int numRes = -1;
    int resolution = -1;
    String[] cmd = new String[] {"OBJ=Max-size", "OBJ=Resolution-number"};
    InputStream stream = postCommands(URLSpec, cmd);
    String label = null;
    while ((label = getLabel(stream)) != null) {
      if (label.equals("max-size")) {
        String data = getDataAsString(stream, false);
        int[] wh = stringToIntArray(data);
        maxWidth = wh[0];
        maxHeight = wh[1];
      } else if (label.equals("resolution-number")) {
        String data = getDataAsString(stream, false);
        numRes = Integer.valueOf(data).intValue();
        if (level < 0) {
          resolution = 0;
        } else if (level >= numRes) {
          resolution = numRes - 1;
        } else {
          resolution = level;
        }
      } else {
        checkError(label, stream, true);
      }
    }
    closeStream(stream);

    // Derive the width and height for this resolution level.
    int w = maxWidth;
    int h = maxHeight;
    for (int i = numRes - 1; i > resolution; i--) {
      w = (w + 1) / 2;
      h = (h + 1) / 2;
    }
    il.setWidth(w);
    il.setHeight(h);

    // Determine image opacity attributes.
    boolean hasAlpha = false;
    boolean isAlphaPremultiplied = false;
    cmd = new String[] {"OBJ=Colorspace," + resolution + "," + subImage};
    stream = postCommands(URLSpec, cmd);
    int colorSpaceIndex = 0;
    int numBands = 0;
    while ((label = getLabel(stream)) != null) {
      if (label.startsWith("colorspace")) {
        int[] ia = stringToIntArray(getDataAsString(stream, false));
        numBands = ia[3];
        switch (ia[2]) {
          case CS_MONOCHROME:
            colorSpaceIndex = ColorSpace.CS_GRAY;
            break;
          case CS_PHOTOYCC:
            colorSpaceIndex = ColorSpace.CS_PYCC;
            break;
          case CS_NIFRGB:
            colorSpaceIndex = ColorSpace.CS_sRGB;
            break;
          default:
            colorSpaceIndex = numBands < 3 ? ColorSpace.CS_GRAY : ColorSpace.CS_sRGB;
        }
        for (int j = 1; j <= numBands; j++) {
          if (ia[3 + j] == CS_PLANE_ALPHA) {
            hasAlpha = true;
          }
        }
        isAlphaPremultiplied = ia[1] == 1;
      } else {
        checkError(label, stream, true);
      }
    }
    closeStream(stream);

    // Set the ColorModel.
    ColorSpace cs = ColorSpace.getInstance(colorSpaceIndex);
    int dtSize = DataBuffer.getDataTypeSize(DataBuffer.TYPE_BYTE);
    int[] bits = new int[numBands];
    for (int i = 0; i < numBands; i++) {
      bits[i] = dtSize;
    }
    int transparency = hasAlpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE;
    ColorModel cm =
        new ComponentColorModel(
            cs, bits, hasAlpha, isAlphaPremultiplied, transparency, DataBuffer.TYPE_BYTE);
    il.setColorModel(cm);

    // Set the SampleModel.
    int[] bandOffsets = new int[numBands];
    for (int i = 0; i < numBands; i++) {
      bandOffsets[i] = i;
    }
    il.setSampleModel(
        RasterFactory.createPixelInterleavedSampleModel(
            DataBuffer.TYPE_BYTE,
            TILE_SIZE,
            TILE_SIZE,
            numBands,
            numBands * TILE_SIZE,
            bandOffsets));

    return il;
  }
  public PlanarImage PostProcessEmage(PlanarImage img) {
    if (maskImgFName != null) {
      int width = img.getWidth();
      int height = img.getHeight();

      // Get the number of bands on the image.
      SampleModel sm = img.getSampleModel();
      int nbands = sm.getNumBands();

      // We assume that we can get the pixels values in a integer array.
      double[] pixel = new double[nbands];

      // Get an iterator for the image.
      RandomIter iterator = RandomIterFactory.create(img, null);
      WritableRaster rasterImage =
          RasterFactory.createBandedRaster(
              DataBuffer.TYPE_BYTE, width, height, nbands, new Point(0, 0));

      double[] pixelNeighb = new double[nbands];
      double[] pixelblack = new double[nbands];
      for (int i = 0; i < nbands; i++) {
        pixelNeighb[i] = 0;
        pixelblack[i] = 0;
      }

      PlanarImage mask = JAI.create("FileLoad", maskImgFName);
      RandomIter iteratorMask = RandomIterFactory.create(mask, null);
      double[] pixelMask = new double[mask.getSampleModel().getNumBands()];

      for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
          iteratorMask.getPixel(i, j, pixelMask);
          if (!isBlack(pixelMask)) {
            iterator.getPixel(i, j, pixel);
            if (isWhite(pixel)) {;
            } else {
              rasterImage.setPixel(i, j, pixel);
            }
          } else {
            rasterImage.setPixel(i, j, pixelblack);
          }
        }
      }
      SampleModel sModel2 =
          RasterFactory.createBandedSampleModel(DataBuffer.TYPE_BYTE, width, height, nbands);

      // Try to create a compatible ColorModel - if the number of bands is
      // larger than 4, it will be null.
      ColorModel cModel2 = PlanarImage.createColorModel(sModel2);

      // Create a TiledImage using the sample and color models.
      TiledImage processedImage = new TiledImage(0, 0, width, height, 0, 0, sModel2, cModel2);

      // Set the data of the tiled image to be the raster.
      processedImage.setData(rasterImage);

      // Save the image to a file.
      try {
        ImageIO.write(processedImage, "jpg", new File("proc_" + theme + ".jpg"));
      } catch (IOException e) {
        log.error(e.getMessage());
      }

      // Save the image on a file.
      return processedImage;
    } else {
      // Save the image to a file.
      try {
        ImageIO.write(img, "jpg", new File("NOTproc_" + theme + ".jpg"));
      } catch (IOException e) {
        log.error(e.getMessage());
      }
      return img;
    }
  }
  public PlanarImage createRectifiedImage(PlanarImage Image) {
    int nRows = params.getNumOfRows();
    int nCols = params.getNumOfColumns();
    Point rectifiedPoint;

    // Get the image dimensions of the unrectified image
    int width = Image.getWidth();
    int height = Image.getHeight();
    log.info(nRows + ", " + nCols + "\t" + width + ", " + height);
    // Get an iterator for the image.
    RandomIter iterator = RandomIterFactory.create(Image, null);

    // Get the number of bands on the image.
    SampleModel smO = Image.getSampleModel();
    int nbandsO = smO.getNumBands();

    // We assume that we can get the pixels values in a integer array.
    double[] pixelO = new double[nbandsO];

    // Get an iterator for the image.
    WritableRaster rasterPollenO =
        RasterFactory.createBandedRaster(
            DataBuffer.TYPE_BYTE, nCols, nRows, nbandsO, new Point(0, 0));

    for (int i = 0; i < nCols; i++) {
      for (int j = 0; j < nRows; j++) {
        rectifiedPoint =
            this.getMatchingCoord(
                new Point(i + 1, j + 1)); // coz java array start at 0 matlab its 1.
        if (rectifiedPoint.x >= 1
            && rectifiedPoint.x < width
            && rectifiedPoint.y >= 1
            && rectifiedPoint.y < height) {
          iterator.getPixel(rectifiedPoint.x - 1, rectifiedPoint.y - 1, pixelO);
          rasterPollenO.setPixel(i, j, pixelO);
          // log.info("setpixel: " + i + ", " + j  + ", value " + pixelO[0] + ", " + pixelO[1] + ",
          // " + pixelO[2] + ", " + pixelO[3]);
        } else {

        }
      }
    }

    SampleModel sModel2 =
        RasterFactory.createBandedSampleModel(DataBuffer.TYPE_BYTE, nCols, nRows, nbandsO);

    // Try to create a compatible ColorModel - if the number of bands is
    // larger than 4, it will be null.
    ColorModel cModel2 = PlanarImage.createColorModel(sModel2);

    // Create a TiledImage using the sample and color models.
    TiledImage rectPollenImage = new TiledImage(0, 0, nCols, nRows, 0, 0, sModel2, cModel2);

    // log.info(rasterPollenO.getMinX() + ", " + rasterPollenO.getMinY() );
    // Set the data of the tiled image to be the raster.
    rectPollenImage.setData(rasterPollenO);

    // Save the image to a file.
    try {
      ImageIO.write(rectPollenImage, "jpg", new File("rect" + theme + ".jpg"));
    } catch (IOException e) {
      log.error(e.getMessage());
    }
    return rectPollenImage;
  }
  public static GGlobeRasterLayer readFile(final File file, final GProjection proj)
      throws IOException, NumberFormatException {

    String s = new String();
    StringTokenizer st;
    @SuppressWarnings("unused")
    String sXOrigin, sYOrigin;
    int iCols, iRows;
    double dResolution;
    double dNoData;
    double dX, dY;
    String sToken = "";
    final BufferedReader fin = new BufferedReader(new FileReader(file));

    s = fin.readLine();
    st = new StringTokenizer(s);
    sToken = st.nextToken();
    sToken = st.nextToken();
    iCols = Integer.parseInt(sToken);
    s = fin.readLine();
    st = new StringTokenizer(s);
    sToken = st.nextToken();
    sToken = st.nextToken();
    iRows = Integer.parseInt(sToken);
    s = fin.readLine();
    st = new StringTokenizer(s);
    sXOrigin = st.nextToken();
    sToken = st.nextToken();
    dX = Double.parseDouble(sToken);
    s = fin.readLine();
    st = new StringTokenizer(s);
    sYOrigin = st.nextToken();
    sToken = st.nextToken();
    dY = Double.parseDouble(sToken);
    s = fin.readLine();
    st = new StringTokenizer(s);
    sToken = st.nextToken();
    sToken = st.nextToken();
    dResolution = Double.parseDouble(sToken);
    s = fin.readLine();
    st = new StringTokenizer(s);
    sToken = st.nextToken();
    sToken = st.nextToken();
    dNoData = Double.parseDouble(sToken);
    if (sXOrigin.equals("xllcenter")) {
      dX = dX - dResolution / 2d;
      dY = dY - dResolution / 2d;
    }

    final WritableRaster raster =
        RasterFactory.createBandedRaster(DataBuffer.TYPE_FLOAT, iCols, iRows, 1, null);

    for (int y = 0; y < iRows; y++) {
      s = fin.readLine();
      st = new StringTokenizer(s);
      for (int x = 0; x < iCols; x++) {
        sToken = st.nextToken();
        raster.setSample(x, y, 0, Double.parseDouble(sToken));
      }
    }
    fin.close();

    final GRasterGeodata extent = new GRasterGeodata(dX, dY, dResolution, iRows, iCols, proj);
    final GGlobeRasterLayer layer = new GGlobeRasterLayer(raster, extent);
    layer.setName(file.getName());
    layer.setNoDataValue(dNoData);

    return layer;
  }