Esempio n. 1
0
 @Test
 public void testTranslatedImage() throws Exception {
   BufferedImage bi = new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY);
   TiledImage image =
       new TiledImage(
           0,
           0,
           256,
           256,
           1,
           1,
           bi.getSampleModel().createCompatibleSampleModel(256, 256),
           bi.getColorModel());
   Graphics g = image.createGraphics();
   g.setColor(Color.WHITE);
   g.fillRect(0, 0, 20, 20);
   g.setColor(new Color(20, 20, 20)); // A dark gray
   g.fillRect(20, 20, 20, 20);
   g.setColor(new Color(200, 200, 200)); // A light gray
   g.fillRect(0, 20, 20, 20);
   g.dispose();
   RenderedImage indexed = quantize(image);
   assertTrue(indexed.getColorModel() instanceof IndexColorModel);
   IndexColorModel icm = (IndexColorModel) indexed.getColorModel();
   assertEquals(4, icm.getMapSize()); // Black background, white fill,
   // light gray fill, dark gray fill =
   // 4 colors
 }
  @Test
  public void testTranslatedImage() {
    BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY);
    Graphics g = image.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(236, 236, 20, 20);
    g.setColor(new Color(80, 80, 80)); // A dark gray
    g.fillRect(216, 216, 20, 20);
    g.setColor(new Color(200, 200, 200)); // A light gray
    g.fillRect(216, 236, 20, 20);
    g.dispose();
    image = image.getSubimage(128, 128, 128, 128);
    CustomPaletteBuilder builder = new CustomPaletteBuilder(image, 256, 1, 1, 1);
    RenderedImage indexed = builder.buildPalette().getIndexedImage();
    assertTrue(indexed.getColorModel() instanceof IndexColorModel);
    IndexColorModel icm = (IndexColorModel) indexed.getColorModel();
    assertEquals(
        4,
        icm
            .getMapSize()); // Black background, white fill, light gray fill, dark gray fill = 4
                            // colors

    // check image not black
    ImageWorker iw = new ImageWorker(indexed).forceComponentColorModel().intensity();
    double[] mins = iw.getMinimums();
    double[] maxs = iw.getMaximums();
    boolean result = true;
    for (int i = 0; i < mins.length; i++) {
      result = mins[i] == maxs[i] ? false : result;
    }
    assertTrue(result);
  }
 public void appendLoggingGeometries(String geomName, RenderedImage img) {
   if (LOGGER.isLoggable(GEOM_LEVEL)) {
     appendLoggingGeometries(
         geomName,
         new GridEnvelope2D(img.getMinX(), img.getMinY(), img.getWidth(), img.getHeight()));
   }
 }
Esempio n. 4
0
  @Test
  public void testFourColorROI() {
    // Testing color indexing with ROI
    // build a transparent image
    BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_4BYTE_ABGR);
    Graphics g = image.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, 10, 10);
    g.setColor(Color.RED);
    g.fillRect(10, 0, 10, 10);
    g.setColor(Color.BLUE);
    g.fillRect(20, 0, 10, 10);
    g.setColor(Color.GREEN);
    g.fillRect(30, 0, 10, 10);
    g.dispose();

    //
    // create a palette out of it
    //
    RenderedImage indexed = quantize(image, new ROIShape(new Rectangle(10, 0, 10, 10)), null, 10);
    assertTrue(indexed.getColorModel() instanceof IndexColorModel);
    IndexColorModel icm = (IndexColorModel) indexed.getColorModel();

    // make sure we have 4 colors + transparent one
    assertEquals(5, icm.getMapSize());
  }
Esempio n. 5
0
  /**
   * Loads an image from a URL
   *
   * @param bitmapFile the bitmap file
   * @return the bitmap as BufferedImage
   */
  public static BufferedImage getImage(File bitmapFile) {
    try {
      InputStream in = new java.io.FileInputStream(bitmapFile);
      try {
        in = new java.io.BufferedInputStream(in);

        ImageTagRegistry reg = ImageTagRegistry.getRegistry();
        Filter filt = reg.readStream(in);
        if (filt == null) {
          return null;
        }

        RenderedImage red = filt.createDefaultRendering();
        if (red == null) {
          return null;
        }

        BufferedImage img =
            new BufferedImage(red.getWidth(), red.getHeight(), BufferedImage.TYPE_INT_ARGB);
        red.copyData(img.getRaster());
        return img;
      } finally {
        IOUtils.closeQuietly(in);
      }
    } catch (IOException e) {
      return null;
    }
  }
  private GridSampleDimension[] getSampleDimensions(final RenderedImage coverageRaster)
      throws IOException {

    GridSampleDimension[] bands = rasterInfo.getGridSampleDimensions();

    // may the image have been promoted? build the correct band info then
    final int imageBands = coverageRaster.getSampleModel().getNumBands();
    if (bands.length == 1 && imageBands > 1) {
      LOGGER.fine(
          coverageName
              + " was promoted from 1 to "
              + coverageRaster.getSampleModel().getNumBands()
              + " bands, returning an appropriate set of GridSampleDimension");
      // stolen from super.createCoverage:
      final ColorModel cm = coverageRaster.getColorModel();
      bands = new GridSampleDimension[imageBands];

      // setting bands names.
      for (int i = 0; i < imageBands; i++) {
        final ColorInterpretation colorInterpretation;
        colorInterpretation = TypeMap.getColorInterpretation(cm, i);
        if (colorInterpretation == null) {
          throw new IOException("Unrecognized sample dimension type");
        }
        bands[i] = new GridSampleDimension(colorInterpretation.name()).geophysics(true);
      }
    }

    return bands;
  }
  protected void printImage(RenderedImage renderedImage) {
    SampleModel sampleModel = renderedImage.getSampleModel();

    int height = renderedImage.getHeight();
    int width = renderedImage.getWidth();
    int numOfBands = sampleModel.getNumBands();

    int[] pixels = new int[height * width * numOfBands];

    Raster raster = renderedImage.getData();

    raster.getPixels(0, 0, width, height, pixels);

    int offset = 0;

    for (int h = 0; h < height; h++) {
      for (int w = 0; w < width; w++) {
        offset = (h * width * numOfBands) + (w * numOfBands);

        System.out.print("[" + w + ", " + h + "] = ");

        for (int b = 0; b < numOfBands; b++) {
          System.out.print(pixels[offset + b] + " ");
        }
      }

      System.out.println();
    }
  }
Esempio n. 8
0
  @Test
  public void testDataTypes() throws IOException, FileNotFoundException {
    if (!isGDALAvailable) {
      return;
    }
    final List<String> fileList = new ArrayList<String>(4);
    fileList.add("paletted.tif");
    fileList.add("utmByte.tif");
    fileList.add("utmInt16.tif");
    fileList.add("utmInt32.tif");
    fileList.add("utmFloat32.tif");
    fileList.add("utmFloat64.tif");

    for (String fileName : fileList) {
      final ImageReadParam irp = new ImageReadParam();
      final File inputFile = TestData.file(this, fileName);
      irp.setSourceSubsampling(1, 1, 0, 0);
      ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance();
      reader.setInput(inputFile);
      final RenderedImage image = reader.readAsRenderedImage(0, irp);
      if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image, fileName);
      if (!fileName.contains("paletted")) {
        Assert.assertEquals(256, image.getHeight());
        Assert.assertEquals(256, image.getWidth());
      } else {
        Assert.assertEquals(128, image.getHeight());
        Assert.assertEquals(128, image.getWidth());
      }

      reader.dispose();
    }
  }
  /**
   * Constructs a <code>SubsampleBinaryToGrayOpImage</code> from a <code>RenderedImage</code>
   * source, x and y scale object. The image dimensions are determined by forward-mapping the source
   * bounds, and are passed to the superclass constructor by means of the <code>layout</code>
   * parameter. Other fields of the layout are passed through unchanged. If <code>layout</code> is
   * <code>null</code>, a new <code>ImageLayout</code> will be constructor to hold the bounds
   * information.
   *
   * <p>The float rounding errors, such as 1.2 being internally represented as 1.200001, are dealt
   * with the floatTol, which is set up so that only 1/10 of pixel error will occur at the end of a
   * line, which yields correct results with Math.round() operation. The repeatability is guaranteed
   * with a one-time computed table xvalues and yvalues.
   *
   * @param layout an <code>ImageLayout</code> optionally containing the tile grid layout, <code>
   *     SampleModel</code>, and <code>ColorModel</code>, or <code>null</code>.
   * @param source a <code>RenderedImage</code>. from this <code>OpImage</code>, or <code>null
   *     </code>. If <code>null</code>, no caching will be performed.
   * @param cobbleSources a boolean indicating whether <code>computeRect</code> expects contiguous
   *     sources.
   * @param extender a <code>BorderExtender</code>, or <code>null</code>.
   * @param interp an <code>Interpolation</code> object to use for resampling.
   * @param scaleX scale factor along x axis.
   * @param scaleY scale factor along y axis.
   * @throws IllegalArgumentException if combining the source bounds with the layout parameter
   *     results in negative output width or height.
   */
  public SubsampleBinaryToGrayOpImage(
      RenderedImage source, ImageLayout layout, Map config, float scaleX, float scaleY) {

    super(
        vectorize(source),
        layoutHelper(source, scaleX, scaleY, layout, config),
        configHelper(config),
        true, // cobbleSources,
        null, // extender
        null, // interpolation
        null);

    this.scaleX = scaleX;
    this.scaleY = scaleY;
    int srcMinX = source.getMinX();
    int srcMinY = source.getMinY();
    int srcWidth = source.getWidth();
    int srcHeight = source.getHeight();

    // compute floatTol, invScaleX, blockX, dWidth, dHeight,...
    computeDestInfo(srcWidth, srcHeight);

    if (extender == null) {
      computableBounds = new Rectangle(0, 0, dWidth, dHeight);
    } else {
      // If extender is present we can write the entire destination.
      computableBounds = getBounds();
    }

    // these can be delayed, such as placed in computeRect()
    buildLookupTables();

    // compute the begining bit position of each row and column
    computeXYValues(srcWidth, srcHeight, srcMinX, srcMinY);
  }
Esempio n. 10
0
  @Override
  public void process() throws Exception {
    RenderedImage source = (RenderedImage) params.get(INPUT_IMG);
    RenderedImage result = source;
    Rectangle area = (Rectangle) params.get(P_AREA);

    if (area == null) {
      LOGGER.warn("Cannot apply \"{}\" because a parameter is null", OP_NAME); // $NON-NLS-1$
    } else {
      area =
          area.intersection(
              new Rectangle(
                  source.getMinX(), source.getMinY(), source.getWidth(), source.getHeight()));
      if (area.width > 1 && area.height > 1) {
        ParameterBlock pb = new ParameterBlock();
        pb.addSource(source);
        pb.add((float) area.x).add((float) area.y);
        pb.add((float) area.width).add((float) area.height);
        result = JAI.create("crop", pb, null); // $NON-NLS-1$

        if (JMVUtils.getNULLtoFalse(params.get(P_SHIFT_TO_ORIGIN))) {
          float diffw = source.getMinX() - result.getMinX();
          float diffh = source.getMinY() - result.getMinY();
          if (diffw != 0.0f || diffh != 0.0f) {
            pb = new ParameterBlock();
            pb.addSource(result);
            pb.add(diffw);
            pb.add(diffh);
            result = JAI.create("translate", pb, null); // $NON-NLS-1$
          }
        }
      }
    }
    params.put(OUTPUT_IMG, result);
  }
Esempio n. 11
0
  /**
   * Convert index color mapped image content to a full 24-bit 16-million color RGB image.
   *
   * @param image the source image to convert.
   * @return a full RGB color image as RenderedOp.
   */
  public static RenderedImage convertIndexColorToRGBColor(RenderedImage image) {
    RenderedImage result = image;

    // If the source image is color mapped, convert it to 3-band RGB.
    // Note that GIF and PNG files fall into this category.
    if (image.getColorModel() instanceof IndexColorModel) {
      // Retrieve the IndexColorModel
      IndexColorModel icm = (IndexColorModel) image.getColorModel();

      // Cache the number of elements in each band of the colormap.
      int mapSize = icm.getMapSize();

      // Allocate an array for the lookup table data.
      byte[][] lutData = new byte[3][mapSize];

      // Load the lookup table data from the IndexColorModel.
      icm.getReds(lutData[0]);
      icm.getGreens(lutData[1]);
      icm.getBlues(lutData[2]);

      // Create the lookup table object.
      LookupTableJAI lut = new LookupTableJAI(lutData);

      // Replace the original image with the 3-band RGB image.
      result = JAI.create("lookup", image, lut); // $NON-NLS-1$
    }

    return result;
  }
  /** This template method should set the xlink:href attribute on the input Element parameter */
  protected void handleHREF(
      RenderedImage image, Element imageElement, SVGGeneratorContext generatorContext)
      throws SVGGraphics2DIOException {
    //
    // Create an buffered image if necessary
    //
    BufferedImage buf = null;
    if (image instanceof BufferedImage
        && ((BufferedImage) image).getType() == getBufferedImageType()) {
      buf = (BufferedImage) image;
    } else {
      Dimension size = new Dimension(image.getWidth(), image.getHeight());
      buf = buildBufferedImage(size);

      Graphics2D g = createGraphics(buf);

      g.drawRenderedImage(image, IDENTITY);
      g.dispose();
    }

    //
    // Cache image and set xlink:href
    //
    cacheBufferedImage(imageElement, buf, generatorContext);
  }
Esempio n. 13
0
  public RenderedImage scale(RenderedImage renderedImage, int width) {
    if (width <= 0) {
      return renderedImage;
    }

    int imageHeight = renderedImage.getHeight();
    int imageWidth = renderedImage.getWidth();

    double factor = (double) width / imageWidth;

    int scaledHeight = (int) (factor * imageHeight);
    int scaledWidth = width;

    BufferedImage bufferedImage = getBufferedImage(renderedImage);

    int type = bufferedImage.getType();

    if (type == 0) {
      type = BufferedImage.TYPE_INT_ARGB;
    }

    BufferedImage scaledBufferedImage = new BufferedImage(scaledWidth, scaledHeight, type);

    Graphics graphics = scaledBufferedImage.getGraphics();

    Image scaledImage =
        bufferedImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);

    graphics.drawImage(scaledImage, 0, 0, null);

    return scaledBufferedImage;
  }
  /**
   * Constructs a <code>SubsampleBinaryToGray4x4OpImage</code> from a <code>RenderedImage</code>
   * source, an optional <code>BorderExtender</code>, x and y scale and translation factors, and an
   * <code>Interpolation</code> object. The image dimensions are determined by forward-mapping the
   * source bounds, and are passed to the superclass constructor by means of the <code>layout</code>
   * parameter. Other fields of the layout are passed through unchanged. If <code>layout</code> is
   * <code>null</code>, a new <code>ImageLayout</code> will be constructor to hold the bounds
   * information.
   *
   * <p>Note that the scale factors are represented internally as Rational numbers in order to
   * workaround inexact device specific representation of floating point numbers. For instance the
   * floating point number 1.2 is internally represented as 1.200001, which can throw the
   * calculations off during a forward/backward map.
   *
   * <p>The Rational approximation is valid upto the sixth decimal place.
   *
   * @param layout an <code>ImageLayout</code> optionally containing the tile grid layout, <code>
   *     SampleModel</code>, and <code>ColorModel</code>, or <code>null</code>.
   * @param source a <code>RenderedImage</code>.
   *     <p>from this <code>OpImage</code>, or <code>null</code>. If <code>null</code>, no caching
   *     will be performed.
   * @param cobbleSources a boolean indicating whether <code>computeRect</code> expects contiguous
   *     sources.
   * @param extender a <code>BorderExtender</code>, or <code>null</code>.
   * @param interp an <code>Interpolation</code> object to use for resampling.
   * @param scaleX scale factor along x axis.
   * @param scaleY scale factor along y axis.
   * @throws IllegalArgumentException if combining the source bounds with the layout parameter
   *     results in negative output width or height.
   */
  public SubsampleBinaryToGray4x4OpImage(RenderedImage source, ImageLayout layout, Map config) {

    super(
        vectorize(source),
        SubsampleBinaryToGrayOpImage.layoutHelper(source, 1.0F / 4, 1.0F / 4, layout, config),
        config,
        true, // cobbleSources,
        null, // extender
        null, // interpolation
        null);

    int srcWidth = source.getWidth();
    int srcHeight = source.getHeight();

    blockX = blockY = 4;

    dWidth = srcWidth / blockX;
    dHeight = srcHeight / blockY;

    if (extender == null) {
      computableBounds = new Rectangle(0, 0, dWidth, dHeight);
    } else {
      // If extender is present we can write the entire destination.
      computableBounds = getBounds();
    }

    // these can be delayed, such as placed in computeRect()
    buildLookupTables();

    // compute the begining bit position of each row and column
    computeXYValues(dWidth, dHeight);
  }
 private RenderedOp createScaledImage(
     RenderedImage sourceImage, S2Resolution resolution, int level) {
   int sourceWidth = sourceImage.getWidth();
   int sourceHeight = sourceImage.getHeight();
   int targetWidth = imageLayouts[0].width >> level;
   int targetHeight = imageLayouts[0].height >> level;
   float scaleX = (float) targetWidth / (float) sourceWidth;
   float scaleY = (float) targetHeight / (float) sourceHeight;
   float corrFactorX = resolution == S2Resolution.R20M ? R20M_X_FACTOR : R60M_X_FACTOR;
   float corrFactorY = resolution == S2Resolution.R20M ? R20M_Y_FACTOR : R60M_Y_FACTOR;
   final Dimension tileDim = getTileDim(targetWidth, targetHeight);
   ImageLayout imageLayout = new ImageLayout();
   imageLayout.setTileWidth(tileDim.width);
   imageLayout.setTileHeight(tileDim.height);
   RenderingHints renderingHints =
       new RenderingHints(
           JAI.KEY_BORDER_EXTENDER, BorderExtender.createInstance(BorderExtender.BORDER_ZERO));
   renderingHints.put(JAI.KEY_IMAGE_LAYOUT, imageLayout);
   RenderedOp scaledImage =
       ScaleDescriptor.create(
           sourceImage,
           scaleX * corrFactorX,
           scaleY * corrFactorY,
           0F,
           0F,
           Interpolation.getInstance(Interpolation.INTERP_NEAREST),
           renderingHints);
   if (scaledImage.getWidth() != targetWidth || scaledImage.getHeight() != targetHeight) {
     return CropDescriptor.create(
         scaledImage, 0.0F, 0.0F, (float) targetWidth, (float) targetHeight, null);
   } else {
     return scaledImage;
   }
 }
Esempio n. 16
0
  public void readDescendingRasterBand(
      final int sourceOffsetX,
      final int sourceOffsetY,
      final int sourceStepX,
      final int sourceStepY,
      final ProductData destBuffer,
      final int destOffsetX,
      final int destOffsetY,
      final int destWidth,
      final int destHeight,
      final int imageID,
      final ImageIOFile img,
      final int bandSampleOffset,
      final boolean isAntennaPointingRight)
      throws IOException {

    final Raster data;

    synchronized (dataDir) {
      final ImageReader reader = img.getReader();
      final ImageReadParam param = reader.getDefaultReadParam();
      param.setSourceSubsampling(
          sourceStepX, sourceStepY, sourceOffsetX % sourceStepX, sourceOffsetY % sourceStepY);

      final RenderedImage image = reader.readAsRenderedImage(0, param);
      if (flipToSARGeometry && isAntennaPointingRight) { // flip the image left to right
        data =
            image.getData(
                new Rectangle(
                    img.getSceneWidth() - destOffsetX - destWidth,
                    destOffsetY,
                    destWidth,
                    destHeight));
      } else {
        data = image.getData(new Rectangle(destOffsetX, destOffsetY, destWidth, destHeight));
      }
    }

    final DataBuffer dataBuffer = data.getDataBuffer();
    final SampleModel sampleModel = data.getSampleModel();
    final int sampleOffset = imageID + bandSampleOffset;

    if (flipToSARGeometry && isAntennaPointingRight) { // flip the image left to right
      final int[] dArray = new int[destWidth * destHeight];
      sampleModel.getSamples(0, 0, destWidth, destHeight, sampleOffset, dArray, dataBuffer);

      int srcStride, destStride;
      for (int r = 0; r < destHeight; r++) {
        srcStride = r * destWidth;
        destStride = r * destWidth + destWidth;
        for (int c = 0; c < destWidth; c++) {
          destBuffer.setElemIntAt(destStride - c - 1, dArray[srcStride + c]);
        }
      }
    } else { // no flipping is needed
      sampleModel.getSamples(
          0, 0, destWidth, destHeight, sampleOffset, (int[]) destBuffer.getElems(), dataBuffer);
    }
  }
Esempio n. 17
0
 public static void storeTiledTiff(RenderedImage image, String filePath) {
   final TIFFEncodeParam encodeParam = new TIFFEncodeParam();
   encodeParam.setTileSize(image.getTileWidth(), image.getTileHeight());
   encodeParam.setWriteTiled(true);
   encodeParam.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
   System.out.println("Storing tiled TIFF image to " + filePath + "...");
   FileStoreDescriptor.create(image, filePath, "TIFF", encodeParam, false, null);
 }
Esempio n. 18
0
 public static RenderedOp transformImage(
     RenderedImage image, double x0, double y0, double theta, double scale) {
   final AffineTransform transform = new AffineTransform();
   transform.rotate(theta, -0.5f * image.getWidth(), -0.5f * image.getHeight());
   transform.scale(scale, scale);
   transform.translate(x0, y0);
   return transformImage(image, transform);
 }
Esempio n. 19
0
 /** A wrapper for {@link #setImage(int, int, ByteBuffer, Rectangle, int)}. */
 private void setImage(RenderedImage image, Rectangle rect) throws IOException {
   setImage(
       image.getWidth(),
       image.getHeight(),
       ImageIOHelper.getImageByteBuffer(image),
       rect,
       image.getColorModel().getPixelSize());
 }
    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 testTileStackImage() throws Exception {
    final SunTileCache tileCache = (SunTileCache) JAI.getDefaultInstance().getTileCache();
    tileCache.flush();
    long cacheTileCount = tileCache.getCacheTileCount();
    assertEquals(0, cacheTileCount);

    Operator operator =
        new Operator() {
          @Override
          public void initialize() throws OperatorException {
            Product product = new Product("name", "desc", 1, 1);

            RenderedOp d =
                ConstantDescriptor.create(
                    (float) product.getSceneRasterWidth(),
                    (float) product.getSceneRasterHeight(),
                    new Float[] {0.5f},
                    null);

            product.addBand("a", ProductData.TYPE_INT32);
            product.addBand("b", ProductData.TYPE_INT32);
            product.addBand("c", ProductData.TYPE_INT32);
            product.addBand("d", ProductData.TYPE_FLOAT32).setSourceImage(d);
            setTargetProduct(product);
          }

          @Override
          public void computeTileStack(
              Map<Band, Tile> targetTiles, Rectangle targetRectangle, ProgressMonitor pm)
              throws OperatorException {
            assertEquals(3, targetTiles.size());

            for (Tile tt : targetTiles.values()) {
              ProductData dataBuffer = tt.getDataBuffer();
              int numElems = dataBuffer.getNumElems();
              for (int i = 0; i < numElems; i++) {
                dataBuffer.setElemIntAt(i, i);
              }
            }

            assertEquals(0, tileCache.getCacheTileCount());
          }
        };

    Product targetProduct = operator.getTargetProduct();
    assertNotNull(targetProduct);
    assertEquals(4, targetProduct.getNumBands());

    MultiLevelImage sourceImage = targetProduct.getBandAt(0).getSourceImage();
    RenderedImage image = sourceImage.getImage(0);
    assertNotNull(image);
    assertEquals(OperatorImageTileStack.class, image.getClass());
    // pull data to trigger computation
    image.getData();

    cacheTileCount = tileCache.getCacheTileCount();
    assertEquals(3, cacheTileCount);
  }
  // package accessible for SubsampleBinaryToGrayOpImage4x4, etc...
  static ImageLayout layoutHelper(
      RenderedImage source, float scaleX, float scaleY, ImageLayout il, Map config) {

    ImageLayout layout = (il == null) ? new ImageLayout() : (ImageLayout) il.clone();

    // to compute dWidth and dHeight
    // fTol and dWi, dHi must be the same as in computeDestInfo(..)
    // due to static method, a few lines of coding are repeated
    int srcWidth = source.getWidth();
    int srcHeight = source.getHeight();

    float f_dw = scaleX * srcWidth;
    float f_dh = scaleY * srcHeight;
    float fTol = .1F * Math.min(scaleX / (f_dw + 1.0F), scaleY / (f_dh + 1.0F));

    int dWi = (int) (f_dw);
    int dHi = (int) (f_dh);

    // let it be int in the almost int case
    //   espacially in the true int case with float calculation errors
    if (Math.abs(Math.round(f_dw) - f_dw) < fTol) {
      dWi = Math.round(f_dw);
    }

    if (Math.abs(Math.round(f_dh) - f_dh) < fTol) {
      dHi = Math.round(f_dh);
    }

    // Set the top left coordinate of the destination
    layout.setMinX((int) (scaleX * source.getMinX()));
    layout.setMinY((int) (scaleY * source.getMinY()));

    layout.setWidth(dWi);
    layout.setHeight(dHi);

    // sample model
    SampleModel sm = layout.getSampleModel(null);

    if (sm == null
        || sm.getDataType() != DataBuffer.TYPE_BYTE
        || !(sm instanceof PixelInterleavedSampleModel
            || sm instanceof SinglePixelPackedSampleModel && sm.getNumBands() == 1)) {

      // Width and height will be corrected in OpImage.layoutHelper
      sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, 1, 1, 1, 1, new int[] {0});
    }

    layout.setSampleModel(sm);

    ColorModel cm = layout.getColorModel(null);

    if (cm == null || !JDKWorkarounds.areCompatibleDataModels(sm, cm)) {

      layout.setColorModel(ImageUtil.getCompatibleColorModel(sm, config));
    }

    return layout;
  }
Esempio n. 23
0
  private boolean needToCreateIndex(RenderedImage image) {

    SampleModel sampleModel = image.getSampleModel();
    ColorModel colorModel = image.getColorModel();

    return sampleModel.getNumBands() != 1
        || sampleModel.getSampleSize()[0] > 8
        || colorModel.getComponentSize()[0] > 8;
  }
Esempio n. 24
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
  }
Esempio n. 25
0
  private void testAlphaRGB(boolean direct) {
    assertTrue("Assertions should be enabled.", ImageWorker.class.desiredAssertionStatus());
    ImageWorker worker = new ImageWorker(getSyntheticRGB(direct));
    worker.applyOpacity(0.5f);

    RenderedImage image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);
    assertTrue(image.getColorModel().hasAlpha());
    int sample = image.getTile(0, 0).getSample(0, 0, 3);
    assertEquals(128, sample);
  }
Esempio n. 26
0
 /**
  * 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);
 }
Esempio n. 27
0
  public static RenderedImage createRenderedImage(RenderedImage image, Color bkg) {
    if (bkg == null) return image;

    BufferedImage bufferedImage =
        new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
    g.setBackground(bkg);
    g.clearRect(0, 0, image.getWidth(), image.getHeight());
    g.drawRenderedImage(image, new AffineTransform());
    return bufferedImage;
  }
Esempio n. 28
0
 /**
  * Makes sure the image starts at 0,0, all images coming from files do but the ones coming from a
  * JAI chain might not
  *
  * @param image
  * @return
  */
 static final RenderedImage realignImage(RenderedImage image) {
   if (image.getMinX() > 0 || image.getMinY() > 0) {
     return new BufferedImage(
         image.getColorModel(),
         ((WritableRaster) image.getData()).createWritableTranslatedChild(0, 0),
         image.getColorModel().isAlphaPremultiplied(),
         null);
   } else {
     return image;
   }
 }
Esempio n. 29
0
  public RenderedImage transformImage(RenderedImage img) {

    if (!(img.getColorModel() instanceof IndexColorModel))
      throw new IllegalArgumentException(
          "Cannot transform this operations: doesn'three have IndexColorModel");

    IndexColorModel icm = (IndexColorModel) img.getColorModel();
    icm = transformMap(icm);
    RenderedImage retImg = ColorMapUtils.insertColorMap(img, icm);

    return retImg;
  }
Esempio n. 30
0
  @Test
  public void testOpacityGray() {
    assertTrue("Assertions should be enabled.", ImageWorker.class.desiredAssertionStatus());
    ImageWorker worker = new ImageWorker(gray);
    worker.applyOpacity(0.5f);

    RenderedImage image = worker.getRenderedImage();
    assertTrue(image.getColorModel() instanceof ComponentColorModel);
    assertTrue(image.getColorModel().hasAlpha());
    int sample = image.getTile(0, 0).getSample(0, 0, 1);
    assertEquals(128, sample);
  }