Example usage for java.awt.image.renderable ParameterBlock set

List of usage examples for java.awt.image.renderable ParameterBlock set

Introduction

In this page you can find the example usage for java.awt.image.renderable ParameterBlock set.

Prototype

public ParameterBlock set(double d, int index) 

Source Link

Document

Replaces an Object in the list of parameters with a Double.

Usage

From source file:it.geosolutions.jaiext.JAIEXTTest.java

@Test
public void testInterpolation() {
    // Getting the registry
    ConcurrentOperationRegistry registry = JAIExt.getRegistry();
    // Using JAI-EXT for changing the descriptor from JAI-EXT to JAI
    JAIExt.registerJAIDescriptor(SCALE);

    // NEAREST INTERPOLATION

    // Trying to execute the Scale operation by passing JAI-EXT interpolation objects
    // and checking if the registry is able to convert them to JAI interpolation objects
    Object[] args = new Object[1];
    ParameterBlock block = new ParameterBlock();
    // Setting of a JAIEXT interpolation object
    block.set(new InterpolationNearest(null, false, 0, 0), 0);
    // Setting of the parameterblock
    args[0] = block;//from ww w.j a  va 2 s  .  c o m
    registry.checkInterpolation(SCALE, args);

    // Ensure that the modified parameterblock contains a JAI interpolation object
    Object interp = block.getObjectParameter(0);
    assertTrue(interp.getClass().isAssignableFrom(javax.media.jai.InterpolationNearest.class));

    // BILINEAR INTERPOLATION

    // Trying to execute the Scale operation by passing JAI-EXT interpolation objects
    // and checking if the registry is able to convert them to JAI interpolation objects
    args = new Object[1];
    block = new ParameterBlock();
    // Setting of a JAIEXT interpolation object
    int subsampleBits = 8;
    block.set(new InterpolationBilinear(subsampleBits, null, false, 0, 0), 0);
    // Setting of the parameterblock
    args[0] = block;
    registry.checkInterpolation(SCALE, args);

    // Ensure that the modified parameterblock contains a JAI interpolation object
    interp = block.getObjectParameter(0);
    assertTrue(interp.getClass().isAssignableFrom(javax.media.jai.InterpolationBilinear.class));
    assertTrue(((javax.media.jai.InterpolationBilinear) interp).getSubsampleBitsH() == subsampleBits);

    // BICUBIC INTERPOLATION

    // Trying to execute the Scale operation by passing JAI-EXT interpolation objects
    // and checking if the registry is able to convert them to JAI interpolation objects
    args = new Object[1];
    block = new ParameterBlock();
    // Setting of a JAIEXT interpolation object
    block.set(new InterpolationBicubic(subsampleBits, null, false, 0, 0, true, subsampleBits), 0);
    // Setting of the parameterblock
    args[0] = block;
    registry.checkInterpolation(SCALE, args);

    // Ensure that the modified parameterblock contains a JAI interpolation object
    interp = block.getObjectParameter(0);
    assertTrue(interp.getClass().isAssignableFrom(javax.media.jai.InterpolationBicubic.class));
    assertTrue(((javax.media.jai.InterpolationBicubic) interp).getSubsampleBitsH() == subsampleBits);
    assertTrue(((javax.media.jai.InterpolationBicubic) interp).getPrecisionBits() == subsampleBits);

    // BICUBIC 2 INTERPOLATION

    // Trying to execute the Scale operation by passing JAI-EXT interpolation objects
    // and checking if the registry is able to convert them to JAI interpolation objects
    args = new Object[1];
    block = new ParameterBlock();
    // Setting of a JAIEXT interpolation object
    block.set(new InterpolationBicubic(subsampleBits, null, false, 0, 0, false, subsampleBits), 0);
    // Setting of the parameterblock
    args[0] = block;
    registry.checkInterpolation(SCALE, args);

    // Ensure that the modified parameterblock contains a JAI interpolation object
    interp = block.getObjectParameter(0);
    assertTrue(interp.getClass().isAssignableFrom(javax.media.jai.InterpolationBicubic2.class));
    assertTrue(((javax.media.jai.InterpolationBicubic2) interp).getSubsampleBitsH() == subsampleBits);
    assertTrue(((javax.media.jai.InterpolationBicubic2) interp).getPrecisionBits() == subsampleBits);
}

From source file:org.geoserver.wps.gs.soilsealing.ChangeMatrixProcess.java

/**
 * @param classes representing the domain of the classes (Mandatory, not empty)
 * @param rasterT0 that is the reference Image (Mandatory)
 * @param rasterT1 rasterT1 that is the update situation (Mandatory)
 * @param roi that identifies the optional ROI (so that could be null)
 * @param JCUDA that indicates if the ChangeMatrix must be calculated using JCUDA or the JAI (could be null, default false)
 * @return/*from   w  ww .j a  v a 2s  .  c o  m*/
 */
@DescribeResult(name = "changeMatrix", description = "the ChangeMatrix", type = ChangeMatrixDTO.class)
public ChangeMatrixDTO execute(
        @DescribeParameter(name = "name", description = "Name of the raster, optionally fully qualified (workspace:name)") String referenceName,
        @DescribeParameter(name = "defaultStyle", description = "Name of the raster default style") String defaultStyle,
        @DescribeParameter(name = "storeName", description = "Name of the destination data store to log info") String storeName,
        @DescribeParameter(name = "typeName", description = "Name of the destination feature type to log info") String typeName,
        @DescribeParameter(name = "referenceFilter", description = "Filter to use on the raster data", min = 1) Filter referenceFilter,
        @DescribeParameter(name = "nowFilter", description = "Filter to use on the raster data", min = 1) Filter nowFilter,
        @DescribeParameter(name = "classes", collectionType = Integer.class, min = 1, description = "The domain of the classes used in input rasters") Set<Integer> classes,
        @DescribeParameter(name = "ROI", min = 0, description = "Region Of Interest") Geometry roi,
        @DescribeParameter(name = "JCUDA", min = 0, description = "Calculation of the ChangeMatrix by using JCUDA") Boolean jCudaEnabled)
        throws IOException {

    // DEBUG OPTION
    if (DEBUG) {
        return getTestMap();
    }

    // Check if JCUDA must be used for calculations
    boolean jcuda = false;
    if (jCudaEnabled != null) {
        jcuda = jCudaEnabled;
    }

    // get the original Coverages
    CoverageInfo ciReference = catalog.getCoverageByName(referenceName);
    if (ciReference == null) {
        throw new WPSException("Could not find coverage " + referenceName);
    }

    // ///////////////////////////////////////////////
    // ChangeMatrix outcome variables ...
    RenderedImage result = null;
    GridCoverage2D nowCoverage = null;
    GridCoverage2D referenceCoverage = null;
    ROI roiObj = null;
    // ///////////////////////////////////////////////

    // ///////////////////////////////////////////////
    // Logging to WFS variables ...
    final String wsName = ciReference.getNamespace().getPrefix();
    final UUID uuid = UUID.randomUUID();
    SimpleFeatureCollection features = null;
    Filter filter = null;
    ToFeature toFeatureProcess = new ToFeature();
    WFSLog wfsLogProcess = new WFSLog(geoserver);
    // ///////////////////////////////////////////////

    try {

        // read reference coverage
        GridCoverageReader referenceReader = ciReference.getGridCoverageReader(null, null);
        ParameterValueGroup readParametersDescriptor = referenceReader.getFormat().getReadParameters();

        // get params for this coverage and override what's needed
        Map<String, Serializable> defaultParams = ciReference.getParameters();
        GeneralParameterValue[] params = CoverageUtils.getParameters(readParametersDescriptor, defaultParams,
                false);
        // GridGeometry object used if ROI is used
        GridGeometry2D gridROI = null;

        // handle Region Of Interest
        if (roi != null) {
            if (roi instanceof GeometryCollection) {
                List<Polygon> geomPolys = new ArrayList<Polygon>();
                for (int g = 0; g < ((GeometryCollection) roi).getNumGeometries(); g++) {
                    CoverageUtilities.extractPolygons(geomPolys, ((GeometryCollection) roi).getGeometryN(g));
                }

                if (geomPolys.size() == 0) {
                    roi = GEOMETRY_FACTORY.createPolygon(null, null);
                } else if (geomPolys.size() == 1) {
                    roi = geomPolys.get(0);
                } else {
                    roi = roi.getFactory().createMultiPolygon(geomPolys.toArray(new Polygon[geomPolys.size()]));
                }
            }

            //
            // Make sure the provided roi intersects the layer BBOX in wgs84
            //
            final ReferencedEnvelope wgs84BBOX = ciReference.getLatLonBoundingBox();
            roi = roi.intersection(JTS.toGeometry(wgs84BBOX));
            if (roi.isEmpty()) {
                throw new WPSException("The provided ROI does not intersect the reference data BBOX: ",
                        roi.toText());
            }

            // Geometry associated with the ROI
            Geometry roiPrj = null;

            //
            // GRID TO WORLD preparation from reference
            //
            final AffineTransform gridToWorldCorner = (AffineTransform) ((GridGeometry2D) ciReference.getGrid())
                    .getGridToCRS2D(PixelOrientation.UPPER_LEFT);

            // check if we need to reproject the ROI from WGS84 (standard in the input) to the reference CRS
            final CoordinateReferenceSystem crs = ciReference.getCRS();
            if (CRS.equalsIgnoreMetadata(crs, DefaultGeographicCRS.WGS84)) {
                roiPrj = roi;
                roiObj = CoverageUtilities.prepareROI2(roi, gridToWorldCorner);
            } else {
                // reproject
                MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, crs, true);
                if (transform.isIdentity()) {
                    roiPrj = roi;
                } else {
                    roiPrj = JTS.transform(roi, transform);
                }
                roiObj = CoverageUtilities.prepareROIGeometry(roiPrj, gridToWorldCorner);
            }
            //
            // Make sure the provided area intersects the layer BBOX in the layer CRS
            //
            final ReferencedEnvelope crsBBOX = ciReference.boundingBox();
            roiPrj = roiPrj.intersection(JTS.toGeometry(crsBBOX));
            if (roiPrj.isEmpty()) {
                throw new WPSException("The provided ROI does not intersect the reference data BBOX: ",
                        roiPrj.toText());
            }

            // Creation of a GridGeometry object used for forcing the reader
            Envelope envelope = roiPrj.getEnvelopeInternal();
            // create with supplied crs
            Envelope2D bounds = JTS.getEnvelope2D(envelope, crs);
            // Creation of a GridGeometry2D instance used for cropping the input images
            gridROI = new GridGeometry2D(PixelInCell.CELL_CORNER, (MathTransform) gridToWorldCorner, bounds,
                    null);
        }

        // merge filter
        params = CoverageUtilities.replaceParameter(params, referenceFilter, ImageMosaicFormat.FILTER);
        // merge USE_JAI_IMAGEREAD to false if needed
        params = CoverageUtilities.replaceParameter(params, !jcuda, ImageMosaicFormat.USE_JAI_IMAGEREAD);
        if (gridROI != null) {
            params = CoverageUtilities.replaceParameter(params, gridROI,
                    AbstractGridFormat.READ_GRIDGEOMETRY2D);
        }
        referenceCoverage = (GridCoverage2D) referenceReader.read(params);

        if (referenceCoverage == null) {
            throw new WPSException("Input Reference Coverage not found");
        }

        // read now coverage
        readParametersDescriptor = referenceReader.getFormat().getReadParameters();
        // get params for this coverage and override what's needed
        defaultParams = ciReference.getParameters();
        params = CoverageUtils.getParameters(readParametersDescriptor, defaultParams, false);

        // merge filter
        params = CoverageUtilities.replaceParameter(params, nowFilter, ImageMosaicFormat.FILTER);
        // merge USE_JAI_IMAGEREAD to false if needed
        params = CoverageUtilities.replaceParameter(params, !jcuda, ImageMosaicFormat.USE_JAI_IMAGEREAD);
        if (gridROI != null) {
            params = CoverageUtilities.replaceParameter(params, gridROI,
                    AbstractGridFormat.READ_GRIDGEOMETRY2D);
        }
        // TODO add tiling, reuse standard values from config
        // TODO add background value, reuse standard values from config
        nowCoverage = (GridCoverage2D) referenceReader.read(params);

        if (nowCoverage == null) {
            throw new WPSException("Input Current Coverage not found");
        }

        // Definition of the final raster name
        final String rasterName = ciReference.getName() + "_cm_" + System.nanoTime();

        // //////////////////////////////////////////////////////////////////////
        // Logging to WFS ...
        // //////////////////////////////////////////////////////////////////////
        /**
         * Convert the spread attributes into a FeatureType
         */
        List<FeatureAttribute> attributes = new ArrayList<FeatureAttribute>();

        attributes.add(new FeatureAttribute("ftUUID", uuid.toString()));
        attributes.add(new FeatureAttribute("runBegin", new Date()));
        attributes.add(new FeatureAttribute("runEnd", new Date()));
        attributes.add(new FeatureAttribute("itemStatus", "RUNNING"));
        attributes.add(new FeatureAttribute("itemStatusMessage", "Instrumented by Server"));
        attributes.add(new FeatureAttribute("referenceName", referenceName));
        attributes.add(new FeatureAttribute("defaultStyle", defaultStyle));
        attributes.add(new FeatureAttribute("referenceFilter", referenceFilter.toString()));
        attributes.add(new FeatureAttribute("nowFilter", nowFilter.toString()));
        attributes.add(new FeatureAttribute("roi", roi.getEnvelope()));
        attributes.add(new FeatureAttribute("wsName", wsName));
        attributes.add(new FeatureAttribute("layerName", ""));
        attributes.add(new FeatureAttribute("changeMatrix", ""));

        features = toFeatureProcess.execute(JTS.toGeometry(ciReference.getNativeBoundingBox()),
                ciReference.getCRS(), typeName, attributes, null);

        if (features == null || features.isEmpty()) {
            throw new ProcessException("There was an error while converting attributes into FeatureType.");
        }

        /**
         * LOG into the DB
         */
        filter = ff.equals(ff.property("ftUUID"), ff.literal(uuid.toString()));
        features = wfsLogProcess.execute(features, typeName, wsName, storeName, filter, true,
                new NullProgressListener());

        if (features == null || features.isEmpty()) {
            throw new ProcessException("There was an error while logging FeatureType into the storage.");
        }

        // //////////////////////////////////////////////////////////////////////
        // Compute the Change Matrix ...
        // //////////////////////////////////////////////////////////////////////

        String refYear = null;
        String nowYear = null;

        Pattern pattern = Pattern.compile("(\\d{4}?)");
        if (referenceFilter != null) {
            Matcher matcher = pattern.matcher(referenceFilter.toString());
            if (matcher.find()) {
                refYear = matcher.group(1);
            }
        }

        if (nowFilter != null) {
            Matcher matcher = pattern.matcher(nowFilter.toString());
            if (matcher.find()) {
                nowYear = matcher.group(1);
            }
        }
        // Calculation of the Area Image
        GridGeometry2D gg2D = referenceCoverage.getGridGeometry();
        ParameterBlock pb = new ParameterBlock();
        pb.setSource(referenceCoverage.getRenderedImage(), 0);
        pb.set(new ReferencedEnvelope(gg2D.getEnvelope()), 0);
        pb.set(HACONVERTER, 1);
        pb.set(classes, 2);
        if (roiObj != null) {
            pb.set(roiObj, 3);
        }
        RenderedOp areaImage = JAI.create("area", pb);

        // Selection of the Object used for calculating the ChangeMatrix
        ChangeMatrixCalculator calculator = ChangeMatrixCalculator.getCalculator(jcuda);
        // Calculation of the ChangeMatrix
        ChangeMatrixContainer container = calculator.computeChangeMatrix(geoserver,
                referenceCoverage.getRenderedImage(), nowCoverage.getRenderedImage(), areaImage, classes,
                roiObj, rasterName, refYear, nowYear);

        // Setting of the results
        result = container.getResult();
        ChangeMatrixDTO changeMatrix = container.getDto();

        // //////////////////////////////////////////////////////////////////////
        // Import into GeoServer the new raster 'result' ...
        // //////////////////////////////////////////////////////////////////////
        /**
         * create the final coverage using final envelope
         */
        // hints for tiling
        final Hints hints = GeoTools.getDefaultHints().clone();

        final GridCoverage2D retValue = new GridCoverageFactory(hints).create(rasterName, result,
                referenceCoverage.getEnvelope());
        /**
         * Add Overviews...
         */
        final File file = File.createTempFile(retValue.getName().toString(), ".tif");
        GeoTiffWriter writer = new GeoTiffWriter(file);

        // setting the write parameters for this geotiff
        final ParameterValueGroup gtiffParams = new GeoTiffFormat().getWriteParameters();
        gtiffParams.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString())
                .setValue(CoverageImporter.DEFAULT_WRITE_PARAMS);
        final GeneralParameterValue[] wps = (GeneralParameterValue[]) gtiffParams.values()
                .toArray(new GeneralParameterValue[1]);

        try {
            writer.write(retValue, wps);
        } finally {
            try {
                writer.dispose();
            } catch (Exception e) {
                throw new IOException("Unable to write the output raster.", e);
            }
        }

        // Disposal of the input Raster
        PlanarImage.wrapRenderedImage(result).dispose();

        AbstractGridCoverage2DReader gtiffReader = null;
        try {
            gtiffReader = new GeoTiffFormat().getReader(file);
            CoverageUtilities.generateOverviews(gtiffReader);
        } catch (DataSourceException e) {
            // we tried, no need to fuss around this one
        }

        /**
         * import the new coverage into the GeoServer catalog
         */
        try {
            ImportProcess importProcess = new ImportProcess(catalog);
            GridCoverage2D retOvValue = gtiffReader.read(wps);
            importProcess.execute(null, retOvValue, wsName, null, retValue.getName().toString(),
                    retValue.getCoordinateReferenceSystem(), null, defaultStyle);
        } finally {
            if (gtiffReader != null) {
                gtiffReader.dispose();
            }

            try {
                FileUtils.forceDelete(file);
            } catch (Exception e) {
                // we tried, no need to fuss around this one
            }
        }

        // //////////////////////////////////////////////////////////////////////
        // Updating WFS ...
        // //////////////////////////////////////////////////////////////////////
        /**
         * Update Feature Attributes and LOG into the DB
         */
        filter = ff.equals(ff.property("ftUUID"), ff.literal(uuid.toString()));

        SimpleFeature feature = SimpleFeatureBuilder
                .copy(features.subCollection(filter).toArray(new SimpleFeature[1])[0]);

        // build the feature
        feature.setAttribute("runEnd", new Date());
        feature.setAttribute("itemStatus", "COMPLETED");
        feature.setAttribute("itemStatusMessage", "Change Matrix Process completed successfully");
        feature.setAttribute("layerName", rasterName);
        feature.setAttribute("changeMatrix", JSONSerializer.toJSON(changeMatrix).toString());

        ListFeatureCollection output = new ListFeatureCollection(features.getSchema());
        output.add(feature);

        features = wfsLogProcess.execute(output, typeName, wsName, storeName, filter, false,
                new NullProgressListener());

        // //////////////////////////////////////////////////////////////////////
        // Return the computed Change Matrix ...
        // //////////////////////////////////////////////////////////////////////
        return changeMatrix;
    } catch (Exception e) {

        if (features != null) {
            // //////////////////////////////////////////////////////////////////////
            // Updating WFS ...
            // //////////////////////////////////////////////////////////////////////
            /**
             * Update Feature Attributes and LOG into the DB
             */
            filter = ff.equals(ff.property("ftUUID"), ff.literal(uuid.toString()));

            SimpleFeature feature = SimpleFeatureBuilder
                    .copy(features.subCollection(filter).toArray(new SimpleFeature[1])[0]);

            // build the feature
            feature.setAttribute("runEnd", new Date());
            feature.setAttribute("itemStatus", "FAILED");
            feature.setAttribute("itemStatusMessage",
                    "There was an error while while processing Input parameters: " + e.getMessage());

            ListFeatureCollection output = new ListFeatureCollection(features.getSchema());
            output.add(feature);

            features = wfsLogProcess.execute(output, typeName, wsName, storeName, filter, false,
                    new NullProgressListener());
        }

        throw new WPSException("Could process request ", e);
    } finally {
        // clean up
        if (result != null) {
            ImageUtilities.disposePlanarImageChain(PlanarImage.wrapRenderedImage(result));
        }
        if (referenceCoverage != null) {
            referenceCoverage.dispose(true);
        }
        if (nowCoverage != null) {
            nowCoverage.dispose(true);
        }
    }
}

From source file:org.photovault.dcraw.RawImage.java

/**
 *     Get a 8 bit gamma corrected version of the image.
 * @param minWidth Minimum width for the image that will be rendered
 * @param minHeight Minimum height for the image that will be rendered
 * @param isLowQualityAcceptable If true, renderer may use optimizations that
 * trade off image quality for speed./*from   w w w  .j  a  v a2  s.co m*/
 * @return The corrected image
 */
public RenderableOp getCorrectedImage(int minWidth, int minHeight, boolean isLowQualityAcceptable) {

    int maxSubsample = 1;
    if (minWidth > 0 && minHeight > 0) {
        while (width >= minWidth * 2 * maxSubsample && height >= minHeight * 2 * maxSubsample) {
            maxSubsample *= 2;
        }
    }
    if (rawImage == null || maxSubsample < subsample) {
        // dcraw.setHalfSize( isHalfSizeEnough );
        if (maxSubsample == 1 && subsample > 1) {
            // The image has been loaded with 1/2 resolution so reloading
            // cannot be avoided
            closeRaw();
        }
        subsample = maxSubsample;
        loadRawImage();
        correctedImage = null;
    }
    if (correctedImage == null) {
        RenderingHints nonCachedHints = new RenderingHints(JAI.KEY_TILE_CACHE, null);

        // TODO: Why setting color model as a rendering hint produces black image???
        RawConvDescriptor.register();
        ParameterBlock pb = new ParameterBlockJAI("RawConv");
        pb.setSource(wbAdjustedRawImage, 0);
        pb.set(white, 0);
        pb.set(black, 1);
        pb.set(highlightCompression, 2);
        rawConverter = JAI.createRenderable("RawConv", pb, nonCachedHints);
        rawConverter.setProperty("org.photovault.opname", "raw_toneadj_image");
        applyExposureSettings();

        // Convert from linear to gamma corrected
        createGammaLut();
        LookupTableJAI jailut = new LookupTableJAI(gammaLut);
        correctedImage = LookupDescriptor.createRenderable(rawConverter, jailut, null);
        correctedImage.setProperty("org.photovault.opname", "gamma_lut_image");
        // Store the color model of the image
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        cm = new ComponentColorModel(cs, new int[] { 8, 8, 8 }, false, false, Transparency.OPAQUE,
                DataBuffer.TYPE_BYTE);

    }
    return correctedImage;
}