Exemplo 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
 }
Exemplo n.º 2
0
  /** Generate a tiled image that contains a view of the mask. */
  @SuppressWarnings("restriction")
  public TiledImage getMaskImage() {
    TiledImage ti =
        new TiledImage(
            0,
            0,
            mwidth,
            mheight,
            0,
            0,
            new PixelInterleavedSampleModel(
                DataBuffer.TYPE_BYTE, mwidth, mheight, 1, mwidth, Transform.bandstride),
            new ComponentColorModel(
                ColorSpace.getInstance(ColorSpace.CS_GRAY),
                false,
                false,
                ComponentColorModel.OPAQUE,
                DataBuffer.TYPE_BYTE));

    WritableRaster gradRaster = ti.getWritableTile(0, 0);
    DataBufferByte gradDB = (DataBufferByte) gradRaster.getDataBuffer();
    byte[] gradImageData = gradDB.getData();

    int maskwh = mwidth * mheight;
    for (int i = 0; i < maskwh; i++) gradImageData[i] = (byte) mask[i];

    return ti;
  }
  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;
  }
Exemplo n.º 4
0
  @Test
  public void testTranslatedImageTileGridROINoData() {
    // Testing color indexing with Nodata and ROI
    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();

    TiledImage image =
        new TiledImage(
            0,
            0,
            256,
            256,
            128,
            128,
            image_.getColorModel().createCompatibleSampleModel(256, 256),
            image_.getColorModel());
    image.set(image_);

    Range range = RangeFactory.create((byte) 255, (byte) 255);
    ROIShape roi = new ROIShape(new Rectangle(0, 0, 20, 20));
    RenderedImage indexed = quantize(image, roi, range, 1);
    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
    RenderedImage component = forceComponentColorModel(indexed);

    final double[][] coeff = new double[1][5];
    Arrays.fill(coeff[0], 0, 4, 1.0 / 4);
    component = BandCombineDescriptor.create(component, coeff, null, null, destinationNoData, null);

    StatsType[] stats = new StatsType[] {StatsType.EXTREMA};
    component =
        StatisticsDescriptor.create(component, 1, 1, null, null, false, new int[] {0}, stats, null);
    Statistics stat = ((Statistics[][]) component.getProperty(Statistics.STATS_PROPERTY))[0][0];
    double[] result = (double[]) stat.getResult();
    final double minimum = result[0];
    final double maximum = result[1];

    assertFalse(Math.abs(maximum - minimum) < TOLERANCE);
  }
Exemplo n.º 5
0
  public int getValue(int pos) {
    int b = (int) (pos / (width * height));
    pos -= b * width * height;
    int y = (int) (pos / width);
    int x = pos % width;

    return outImage.getSample(x, y, b);
  }
Exemplo n.º 6
0
  protected void setValue(int pos, int val) {

    int b = (int) (pos / (width * height));
    pos -= b * width * height;
    int y = (int) (pos / width);
    int x = pos % width;

    outImage.setSample(x, y, b, val);
  }
  @Test
  public void testTranslatedImageTileGrid() {
    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();

    TiledImage image =
        new TiledImage(
            0,
            0,
            256,
            256,
            128,
            128,
            image_.getColorModel().createCompatibleSampleModel(256, 256),
            image_.getColorModel());
    image.set(image_);

    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);
  }
Exemplo n.º 8
0
  protected void setValue(int pos, int sign, int tt) {
    int s = (sign == QuadOutputStream.PLUS) ? 1 : -1;

    int b = (int) (pos / (width * height));
    pos -= b * width * height;
    int y = (int) (pos / width);
    int x = pos % width;

    outImage.setSample(x, y, b, s * tt);
  }
Exemplo n.º 9
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]);
  }
Exemplo n.º 10
0
  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;
  }
Exemplo n.º 11
0
  /**
   * Creates a SampleOpImage with the given ParameterBlock if the SampleOpImage can handle the
   * particular ParameterBlock.
   */
  @Override
  public RenderedImage create(ParameterBlock paramBlock, RenderingHints renderHints) {
    PlanarImage source1 = (PlanarImage) paramBlock.getRenderedSource(0);
    if (source1 == null) {
      return null;
    }
    ROIShape shape = (ROIShape) paramBlock.getObjectParameter(0);
    if (shape == null) {
      return source1;
    }

    TiledImage image;
    if (ImageUtil.isBinary(source1.getSampleModel())) {
      image =
          new TiledImage(
              source1.getMinX(),
              source1.getMinY(),
              source1.getWidth(),
              source1.getHeight(),
              source1.getTileGridXOffset(),
              source1.getTileGridYOffset(),
              LayoutUtil.createBinarySampelModel(),
              LayoutUtil.createBinaryIndexColorModel());
    } else {
      // rgb cannot be null or have less than one value
      Byte[] rgb = (Byte[]) paramBlock.getObjectParameter(1);
      int nbands = source1.getSampleModel().getNumBands();
      if (rgb.length != nbands) {
        Byte fillVal = rgb[0];
        rgb = new Byte[nbands];
        Arrays.fill(rgb, fillVal);
      }

      image = ImageFiler.getEmptyTiledImage(rgb, source1.getWidth(), source1.getHeight());
    }

    image.set(source1, shape);
    return image;
  }
Exemplo n.º 12
0
  /** Simple method for image creation */
  private static RenderedImage createTestImage(
      int dataType, int width, int height, Number noDataValue, int bands) {
    // This values could be used for fill all the image
    byte valueB = 64;
    short valueUS = Short.MAX_VALUE / 4;
    short valueS = -50;
    int valueI = 100;
    float valueF = (255 / 2) * 5;
    double valueD = (255 / 1) * 4;

    // parameter block initialization
    int tileW = width / 8;
    int tileH = height / 8;
    int imageDim = width * height;

    final SampleModel sm;

    Byte crossValueByte = null;
    Short crossValueUShort = null;
    Short crossValueShort = null;
    Integer crossValueInteger = null;
    Float crossValueFloat = null;
    Double crossValueDouble = null;

    int numBands = bands;

    if (numBands == 3) {
      sm =
          new ComponentSampleModel(
              dataType, width, height, 3, width, new int[] {0, imageDim, imageDim * 2});
    } else {
      sm = new ComponentSampleModel(dataType, width, height, 1, width, new int[] {0});
    }

    switch (dataType) {
      case DataBuffer.TYPE_BYTE:
        crossValueByte = (Byte) noDataValue;
        break;
      case DataBuffer.TYPE_USHORT:
        crossValueUShort = (Short) noDataValue;
        break;
      case DataBuffer.TYPE_SHORT:
        crossValueShort = (Short) noDataValue;
        break;
      case DataBuffer.TYPE_INT:
        crossValueInteger = (Integer) noDataValue;
        break;
      case DataBuffer.TYPE_FLOAT:
        crossValueFloat = (Float) noDataValue;
        break;
      case DataBuffer.TYPE_DOUBLE:
        crossValueDouble = (Double) noDataValue;
        break;
      default:
        throw new IllegalArgumentException("Wrong data type");
    }

    // Create the constant operation.
    TiledImage used = new TiledImage(sm, tileW, tileH);

    for (int b = 0; b < numBands; b++) {
      for (int j = 0; j < width; j++) {
        for (int k = 0; k < height; k++) {
          // Addition of a cross on the image
          if (j == k || j == width - k - 1) {
            switch (dataType) {
              case DataBuffer.TYPE_BYTE:
                used.setSample(j, k, b, crossValueByte);
                break;
              case DataBuffer.TYPE_USHORT:
                used.setSample(j, k, b, crossValueUShort);
                break;
              case DataBuffer.TYPE_SHORT:
                used.setSample(j, k, b, crossValueShort);
                break;
              case DataBuffer.TYPE_INT:
                used.setSample(j, k, b, crossValueInteger);
                break;
              case DataBuffer.TYPE_FLOAT:
                used.setSample(j, k, b, crossValueFloat);
                break;
              case DataBuffer.TYPE_DOUBLE:
                used.setSample(j, k, b, crossValueDouble);
                break;
              default:
                throw new IllegalArgumentException("Wrong data type");
            }
            // If selected, the image could be filled
          } else
          // a little square of no data on the upper left is inserted
          if ((j >= 20) && (j < 50) && (k >= 20) && (k < 50)) {
            switch (dataType) {
              case DataBuffer.TYPE_BYTE:
                used.setSample(j, k, b, 0);
                break;
              case DataBuffer.TYPE_USHORT:
                used.setSample(j, k, b, 0);
                break;
              case DataBuffer.TYPE_SHORT:
                used.setSample(j, k, b, 0);
                break;
              case DataBuffer.TYPE_INT:
                used.setSample(j, k, b, 0);
                break;
              case DataBuffer.TYPE_FLOAT:
                used.setSample(j, k, b, 0);
                break;
              case DataBuffer.TYPE_DOUBLE:
                used.setSample(j, k, b, 0);
                break;
              default:
                throw new IllegalArgumentException("Wrong data type");
            }

            if ((j >= 30) && (j < 40) && (k >= 20) && (k < 30)) {
              switch (dataType) {
                case DataBuffer.TYPE_BYTE:
                  used.setSample(j, k, b, crossValueByte);
                  break;
                case DataBuffer.TYPE_USHORT:
                  used.setSample(j, k, b, crossValueUShort);
                  break;
                case DataBuffer.TYPE_SHORT:
                  used.setSample(j, k, b, crossValueShort);
                  break;
                case DataBuffer.TYPE_INT:
                  used.setSample(j, k, b, crossValueInteger);
                  break;
                case DataBuffer.TYPE_FLOAT:
                  used.setSample(j, k, b, crossValueFloat);
                  break;
                case DataBuffer.TYPE_DOUBLE:
                  used.setSample(j, k, b, crossValueDouble);
                  break;
                default:
                  throw new IllegalArgumentException("Wrong data type");
              }
            }
          } else {
            // No Data is set
            switch (dataType) {
              case DataBuffer.TYPE_BYTE:
                used.setSample(j, k, b, valueB + b);
                break;
              case DataBuffer.TYPE_USHORT:
                used.setSample(j, k, b, valueUS + b);
                break;
              case DataBuffer.TYPE_SHORT:
                used.setSample(j, k, b, valueS + b);
                break;
              case DataBuffer.TYPE_INT:
                used.setSample(j, k, b, valueI + b);
                break;
              case DataBuffer.TYPE_FLOAT:
                float data = valueF + b / 3.0f;
                used.setSample(j, k, b, data);
                break;
              case DataBuffer.TYPE_DOUBLE:
                double dataD = valueD + b / 3.0d;
                used.setSample(j, k, b, dataD);
                break;
              default:
                throw new IllegalArgumentException("Wrong data type");
            }
          }
        }
      }
    }
    return used;
  }
  public TiledImage makeQuadCurve(
      int lineBeginningX,
      int lineBeginningY,
      int lineEndingX,
      int lineEndingY,
      double slope1st,
      double slope2nd,
      Inspiram inspiram) {
    int width = inspiram.layers[inspiram.currentLayer].getWidth();
    int height = inspiram.layers[inspiram.currentLayer].getHeight();
    SampleModel mySampleModel =
        inspiram.layers[inspiram.currentLayer].getLayerImage().getSampleModel();
    int nbands = mySampleModel.getNumBands();
    Raster readableRaster = inspiram.layers[inspiram.currentLayer].getLayerImage().getData();
    WritableRaster writableRaster = readableRaster.createCompatibleWritableRaster();
    int[] pixels = new int[nbands * width * height];
    readableRaster.getPixels(0, 0, width, height, pixels);
    double yIntercept1st = findYIntercept(p1X, p1Y, slope1st);
    double yIntercept2nd = findYIntercept(p2X, p2Y, slope2nd);
    System.out.println(
        "Y-Intercept of 1st: "
            + findYIntercept(p0X, p0Y, slope1st)
            + "     Y-Intercept of 2nd: "
            + findYIntercept(p1X, p1Y, slope1st));
    int pixelIndexQ = 0;

    double x1first = p0X;
    double x2first = p1X;
    double y1first = p0Y;
    double y2first = p1Y;
    double x1second = p1X;
    double x2second = p2X;
    double y1second = p1Y;
    double y2second = p2Y;
    if (p0X >= p1X) {
      x1first = p1X;
      x2first = p0X;
      y1first = p1Y;
      y2first = p0Y;
    }
    if (p1X >= p2X) {
      x1second = p2X;
      x2second = p1X;
      y1second = p2Y;
      y2second = p1Y;
    }

    double repeatingXs1st = Math.abs(slope1st);
    double yPlus1st = 0;
    double repeatingXs2nd = Math.abs(slope2nd);
    double yPlus2nd = 0;

    Change change = new Change("QUAD Bezier Creation", inspiram.currentLayer);
    change.undoChange.addActionListener(change.createChangeUndoListener(inspiram));
    System.out.println("SLOPE: " + slope1st);
    for (double dub = .01; dub < 1.0; dub += .001) {

      // P's//
      double x1st = (x1first + ((x2first - x1first) * dub)); // X coordinate for 1st line
      double x2nd = (x1second + ((x2second - x1second) * dub)); // X coordinate for 2nd line
      double y1st =
          (slope1st * (x1first + ((x2first - x1first) * dub))
              + yIntercept1st); // Y coordinate for 1st line
      double y2nd =
          (slope2nd * (x1second + ((x2second - x1second) * dub))
              + yIntercept2nd); // Y coordinate for 2nd line.
      // End of P's//

      // Q's//
      double yDifferenceQ = y2nd - y1st;
      double xDifferenceQ = x2nd - x1st;
      double slopeQ = (((yDifferenceQ) / (xDifferenceQ)));
      double yInterceptQ = findYIntercept(x2nd, y2nd, slopeQ);
      double x1Q = x1st;
      double x2Q = x2nd;
      double y1Q = y1st;
      double y2Q = y2nd;
      if (x1st >= x2nd) {
        x1Q = x2nd;
        x2Q = x1st;
        y1Q = y2nd;
        y2Q = y1st;
      }
      double repeatingXsQ = Math.abs(slopeQ);
      double yPlusQ = 0;

      double xQ = (x1Q + ((x2Q - x1Q) * dub)); // X coordinate for q line
      double yQ = (slopeQ * (x1Q + ((x2Q - x1Q) * dub)) + yInterceptQ); // Y coordinate for q line
      // End of Q's//

      pixelIndexQ = (int) yQ * width * nbands + (int) xQ * nbands;

      PixelHistory pixelHistory = new PixelHistory((int) xQ, (int) yQ);
      if (!change.getAllPixelHistory().contains(pixelHistory.x)
          && !change.getAllPixelHistory().contains(pixelHistory.y)) {
        pixelHistory.setPrevR(pixels[(pixelIndexQ - 0) + (0)]);
        pixelHistory.setPrevG(pixels[(pixelIndexQ - 0) + (1)]);
        pixelHistory.setPrevB(pixels[(pixelIndexQ - 0) + (2)]);
        pixels[(pixelIndexQ - 0) + (0)] = 255;
        pixels[(pixelIndexQ - 0) + (1)] = 255;
        pixels[(pixelIndexQ - 0) + (2)] = 255;
        pixelHistory.setNewR(255);
        pixelHistory.setNewG(255);
        pixelHistory.setNewB(255);
        if (!change.getAllPixelHistory().contains(pixelHistory.x)
            && !change.getAllPixelHistory().contains(pixelHistory.y)) {
          change.getAllPixelHistory().add(pixelHistory);
        }
      }
    }
    inspiram.inspiramHistory.addChange(change);
    writableRaster.setPixels(0, 0, width, height, pixels);
    TiledImage ti = new TiledImage(inspiram.layers[inspiram.currentLayer].getLayerImage(), 1, 1);
    ti.setData(writableRaster);
    return ti;
  }
  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;
  }
Exemplo n.º 16
0
  public TiledImage cutFrame(
      RenderedImage image,
      double resdpi,
      int frameWidthPix,
      int frameHeightPix,
      boolean reverseImage,
      int frameNum,
      double scaleMult,
      boolean rescale,
      boolean correctrotation) {
    noCut = false;
    if (farEdge == null || farEdge.stdDev > worstEdgeStdDevAllowed) {
      System.out.println(
          "WARNING: far film edge for frame "
              + frameNum
              + " has a stdDev of "
              + (farEdge == null ? "null" : Double.toString(farEdge.stdDev))
              + " and will not be used.");

      if (sprocketEdge == null || sprocketEdge.stdDev > worstEdgeStdDevAllowed) {
        System.out.println(
            "WARNING: near film edge for frame "
                + frameNum
                + " has a stdDev of "
                + (sprocketEdge == null ? "null" : Double.toString(sprocketEdge.stdDev))
                + " and will not be used.");
        noCut = true;
        return null;
      } else
        preMapSetupUsingSprocketEdge(
            frameWidthPix, frameHeightPix, scaleMult, reverseImage, rescale, correctrotation);
    } else
      preMapSetupUsingFarEdge(
          frameWidthPix, frameHeightPix, scaleMult, reverseImage, rescale, correctrotation);

    outOfBounds = false;

    //      double resdpmm = resdpi / FilmSpec.mmPerInch;
    //      double [] spec = FilmSpec.filmModel(filmType);

    TiledImage ret =
        new TiledImage(
            0,
            0,
            frameWidthPix,
            frameHeightPix,
            0,
            0,
            image.getSampleModel().createCompatibleSampleModel(frameWidthPix, frameHeightPix),
            image.getColorModel());

    RenderedImage[] srcs = new RenderedImage[1];
    srcs[0] = image;
    RasterFormatTag[] tags = RasterAccessor.findCompatibleTags(srcs, ret);
    RasterFormatTag srctag = tags[0];
    RasterFormatTag dsttag = tags[1];

    Raster srcraster = image.getData();
    RasterAccessor srcra =
        new RasterAccessor(srcraster, srcraster.getBounds(), srctag, image.getColorModel());

    Raster dstraster = ret.getWritableTile(0, 0);
    RasterAccessor dstra =
        new RasterAccessor(dstraster, dstraster.getBounds(), dsttag, ret.getColorModel());

    int srcwidth = srcra.getWidth();
    int srcheight = srcra.getHeight();
    //      int srcbandcount = srcra.getNumBands();
    byte bandedsrc[][] = srcra.getByteDataArrays();
    int srcBandOffsets[] = srcra.getBandOffsets();
    int srcPixelStride = srcra.getPixelStride();
    int srcScanLineStride = srcra.getScanlineStride();

    int dstwidth = dstra.getWidth();
    int dstheight = dstra.getHeight();
    int dstbandcount = dstra.getNumBands();
    byte bandeddst[][] = dstra.getByteDataArrays();
    int dstBandOffsets[] = dstra.getBandOffsets();
    int dstPixelStride = dstra.getPixelStride();
    int dstScanLineStride = dstra.getScanlineStride();

    for (int band = 0; band < dstbandcount; band++) {
      byte dst[] = bandeddst[band];
      byte src[] = bandedsrc[band];
      int srcBegCurBand = srcBandOffsets[band];
      int dstBegCurRow = dstBandOffsets[band];
      for (int dstRow = 0; dstRow < dstheight; dstRow++) {
        int dstpos = dstBegCurRow;

        for (int dstCol = 0; dstCol < dstwidth; dstCol++) {
          Point srclocation = map(dstRow, dstCol, frameWidthPix, frameHeightPix, reverseImage);

          if (leftmostCol > srclocation.x) leftmostCol = srclocation.x;
          if (rightmostCol < srclocation.x) rightmostCol = srclocation.x;
          if (topmostRow > srclocation.y) topmostRow = srclocation.y;
          if (bottommostRow < srclocation.y) bottommostRow = srclocation.y;

          if (srclocation.y < 0
              || srclocation.y >= srcheight
              || srclocation.x < 0
              || srclocation.x >= srcwidth) {
            dst[dstpos] = (byte) 0;
            outOfBounds = true;
          } else
            dst[dstpos] =
                src[
                    srcBegCurBand
                        + ((srclocation.y * srcScanLineStride) + (srclocation.x * srcPixelStride))];

          dstpos += dstPixelStride;
        }

        dstBegCurRow += dstScanLineStride;
      }
    }

    frameCut = true;
    return ret;
  }