javax.media.jai.Interpolation Java Examples

The following examples show how to use javax.media.jai.Interpolation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WarpOpImage.java    From geowave with Apache License 2.0 6 votes vote down vote up
public WarpOpImage(
    final RenderedImage source,
    final ImageLayout layout,
    final Map<?, ?> configuration,
    final boolean cobbleSources,
    final BorderExtender extender,
    final Interpolation interp,
    final Warp warp,
    final double[] backgroundValues,
    final ROI roi,
    final Range noData) {
  super(
      source,
      layout,
      configuration,
      cobbleSources,
      extender,
      interp,
      warp,
      backgroundValues,
      roi,
      noData);
}
 
Example #2
Source File: RasterDataAdapter.java    From geowave with Apache License 2.0 6 votes vote down vote up
protected static byte interpolationToByte(final Interpolation interpolation) {
  // this is silly because it seems like a translation JAI should provide,
  // but it seems its not provided and its the most efficient approach
  // (rather than serializing class names)
  if (interpolation instanceof InterpolationNearest) {
    return Interpolation.INTERP_NEAREST;
  }
  if (interpolation instanceof InterpolationBilinear) {
    return Interpolation.INTERP_BILINEAR;
  }
  if (interpolation instanceof InterpolationBicubic2) {
    return Interpolation.INTERP_BICUBIC_2;
  }

  return Interpolation.INTERP_BICUBIC;
}
 
Example #3
Source File: RasterDataAdapter.java    From geowave with Apache License 2.0 6 votes vote down vote up
public MosaicPerPyramidLevelBuilder(
    final MultiDimensionalNumericData originalBounds,
    final GridCoverage originalData,
    final int tileSize,
    final double[] backgroundValuesPerBand,
    final Geometry footprint,
    final Interpolation defaultInterpolation,
    final CoordinateReferenceSystem crs) {
  this.originalBounds = originalBounds;
  this.originalData = originalData;
  this.tileSize = tileSize;
  this.backgroundValuesPerBand = backgroundValuesPerBand;
  this.footprint = footprint;
  this.defaultInterpolation = defaultInterpolation;
  this.crs = crs;
}
 
Example #4
Source File: OmsRasterResolutionResampler.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("nls")
@Execute
public void process() throws Exception {
    checkNull(inGeodata, pXres);
    if (pYres == null) {
        pYres = pXres;
    }
    JGTProcessingRegion region = new JGTProcessingRegion(inGeodata);
    region.setWEResolution(pXres);
    region.setNSResolution(pYres);

    GridGeometry2D newGridGeometry = region.getGridGeometry(inGeodata.getCoordinateReferenceSystem());

    Interpolation interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST);
    if (pInterpolation.equals(BILINEAR)) {
        interpolation = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
    } else if (pInterpolation.equals(BICUBIC)) {
        interpolation = Interpolation.getInstance(Interpolation.INTERP_BICUBIC);
    }

    pm.beginTask("Resampling...", IHMProgressMonitor.UNKNOWN);
    outGeodata = (GridCoverage2D) Operations.DEFAULT.resample(inGeodata, inGeodata.getCoordinateReferenceSystem(),
            newGridGeometry, interpolation);
    pm.done();
}
 
Example #5
Source File: RasterDataAdapter.java    From geowave with Apache License 2.0 6 votes vote down vote up
public RasterDataAdapter(
    final String coverageName,
    final SampleModel sampleModel,
    final ColorModel colorModel,
    final Map<String, String> metadata,
    final int tileSize,
    final double[][] noDataValuesPerBand,
    final double[] backgroundValuesPerBand,
    final boolean buildPyramid) {
  this(
      coverageName,
      sampleModel,
      colorModel,
      metadata,
      tileSize,
      noDataValuesPerBand,
      backgroundValuesPerBand,
      new HistogramConfig(sampleModel),
      true,
      Interpolation.INTERP_NEAREST,
      buildPyramid,
      new NoDataMergeStrategy());
}
 
Example #6
Source File: ImageFileAssistantPage1.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Image doInBackground() throws Exception {
    RenderedImage sourceImage = FileLoadDescriptor.create(imageFilePath, null, true, null);
    int width = sourceImage.getWidth();
    int height = sourceImage.getHeight();

    float scale = (float) (targetDimension.getWidth() / width);
    scale = (float) Math.min(scale, targetDimension.getHeight() / height);
    if (scale > 1) {
        scale = 1.0f;
    }

    Interpolation interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST);
    RenderedImage scaledImage = ScaleDescriptor.create(sourceImage,
                                                       scale, scale,
                                                       0.0f, 0.0f,
                                                       interpolation, null);
    PlanarImage planarImage = PlanarImage.wrapRenderedImage(scaledImage);
    BufferedImage bufferedImage = planarImage.getAsBufferedImage();
    planarImage.dispose();
    return bufferedImage;
}
 
Example #7
Source File: InterpolationValues.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Populate symbol type.
 *
 * @param symbolTypeConfig the symbol type config
 */
protected void populateSymbolType(SymbolTypeConfig symbolTypeConfig) {
    if (symbolTypeConfig != null) {
        for (Entry<Class<? extends Interpolation>, String> entry :
                interpolationMap.entrySet()) {
            symbolTypeConfig.addOption(entry.getKey().getSimpleName(), entry.getValue());
        }
    }
}
 
Example #8
Source File: WarpRIF.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of warp operator according to the warp object and interpolation method.
 *
 * @param paramBlock The warp and interpolation objects.
 */
@Override
public RenderedImage create(final ParameterBlock paramBlock, final RenderingHints renderHints) {
  final Interpolation interp = (Interpolation) paramBlock.getObjectParameter(1);
  if ((interp instanceof InterpolationNearest)
      || (interp instanceof javax.media.jai.InterpolationNearest)) {
    // Get ImageLayout from renderHints if any.
    final ImageLayout layout = RIFUtil.getImageLayoutHint(renderHints);

    RenderedImage source = paramBlock.getRenderedSource(0);
    final Warp warp = (Warp) paramBlock.getObjectParameter(0);
    final double[] backgroundValues = (double[]) paramBlock.getObjectParameter(2);

    ROI roi = null;
    final Object roi_ = paramBlock.getObjectParameter(3);
    if (roi_ instanceof ROI) {
      roi = (ROI) roi_;
      final PlanarImage temp = PlanarImage.wrapRenderedImage(source);
      temp.setProperty("ROI", roi);
      source = temp;
    }
    Range noData = (Range) paramBlock.getObjectParameter(4);
    noData = RangeFactory.convert(noData, source.getSampleModel().getDataType());
    return new WarpNearestOpImage(
        source,
        renderHints,
        layout,
        warp,
        interp,
        roi,
        noData,
        backgroundValues);
  }
  return super.create(paramBlock, renderHints);
}
 
Example #9
Source File: RasterUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static RasterDataAdapter createDataAdapterTypeDouble(
    final String coverageName,
    final int numBands,
    final int tileSize,
    final double[] minsPerBand,
    final double[] maxesPerBand,
    final String[] namesPerBand,
    final RasterTileMergeStrategy<?> mergeStrategy) {
  final double[][] noDataValuesPerBand = new double[numBands][];
  final double[] backgroundValuesPerBand = new double[numBands];
  final int[] bitsPerSample = new int[numBands];
  for (int i = 0; i < numBands; i++) {
    noDataValuesPerBand[i] = new double[] {Double.valueOf(Double.NaN)};
    backgroundValuesPerBand[i] = Double.valueOf(Double.NaN);
    bitsPerSample[i] = DataBuffer.getDataTypeSize(DataBuffer.TYPE_DOUBLE);
  }
  final SampleModel sampleModel = createRasterTypeDouble(numBands, tileSize).getSampleModel();
  return new RasterDataAdapter(
      coverageName,
      sampleModel,
      new ComponentColorModel(
          new BogusColorSpace(numBands),
          bitsPerSample,
          false,
          false,
          Transparency.OPAQUE,
          DataBuffer.TYPE_DOUBLE),
      new HashMap<String, String>(),
      tileSize,
      minsPerBand,
      maxesPerBand,
      namesPerBand,
      noDataValuesPerBand,
      backgroundValuesPerBand,
      null,
      false,
      Interpolation.INTERP_NEAREST,
      false,
      mergeStrategy);
}
 
Example #10
Source File: GeoWaveRasterReader.java    From geowave with Apache License 2.0 5 votes vote down vote up
public GridCoverage2D renderGridCoverage(
    final String coverageName,
    final Rectangle dim,
    final GeneralEnvelope generalEnvelope,
    Color backgroundColor,
    Color outputTransparentColor,
    final Interpolation interpolation) throws IOException {
  if (backgroundColor == null) {
    backgroundColor = AbstractGridFormat.BACKGROUND_COLOR.getDefaultValue();
  }
  if (outputTransparentColor == null) {
    outputTransparentColor = GeoWaveGTRasterFormat.OUTPUT_TRANSPARENT_COLOR.getDefaultValue();
  }

  final GeoWaveRasterReaderState state = new GeoWaveRasterReaderState(coverageName);
  state.setRequestedEnvelope(generalEnvelope);
  // /////////////////////////////////////////////////////////////////////
  //
  // Loading tiles trying to optimize as much as possible
  //
  // /////////////////////////////////////////////////////////////////////
  final GridCoverage2D coverage =
      loadTiles(
          coverageName,
          backgroundColor,
          outputTransparentColor,
          interpolation,
          dim,
          state,
          getCoordinateReferenceSystem(coverageName),
          getOriginalEnvelope(coverageName));

  return coverage;
}
 
Example #11
Source File: GeoWaveRasterConfig.java    From geowave with Apache License 2.0 5 votes vote down vote up
public Interpolation getInterpolationOverride() {
  if (!isInterpolationOverrideSet()) {
    throw new IllegalStateException("Interpolation Override is not set for this config");
  }

  return Interpolation.getInstance(interpolationOverride);
}
 
Example #12
Source File: WebPWriterTest.java    From webp-imageio with Apache License 2.0 5 votes vote down vote up
/**
 * Test method tests {@link WebPWriter} with image resize options.
 *
 * @throws IOException
 *            the test fails.
 */
@Test(dataProvider = "createImagesWithScaleOptions", enabled = true)
public void testImageWriterScale(final RenderedImage image, final float xScale,
      final float yScale, final String outputName) throws IOException {
   final String extension = outputName.substring(outputName.lastIndexOf(".") + 1);

   // Scale the image.
   final RenderedOp scaledImage = ScaleDescriptor.create(image, xScale, yScale, 0f, 0f,
         Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2), null);

   // get writer
   final ImageWriter imgWriter = ImageIO.getImageWritersByFormatName(extension).next();
   final ImageWriteParam imgWriteParams = new WebPWriteParam(null);
   final String testName = "ScaleOptions";
   final File file = createOutputFile(testName, outputName);
   final ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(file);
   try {
      imgWriter.setOutput(imageOutputStream);
      imgWriter.write(null, new IIOImage(scaledImage, null, null), imgWriteParams);
      final int length = (int) imageOutputStream.length();
      assertTrue(length > 0);
   } finally {
      try {
         imageOutputStream.close();
      } catch (final IOException e) {
      }
   }
}
 
Example #13
Source File: ProcessingUtils.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
public static RenderedImage resizeImage(RenderedImage image, int width, int height)
      throws InconsistentImageScale
{
   RenderedImage resizedImage=image;
   // Computes ratio and scale
   float scale=getScale(image.getWidth(),image.getHeight(),width,height);
   
   // Processing resize process
   ParameterBlock pb = new ParameterBlock();
   // The source image
   pb.addSource(resizedImage);
   // The xScale
   pb.add(scale);
   // The yScale
   pb.add(scale);
   // The x translation
   pb.add(0.0F);
   // The y translation
   pb.add(0.0F);
   // The interpolation
   pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC));
   resizedImage = JAI.create("scale", pb, null);
   
   LOGGER.debug("Image resized to : " + resizedImage.getWidth() + "x"
      + resizedImage.getHeight());
   
   return resizedImage;
}
 
Example #14
Source File: DistributedRenderOptions.java    From geowave with Apache License 2.0 4 votes vote down vote up
public List<Interpolation> getInterpolations() {
  if ((interpolationOrdinals != null) && !interpolationOrdinals.isEmpty()) {
    return Lists.transform(interpolationOrdinals, input -> Interpolation.getInstance(input));
  }
  return Collections.emptyList();
}
 
Example #15
Source File: DistributedRenderOptions.java    From geowave with Apache License 2.0 4 votes vote down vote up
public DistributedRenderOptions(
    final WMS wms,
    final WMSMapContent mapContent,
    final Style style) {
  optimizeLineWidth = DefaultWebMapService.isLineWidthOptimizationEnabled();
  maxFilters = DefaultWebMapService.getMaxFilterRules();

  transparent = mapContent.isTransparent();
  buffer = mapContent.getBuffer();
  angle = mapContent.getAngle();
  mapWidth = mapContent.getMapWidth();
  mapHeight = mapContent.getMapHeight();
  bgColor = mapContent.getBgColor();
  palette = mapContent.getPalette();
  renderScaleMethodAccurate =
      StreamingRenderer.SCALE_ACCURATE.equals(mapContent.getRendererScaleMethod());
  wmsIterpolationOrdinal = wms.getInterpolation().ordinal();
  maxErrors = wms.getMaxRenderingErrors();
  this.style = style;
  envelope = mapContent.getRenderingArea();

  final GetMapRequest request = mapContent.getRequest();
  final Object timeoutOption = request.getFormatOptions().get("timeout");
  int localMaxRenderTime = 0;
  if (timeoutOption != null) {
    try {
      // local render time is in millis, while WMS max render time is
      // in seconds
      localMaxRenderTime = Integer.parseInt(timeoutOption.toString()) / 1000;
    } catch (final NumberFormatException e) {
      LOGGER.warn("Could not parse format_option \"timeout\": " + timeoutOption, e);
    }
  }
  maxRenderTime = getMaxRenderTime(localMaxRenderTime, wms);
  isMetatile = request.isTiled() && (request.getTilesOrigin() != null);
  final Object antialiasObj = request.getFormatOptions().get("antialias");
  if (antialiasObj != null) {
    antialias = antialiasObj.toString();
  }

  if (request.getFormatOptions().get("kmplacemark") != null) {
    kmlPlacemark = ((Boolean) request.getFormatOptions().get("kmplacemark")).booleanValue();
  }
  // turn on advanced projection handling
  advancedProjectionHandlingEnabled = wms.isAdvancedProjectionHandlingEnabled();
  final Object advancedProjectionObj =
      request.getFormatOptions().get(WMS.ADVANCED_PROJECTION_KEY);
  if ((advancedProjectionObj != null)
      && "false".equalsIgnoreCase(advancedProjectionObj.toString())) {
    advancedProjectionHandlingEnabled = false;
    continuousMapWrapping = false;
  }
  final Object mapWrappingObj = request.getFormatOptions().get(WMS.ADVANCED_PROJECTION_KEY);
  if ((mapWrappingObj != null) && "false".equalsIgnoreCase(mapWrappingObj.toString())) {
    continuousMapWrapping = false;
  }
  final List<Interpolation> interpolations = request.getInterpolations();
  if ((interpolations == null) || interpolations.isEmpty()) {
    interpolationOrdinals = Collections.emptyList();
  } else {
    interpolationOrdinals =
        Lists.transform(interpolations, new Function<Interpolation, Integer>() {

          @Override
          public Integer apply(final Interpolation input) {
            if (input instanceof InterpolationNearest) {
              return Interpolation.INTERP_NEAREST;
            } else if (input instanceof InterpolationNearest) {
              return Interpolation.INTERP_NEAREST;
            } else if (input instanceof InterpolationNearest) {
              return Interpolation.INTERP_NEAREST;
            } else if (input instanceof InterpolationNearest) {
              return Interpolation.INTERP_NEAREST;
            }
            return Interpolation.INTERP_NEAREST;
          }
        });
  }
}
 
Example #16
Source File: OmsMapsViewer.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private void addImageMosaic( MapContent map ) throws Exception {
    if (inImageMosaics != null) {
        RasterSymbolizer sym = sf.getDefaultRasterSymbolizer();
        Style style = SLD.wrapSymbolizers(sym);

        final ParameterValue<Color> inTransp = AbstractGridFormat.INPUT_TRANSPARENT_COLOR.createValue();
        inTransp.setValue(Color.white);

        final ParameterValue<Color> outTransp = ImageMosaicFormat.OUTPUT_TRANSPARENT_COLOR.createValue();
        outTransp.setValue(Color.white);
        final ParameterValue<Color> backColor = ImageMosaicFormat.BACKGROUND_COLOR.createValue();
        backColor.setValue(Color.RED);
        final ParameterValue<Boolean> fading = ImageMosaicFormat.FADING.createValue();
        fading.setValue(true);

        final ParameterValue<Interpolation> interpol = ImageMosaicFormat.INTERPOLATION.createValue();
        interpol.setValue(new javax.media.jai.InterpolationBilinear());

        final ParameterValue<Boolean> resol = ImageMosaicFormat.ACCURATE_RESOLUTION.createValue();
        resol.setValue(true);

        
        final ParameterValue<Boolean> multiThread= ImageMosaicFormat.ALLOW_MULTITHREADING.createValue();
        multiThread.setValue(true);

        final ParameterValue<Boolean> usejai = ImageMosaicFormat.USE_JAI_IMAGEREAD.createValue();
        usejai.setValue(false);

        final ParameterValue<double[]> bkg = ImageMosaicFormat.BACKGROUND_VALUES.createValue();
        bkg.setValue(new double[]{0});

        GeneralParameterValue[] gp = new GeneralParameterValue[]{inTransp, multiThread};

        for( String imageMosaicPath : inImageMosaics ) {
            ImageMosaicReader imr = new ImageMosaicReader(new File(imageMosaicPath));
            GridReaderLayer layer = new GridReaderLayer(imr, style, gp);
            map.addLayer(layer);
        }
    }

}
 
Example #17
Source File: RasterDataAdapter.java    From geowave with Apache License 2.0 4 votes vote down vote up
public RasterDataAdapter(
    final String coverageName,
    final SampleModel sampleModel,
    final ColorModel colorModel,
    final Map<String, String> metadata,
    final int tileSize,
    final double[] minsPerBand,
    final double[] maxesPerBand,
    final String[] namesPerBand,
    final double[][] noDataValuesPerBand,
    final double[] backgroundValuesPerBand,
    final HistogramConfig histogramConfig,
    final boolean equalizeHistogram,
    final int interpolationType,
    final boolean buildPyramid,
    final RasterTileMergeStrategy<?> mergeStrategy) {
  staticInit();

  this.coverageName = coverageName;
  this.tileSize = tileSize;
  if ((sampleModel.getWidth() != tileSize) || (sampleModel.getHeight() != tileSize)) {
    this.sampleModel = sampleModel.createCompatibleSampleModel(tileSize, tileSize);
  } else {
    this.sampleModel = sampleModel;
  }
  this.colorModel = colorModel;
  this.metadata = metadata;
  this.minsPerBand = minsPerBand;
  this.maxesPerBand = maxesPerBand;
  this.namesPerBand = namesPerBand;
  this.noDataValuesPerBand = noDataValuesPerBand;
  this.backgroundValuesPerBand = backgroundValuesPerBand;
  // a null histogram config will result in histogram statistics not being
  // accumulated
  this.histogramConfig = histogramConfig;
  this.buildPyramid = buildPyramid;
  this.equalizeHistogram = equalizeHistogram;
  interpolation = Interpolation.getInstance(interpolationType);
  this.mergeStrategy = mergeStrategy;
  init();
}
 
Example #18
Source File: InterpolationValuesTest.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Test method for {@link
 * com.sldeditor.rendertransformation.types.InterpolationValues#InterpolationValues()}.
 */
@Test
void testInterpolationValues() {
    InterpolationValues testObj = new InterpolationValues();
    testObj.createInstance();

    assertEquals(Arrays.asList(Interpolation.class), testObj.getType());

    Interpolation interpolation = new InterpolationBicubic2(3);
    testObj.setDefaultValue(interpolation);
    assertEquals(
            String.format("%s(%d)", interpolation.getClass().getSimpleName(), 8),
            testObj.getExpression().toString());

    // Interpolation value
    testObj.setValue(ff.literal(interpolation.getClass().getSimpleName()));
    assertEquals(
            String.format("%s(%d)", InterpolationBicubic2.class.getSimpleName(), 8),
            testObj.getExpression().toString());

    interpolation = new InterpolationBilinear(8, null, false, 1.0, 1);
    testObj.setValue(ff.literal(interpolation.getClass().getSimpleName()));
    assertEquals(
            InterpolationBilinear.class.getSimpleName(), testObj.getExpression().toString());

    testObj.setValue(
            ff.literal(
                    String.format("%s(%d)", InterpolationBicubic.class.getSimpleName(), 16)));
    assertEquals(
            String.format("%s(%d)", InterpolationBicubic.class.getSimpleName(), 16),
            testObj.getExpression().toString());

    // Literal expression
    interpolation = new InterpolationNearest(null, false, 1.0, 1);
    Expression expectedExpression = ff.literal(interpolation.getClass().getSimpleName());
    testObj.setValue(expectedExpression);
    assertEquals(
            testObj.getExpression().toString(), InterpolationNearest.class.getSimpleName());

    // Attribute expression
    expectedExpression = ff.property("test");
    testObj.setValue(expectedExpression);
    assertNull(testObj.getExpression());

    // Not set
    testObj.setValue("");
    assertNull(testObj.getExpression());

    FieldConfigBase field =
            testObj.getField(
                    new FieldConfigCommonData(
                            InterpolationValues.class,
                            FieldIdEnum.INITIAL_GAP,
                            "label",
                            true,
                            false,
                            false));
    assertEquals(FieldConfigEnum.class, field.getClass());

    // Increase code coverage
    TestInterpolationValues testObj2 = new TestInterpolationValues();
    testObj2.populateSymbolType(null);

    SymbolTypeConfig config = new SymbolTypeConfig(String.class);
    testObj2.populateSymbolType(config);
    assertTrue(config.getKeyOrderList().size() > 0);
}
 
Example #19
Source File: RasterDataAdapter.java    From geowave with Apache License 2.0 4 votes vote down vote up
public Interpolation getInterpolation() {
  return interpolation;
}
 
Example #20
Source File: WarpNearestOpImage.java    From geowave with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a WarpNearestOpImage.
 *
 * @param source The source image.
 * @param config RenderingHints used in calculations.
 * @param layout The destination image layout.
 * @param warp An object defining the warp algorithm.
 * @param interp An object describing the interpolation method.
 * @param roi input ROI object used.
 * @param noData NoData Range object used for checking if NoData are present.
 */
public WarpNearestOpImage(
    final RenderedImage source,
    final Map<?, ?> config,
    final ImageLayout layout,
    final Warp warp,
    final Interpolation interp,
    final ROI sourceROI,
    final Range noData,
    final double[] bkg) {
  super(
      source,
      layout,
      config,
      false,
      null, // extender not needed in
      // nearest-neighbor
      // interpolation
      interp,
      warp,
      bkg,
      sourceROI,
      noData);

  /*
   * If the source has IndexColorModel, override the default setting in OpImage. The dest shall
   * have exactly the same SampleModel and ColorModel as the source. Note, in this case, the
   * source should have an integral data type.
   */
  final ColorModel srcColorModel = source.getColorModel();
  if (srcColorModel instanceof IndexColorModel) {
    sampleModel = source.getSampleModel().createCompatibleSampleModel(tileWidth, tileHeight);
    colorModel = srcColorModel;
  }

  /*
   * Selection of a destinationNoData value for each datatype
   */
  final SampleModel sm = source.getSampleModel();
  // Source image data Type
  final int srcDataType = sm.getDataType();

  // Creation of a lookuptable containing the values to use for no data
  if ((srcDataType == DataBuffer.TYPE_BYTE) && hasNoData) {
    final int numBands = getNumBands();
    byteLookupTable = new byte[numBands][256];
    for (int b = 0; b < numBands; b++) {
      for (int i = 0; i < byteLookupTable[0].length; i++) {
        final byte value = (byte) i;
        if (noDataRange.contains(value)) {
          byteLookupTable[b][i] = (byte) backgroundValues[b];
        } else {
          byteLookupTable[b][i] = value;
        }
      }
    }
  }
}
 
Example #21
Source File: InterpolationValues.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<Class<?>> getType() {
    return Arrays.asList(Interpolation.class);
}
 
Example #22
Source File: InterpolationValues.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void setDefaultValue(Object defaultValue) {
    this.value = (Interpolation) defaultValue;
}
 
Example #23
Source File: LandsatIT.java    From geowave with Apache License 2.0 4 votes vote down vote up
@Test
public void testMosaic() throws Exception {

  // Skip this test if we're on a Mac
  org.junit.Assume.assumeTrue(isNotMac());

  JAIExt.initJAIEXT();
  MapProjection.SKIP_SANITY_CHECKS = true;
  // just use the QA band as QA is the smallest, get the best cloud cover,
  // but ensure it is before now so no recent collection affects the test
  final Landsat8BasicCommandLineOptions analyzeOptions = new Landsat8BasicCommandLineOptions();
  analyzeOptions.setCqlFilter(
      String.format(
          "BBOX(%s,%f,%f,%f,%f) AND %s='B4' AND %s <= '%s' AND path >= %d AND path <= %d AND row >= %d AND row <= %d",
          SceneFeatureIterator.SHAPE_ATTRIBUTE_NAME,
          WEST,
          SOUTH,
          EAST,
          NORTH,
          BandFeatureIterator.BAND_ATTRIBUTE_NAME,
          SceneFeatureIterator.ACQUISITION_DATE_ATTRIBUTE_NAME,
          "2016-06-01T00:00:00Z",
          MIN_PATH,
          MAX_PATH,
          MIN_ROW,
          MAX_ROW));
  analyzeOptions.setNBestPerSpatial(true);
  analyzeOptions.setNBestScenes(1);
  analyzeOptions.setUseCachedScenes(true);
  final Landsat8DownloadCommandLineOptions downloadOptions =
      new Landsat8DownloadCommandLineOptions();
  final Landsat8RasterIngestCommandLineOptions ingestOptions =
      new Landsat8RasterIngestCommandLineOptions();
  ingestOptions.setRetainImages(true);
  ingestOptions.setCreatePyramid(true);
  ingestOptions.setCreateHistogram(true);
  ingestOptions.setCoverageName("test");
  // crop to the specified bbox
  ingestOptions.setCropToSpatialConstraint(true);
  final RasterIngestTester runner =
      new RasterIngestTester(
          dataStoreOptions,
          analyzeOptions,
          downloadOptions,
          ingestOptions,
          null);
  runner.runInternal(null);

  final StringBuilder str =
      new StringBuilder(StoreFactoryOptions.GEOWAVE_NAMESPACE_OPTION).append("=").append(
          dataStoreOptions.getGeoWaveNamespace()).append(
              ";equalizeHistogramOverride=false;interpolationOverride=").append(
                  Interpolation.INTERP_NEAREST);

  str.append(";").append(GeoWaveStoreFinder.STORE_HINT_KEY).append("=").append(
      dataStoreOptions.getType());

  final Map<String, String> options = dataStoreOptions.getOptionsAsMap();

  for (final Entry<String, String> entry : options.entrySet()) {
    if (!entry.getKey().equals(StoreFactoryOptions.GEOWAVE_NAMESPACE_OPTION)) {
      str.append(";").append(entry.getKey()).append("=").append(entry.getValue());
    }
  }
  final GeneralEnvelope queryEnvelope =
      new GeneralEnvelope(new double[] {WEST, SOUTH}, new double[] {EAST, NORTH});
  queryEnvelope.setCoordinateReferenceSystem(GeometryUtils.getDefaultCRS());

  final GeoWaveRasterReader reader =
      new GeoWaveRasterReader(GeoWaveRasterConfig.readFromConfigParams(str.toString()));
  final GridCoverage2D gridCoverage =
      reader.renderGridCoverage(
          "test",
          new Rectangle(0, 0, 1024, 1024),
          queryEnvelope,
          null,
          null,
          null);
  final RenderedImage result = gridCoverage.getRenderedImage();

  // test the result with expected, allowing for minimal error
  final BufferedImage reference = ImageIO.read(new File(REFERENCE_LANDSAT_IMAGE_PATH));
  TestUtils.testTileAgainstReference(
      PlanarImage.wrapRenderedImage(result).getAsBufferedImage(),
      reference,
      0,
      0.005);
  MapProjection.SKIP_SANITY_CHECKS = false;
}
 
Example #24
Source File: CustomCRSKDERasterResizeIT.java    From geowave with Apache License 2.0 4 votes vote down vote up
private double[][][] testSamplesMatch(
    final String coverageNamePrefix,
    final int numCoverages,
    final GeneralEnvelope queryEnvelope,
    final Rectangle pixelDimensions,
    double[][][] expectedResults) throws Exception {
  final StringBuilder str =
      new StringBuilder(StoreFactoryOptions.GEOWAVE_NAMESPACE_OPTION).append("=").append(
          TEST_COVERAGE_NAMESPACE).append(
              ";equalizeHistogramOverride=false;scaleTo8Bit=false;interpolationOverride=").append(
                  Interpolation.INTERP_NEAREST);

  str.append(";").append(GeoWaveStoreFinder.STORE_HINT_KEY).append("=").append(
      outputDataStorePluginOptions.getType());

  final Map<String, String> options = outputDataStorePluginOptions.getOptionsAsMap();

  for (final Entry<String, String> entry : options.entrySet()) {
    if (!entry.getKey().equals(StoreFactoryOptions.GEOWAVE_NAMESPACE_OPTION)) {
      str.append(";").append(entry.getKey()).append("=").append(entry.getValue());
    }
  }

  final GeoWaveRasterReader reader =
      new GeoWaveRasterReader(GeoWaveRasterConfig.readFromConfigParams(str.toString()));

  queryEnvelope.setCoordinateReferenceSystem(CRS.decode("EPSG:4166", true));
  final Raster[] rasters = new Raster[numCoverages];
  int coverageCount = 0;
  for (int i = MIN_TILE_SIZE_POWER_OF_2; i <= MAX_TILE_SIZE_POWER_OF_2; i += INCREMENT) {
    final String tileSizeCoverageName = coverageNamePrefix + i;
    final GridCoverage gridCoverage =
        reader.renderGridCoverage(
            tileSizeCoverageName,
            pixelDimensions,
            queryEnvelope,
            Color.BLACK,
            null,
            null);
    final RenderedImage image = gridCoverage.getRenderedImage();
    final Raster raster = image.getData();
    rasters[coverageCount++] = raster;
  }
  boolean atLeastOneResult = expectedResults != null;
  for (int i = 0; i < numCoverages; i++) {
    final boolean initialResults = expectedResults == null;
    if (initialResults) {
      expectedResults =
          new double[rasters[i].getWidth()][rasters[i].getHeight()][rasters[i].getNumBands()];
    } else {
      Assert.assertEquals(
          "The expected width does not match the expected width for the coverage " + i,
          expectedResults.length,
          rasters[i].getWidth());
      Assert.assertEquals(
          "The expected height does not match the expected height for the coverage " + i,
          expectedResults[0].length,
          rasters[i].getHeight());
      Assert.assertEquals(
          "The expected number of bands does not match the expected bands for the coverage " + i,
          expectedResults[0][0].length,
          rasters[i].getNumBands());
    }
    long mismatchedSamples = 0;
    for (int y = 0; y < rasters[i].getHeight(); y++) {
      for (int x = 0; x < rasters[i].getWidth(); x++) {
        for (int b = 0; b < rasters[i].getNumBands(); b++) {
          final double sample = rasters[i].getSampleDouble(x, y, b);
          if (initialResults) {
            expectedResults[x][y][b] = sample;
            if (!atLeastOneResult && (sample != 0)) {
              atLeastOneResult = true;
            }
          } else {
            if ((Double.isNaN(sample) && !Double.isNaN(expectedResults[x][y][b]))
                || (!Double.isNaN(sample) && Double.isNaN(expectedResults[x][y][b]))
                || (Math.abs(expectedResults[x][y][b] - sample) > TestUtils.DOUBLE_EPSILON)) {
              mismatchedSamples++;
            }
          }
        }
      }
    }
    final double percentMismatch =
        mismatchedSamples
            / (double) (rasters[i].getWidth()
                * rasters[i].getHeight()
                * rasters[i].getNumBands());
    Assert.assertTrue(
        (percentMismatch * 100) + "% mismatch is less than 1%",
        percentMismatch < 0.01);
  }
  Assert.assertTrue("There should be at least one value that is not black", atLeastOneResult);
  return expectedResults;
}