Search in sources :

Example 91 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class OmsHoleFiller method process.

@Execute
public void process() throws Exception {
    checkNull(inRaster);
    ISurfaceInterpolator interpolator;
    if (pMode.equals(IDW)) {
        interpolator = new IDWInterpolator(pBuffer);
    } else {
        interpolator = new TPSInterpolator(pBuffer);
    }
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster);
    int rows = regionMap.getRows();
    int cols = regionMap.getCols();
    WritableRaster outWR = CoverageUtilities.renderedImage2WritableRaster(inRaster.getRenderedImage(), false);
    WritableRandomIter outIter = CoverageUtilities.getWritableRandomIterator(outWR);
    GridGeometry2D gridGeometry = inRaster.getGridGeometry();
    PreparedGeometry preparedRoi = null;
    if (inROI != null) {
        List<Geometry> roiList = FeatureUtilities.featureCollectionToGeometriesList(inROI, false, null);
        GeometryCollection gc = new GeometryCollection(roiList.toArray(GeometryUtilities.TYPE_GEOMETRY), gf);
        preparedRoi = PreparedGeometryFactory.prepare(gc);
    }
    pm.beginTask("Filling holes...", cols - 2);
    for (int r = 1; r < rows - 1; r++) {
        for (int c = 1; c < cols - 1; c++) {
            if (pm.isCanceled()) {
                return;
            }
            double value = outIter.getSampleDouble(c, r, 0);
            if (isNovalue(value)) {
                DirectPosition worldPosition = gridGeometry.gridToWorld(new GridCoordinates2D(c, r));
                double[] coordinate = worldPosition.getCoordinate();
                Coordinate pointCoordinate = new Coordinate(coordinate[0], coordinate[1]);
                Point point = gf.createPoint(pointCoordinate);
                if (preparedRoi == null || preparedRoi.intersects(point)) {
                    // TODO this could be done considering more points and more far away points.
                    // For now, this works.
                    List<Coordinate> surroundingValids = getValidSurroundingPoints(outIter, gridGeometry, c, r);
                    if (surroundingValids.size() > 3) {
                        double newValue = interpolator.getValue(surroundingValids.toArray(new Coordinate[0]), pointCoordinate);
                        outIter.setSample(c, r, 0, newValue);
                    }
                }
            }
        }
        pm.worked(1);
    }
    pm.done();
    outIter.done();
    outRaster = CoverageUtilities.buildCoverage("nulled", outWR, regionMap, inRaster.getCoordinateReferenceSystem());
}
Also used : ISurfaceInterpolator(org.hortonmachine.gears.modules.r.interpolation2d.core.ISurfaceInterpolator) DirectPosition(org.opengis.geometry.DirectPosition) GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) RegionMap(org.hortonmachine.gears.utils.RegionMap) Point(org.locationtech.jts.geom.Point) Point(org.locationtech.jts.geom.Point) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Geometry(org.locationtech.jts.geom.Geometry) GeometryCollection(org.locationtech.jts.geom.GeometryCollection) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Coordinate(org.locationtech.jts.geom.Coordinate) WritableRaster(java.awt.image.WritableRaster) TPSInterpolator(org.hortonmachine.gears.modules.r.interpolation2d.core.TPSInterpolator) GridCoordinates2D(org.geotools.coverage.grid.GridCoordinates2D) IDWInterpolator(org.hortonmachine.gears.modules.r.interpolation2d.core.IDWInterpolator) Execute(oms3.annotations.Execute)

Example 92 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class OmsRasterGenerator method process.

@Execute
public void process() throws Exception {
    checkNull(pNorth, pSouth, pEast, pWest, pXres, pYres);
    if (pCode == null && inCrs == null) {
        throw new ModelsIllegalargumentException("At lest one of the CRS definitions are necessary.", this);
    }
    CoordinateReferenceSystem crs = inCrs;
    if (crs == null)
        crs = CrsUtilities.getCrsFromEpsg(pCode, null);
    int rows = (int) round((pNorth - pSouth) / pYres);
    int cols = (int) round((pEast - pWest) / pXres);
    GridGeometry2D gridGeometryFromRegionValues = CoverageUtilities.gridGeometryFromRegionValues(pNorth, pSouth, pEast, pWest, cols, rows, crs);
    RegionMap regionMap = CoverageUtilities.gridGeometry2RegionParamsMap(gridGeometryFromRegionValues);
    WritableRaster outWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, null);
    WritableRandomIter outIter = CoverageUtilities.getWritableRandomIterator(outWR);
    Random random = new Random();
    pm.beginTask("Generating raster...", rows);
    for (int r = 0; r < rows; r++) {
        if (isCanceled(pm)) {
            return;
        }
        for (int c = 0; c < cols; c++) {
            double value = pValue;
            if (doRandom) {
                value = pOffset + pScale * random.nextDouble();
            }
            outIter.setSample(c, r, 0, value);
        }
        pm.worked(1);
    }
    pm.done();
    outIter.done();
    outRaster = CoverageUtilities.buildCoverage("generated", outWR, regionMap, crs);
}
Also used : ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) Random(java.util.Random) WritableRaster(java.awt.image.WritableRaster) RegionMap(org.hortonmachine.gears.utils.RegionMap) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Execute(oms3.annotations.Execute)

Example 93 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class OmsRasterResizer method process.

@Execute
public void process() throws Exception {
    checkNull(inRaster);
    if (inVector != null) {
        RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster);
        ReferencedEnvelope bounds = inVector.getBounds();
        // add a one cell buffer around the vector
        double xres = regionMap.getXres();
        double yres = regionMap.getYres();
        bounds.expandBy(2 * xres, 2 * yres);
        double n = regionMap.getNorth();
        double s = regionMap.getSouth();
        double w = regionMap.getWest();
        double e = regionMap.getEast();
        double newW = bounds.getMinX();
        if (newW < w) {
            newW = w;
        }
        double newE = bounds.getMaxX();
        if (newE > e) {
            newE = e;
        }
        double newS = bounds.getMinY();
        if (newS < s) {
            newS = s;
        }
        double newN = bounds.getMaxY();
        if (newN > n) {
            newN = n;
        }
        Envelope env = new Envelope(newW, newE, newS, newN);
        RegionMap subRegion = regionMap.toSubRegion(env);
        WritableRaster outWR = CoverageUtilities.createWritableRaster(subRegion.getCols(), subRegion.getRows(), null, null, null);
        WritableRandomIter outIter = CoverageUtilities.getWritableRandomIterator(outWR);
        RandomIter iter = CoverageUtilities.getRandomIterator(inRaster);
        try {
            GridGeometry2D startGG = inRaster.getGridGeometry();
            GridGeometry2D destGG = CoverageUtilities.gridGeometryFromRegionParams(subRegion, inRaster.getCoordinateReferenceSystem());
            int rows = subRegion.getRows();
            int cols = subRegion.getCols();
            for (int r = 0; r < rows; r++) {
                for (int c = 0; c < cols; c++) {
                    Coordinate coord = CoverageUtilities.coordinateFromColRow(c, r, destGG);
                    int[] cr = CoverageUtilities.colRowFromCoordinate(coord, startGG, null);
                    double value = iter.getSampleDouble(cr[0], cr[1], 0);
                    outIter.setSample(c, r, 0, value);
                }
            }
            outRaster = CoverageUtilities.buildCoverage("resized", outWR, subRegion, inRaster.getCoordinateReferenceSystem());
        } finally {
            outIter.done();
            iter.done();
        }
    } else if (inMaskRaster != null) {
        RegionMap maskRegionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inMaskRaster);
        int rows = maskRegionMap.getRows();
        int cols = maskRegionMap.getCols();
        WritableRaster outWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, null);
        WritableRandomIter maskOutIter = CoverageUtilities.getWritableRandomIterator(outWR);
        RandomIter outIter = CoverageUtilities.getRandomIterator(inMaskRaster);
        RandomIter inIter = CoverageUtilities.getRandomIterator(inRaster);
        RegionMap inRegionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster);
        Envelope inEnvelope = inRegionMap.toEnvelope();
        GridGeometry2D inGridGeometry = inRaster.getGridGeometry();
        GridGeometry2D maskGridGeometry = inMaskRaster.getGridGeometry();
        double inRasterNv = HMConstants.getNovalue(inRaster);
        double maskRasterNv = HMConstants.getNovalue(inMaskRaster);
        try {
            pm.beginTask("Resizing raster...", rows);
            for (int r = 0; r < rows; r++) {
                if (pm.isCanceled()) {
                    return;
                }
                for (int c = 0; c < cols; c++) {
                    double maskValue = outIter.getSampleDouble(c, r, 0);
                    if (!HMConstants.isNovalue(maskValue, maskRasterNv)) {
                        Coordinate coordinate = CoverageUtilities.coordinateFromColRow(c, r, maskGridGeometry);
                        if (inEnvelope.contains(coordinate)) {
                            int[] colRow = CoverageUtilities.colRowFromCoordinate(coordinate, inGridGeometry, null);
                            double value = inIter.getSampleDouble(colRow[0], colRow[1], 0);
                            maskOutIter.setSample(c, r, 0, value);
                        } else {
                            maskOutIter.setSample(c, r, 0, inRasterNv);
                        }
                    } else {
                        maskOutIter.setSample(c, r, 0, inRasterNv);
                    }
                }
                pm.worked(1);
            }
            pm.done();
            outRaster = CoverageUtilities.buildCoverageWithNovalue("resized", outWR, maskRegionMap, inRaster.getCoordinateReferenceSystem(), inRasterNv);
        } finally {
            inIter.done();
            maskOutIter.done();
        }
    } else {
        throw new ModelsIllegalargumentException("Either an input vector or raster need to be defined.", this);
    }
}
Also used : ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) Coordinate(org.locationtech.jts.geom.Coordinate) WritableRaster(java.awt.image.WritableRaster) RegionMap(org.hortonmachine.gears.utils.RegionMap) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.locationtech.jts.geom.Envelope) Execute(oms3.annotations.Execute)

Example 94 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class HMModelIM method processGeometryByTileCell.

private void processGeometryByTileCell(int count, Geometry boundGeometry) throws IOException, TransformException, Exception {
    Envelope writeEnv = boundGeometry.getEnvelopeInternal();
    double writeEast = writeEnv.getMaxX();
    double writeWest = writeEnv.getMinX();
    double writeNorth = writeEnv.getMaxY();
    double writeSouth = writeEnv.getMinY();
    int writeCols = (int) ((writeEast - writeWest) / xRes);
    int writeRows = (int) ((writeNorth - writeSouth) / yRes);
    Envelope readEnv = new Envelope(writeEnv);
    readEnv.expandBy(cellBuffer * xRes, cellBuffer * yRes);
    double readEast = readEnv.getMaxX();
    double readWest = readEnv.getMinX();
    double readNorth = readEnv.getMaxY();
    double readSouth = readEnv.getMinY();
    // int readCols = (int) ((readEast - readWest) / xRes);
    // int readRows = (int) ((readNorth - readSouth) / yRes);
    /*
         * clear lists of in and out data local to the loop
         */
    outGridCoverages.clear();
    inRasterIterators.clear();
    inRasters.clear();
    outRasterIterators.clear();
    GridGeometry2D writeGridGeometry = CoverageUtilities.gridGeometryFromRegionValues(writeNorth, writeSouth, writeEast, writeWest, writeCols, writeRows, crs);
    for (File outRasterFile : outRasterFiles) {
        File parentFile = outRasterFile.getParentFile();
        if (parentFile != null && parentFile.exists()) {
            WritableRaster outWR = CoverageUtilities.createWritableRaster(writeCols, writeRows, null, null, HMConstants.doubleNovalue);
            RegionMap writeParams = CoverageUtilities.gridGeometry2RegionParamsMap(writeGridGeometry);
            GridCoverage2D writeGC = CoverageUtilities.buildCoverage(outRasterFile.getName(), outWR, writeParams, crs);
            outGridCoverages.add(writeGC);
            WritableRandomIter outDataIter = CoverageUtilities.getWritableRandomIterator(outWR);
            outRasterIterators.add(outDataIter);
        } else {
            outGridCoverages.add(null);
            outRasterIterators.add(null);
        }
    }
    readGridGeometry = null;
    GeneralParameterValue[] readGeneralParameterValues = CoverageUtilities.createGridGeometryGeneralParameter(xRes, yRes, readNorth, readSouth, readEast, readWest, crs);
    int index = 0;
    for (ImageMosaicReader reader : readers) {
        try {
            GridCoverage2D readGC = reader.read(readGeneralParameterValues);
            readGridGeometry = readGC.getGridGeometry();
            // read raster at once, since a randomiter is way slower when wrapping borders
            Raster readRaster = readGC.getRenderedImage().getData();
            RandomIter readIter = RandomIterFactory.create(readRaster, null);
            inRasterIterators.add(readIter);
            inRasters.add(readGC);
            inRasterNovalues.add(HMConstants.getNovalue(readGC));
            index++;
        } catch (Exception e) {
            StringBuilder errSb = new StringBuilder();
            errSb.append("ERROR: could not read coverage for parameters: \n");
            errSb.append(readGeneralParameterValues[0]);
            errSb.append("ERROR: with reader N." + index + ": " + Arrays.toString(reader.getGridCoverageNames()));
            errSb.append("\nERROR: " + e.getLocalizedMessage());
            pm.errorMessage(errSb.toString());
            freeIterators();
            // return;
            throw new IOException("Problems reading Mosaic!");
        }
    }
    // Envelope allBoundsEnv = new Envelope(new Coordinate(llCorner[0], llCorner[1]), new
    // Coordinate(urCorner[0], urCorner[1]));
    // MathTransform crsToGrid = readGridGeometry.getCRSToGrid2D(PixelOrientation.LOWER_RIGHT);
    // 
    // Envelope transformed = JTS.transform(allBoundsEnv, crsToGrid);
    // int minX = (int) round(transformed.getMinX());
    // int maxY = (int) round(transformed.getMaxY()); // y grid is inverse
    // int maxX = (int) round(transformed.getMaxX());
    // int minY = (int) round(transformed.getMinY());
    GridCoordinates2D llGrid = readGridGeometry.worldToGrid(new DirectPosition2D(llCorner[0], llCorner[1]));
    GridCoordinates2D urGrid = readGridGeometry.worldToGrid(new DirectPosition2D(urCorner[0], urCorner[1]));
    int minX = llGrid.x;
    // y grid is inverse
    int maxY = llGrid.y;
    int maxX = urGrid.x;
    int minY = urGrid.y;
    // is there a gridrange shift?
    GridEnvelope2D gridRange2D = readGridGeometry.getGridRange2D();
    int readRows = gridRange2D.height;
    minY = minY + gridRange2D.y;
    // TODO check this out properly
    if (isSingleInY) {
        maxY = maxY - gridRange2D.y;
    } else {
        maxY = maxY + gridRange2D.y;
    }
    int readCols = gridRange2D.width;
    minX = minX + gridRange2D.x;
    if (isSingleInX) {
        maxX = maxX - gridRange2D.x;
    } else {
        maxX = maxX + gridRange2D.x;
    }
    try {
        final GridCoordinates2D gridCoordinates2D = new GridCoordinates2D();
        for (int writeRow = 0; writeRow < writeRows; writeRow++) {
            for (int writeCol = 0; writeCol < writeCols; writeCol++) {
                gridCoordinates2D.x = writeCol;
                gridCoordinates2D.y = writeRow;
                DirectPosition writeGridToWorld = writeGridGeometry.gridToWorld(gridCoordinates2D);
                GridCoordinates2D worldToReadGrid = readGridGeometry.worldToGrid(writeGridToWorld);
                int readCol = worldToReadGrid.x;
                int readRow = worldToReadGrid.y;
                if (// 
                readCol + cellBuffer > maxX || readCol - cellBuffer < minX || readRow + cellBuffer > maxY || readRow - cellBuffer < minY) {
                    continue;
                }
                processCell(readCol, readRow, writeCol, writeRow, readCols, readRows, writeCols, writeRows);
            }
        }
    } finally {
        freeIterators();
    }
    for (int i = 0; i < outRasterFiles.size(); i++) {
        File outputFile = outRasterFiles.get(i);
        GridCoverage2D writeGC = outGridCoverages.get(i);
        if (writeGC != null) {
            File outParentFolder = outputFile.getParentFile();
            if (outParentFolder == null || !outParentFolder.exists()) {
                continue;
            }
            String outBaseName = FileUtilities.getNameWithoutExtention(outputFile);
            File outTileFile = new File(outParentFolder, outBaseName + "_" + count + ".tiff");
            OmsRasterWriter writer = new OmsRasterWriter();
            writer.pm = new DummyProgressMonitor();
            writer.inRaster = writeGC;
            writer.file = outTileFile.getAbsolutePath();
            writer.process();
        }
    }
}
Also used : GeneralParameterValue(org.opengis.parameter.GeneralParameterValue) DirectPosition(org.opengis.geometry.DirectPosition) GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) ImageMosaicReader(org.geotools.gce.imagemosaic.ImageMosaicReader) Raster(java.awt.image.Raster) WritableRaster(java.awt.image.WritableRaster) RegionMap(org.hortonmachine.gears.utils.RegionMap) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) IOException(java.io.IOException) GeneralEnvelope(org.geotools.geometry.GeneralEnvelope) Envelope(org.locationtech.jts.geom.Envelope) DirectPosition2D(org.geotools.geometry.DirectPosition2D) TransformException(org.opengis.referencing.operation.TransformException) IOException(java.io.IOException) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) GridEnvelope2D(org.geotools.coverage.grid.GridEnvelope2D) WritableRaster(java.awt.image.WritableRaster) GridCoordinates2D(org.geotools.coverage.grid.GridCoordinates2D) DummyProgressMonitor(org.hortonmachine.gears.libs.monitor.DummyProgressMonitor) File(java.io.File) OmsRasterWriter(org.hortonmachine.gears.io.rasterwriter.OmsRasterWriter)

Example 95 with WritableRandomIter

use of javax.media.jai.iterator.WritableRandomIter in project hortonmachine by TheHortonMachine.

the class ModelsEngine method sumDownstream.

/**
 * Calculates the sum of the values of a specified quantity from every point to the outlet.
 *
 * <p>During the calculation the drainage directions are followed.</p>
 *
 * @param flowIter the map of flowdirections.
 * @param mapToSumIter the map for which to sum downstream.
 * @param width the width of the resulting map.
 * @param height the height of the resulting map.
 * @param upperThreshold the upper threshold, values above that are excluded.
 * @param lowerThreshold the lower threshold, values below that are excluded.
 * @param pm the monitor.
 * @return The map of downstream summed values.
 */
public static WritableRaster sumDownstream(RandomIter flowIter, RandomIter mapToSumIter, int width, int height, Double upperThreshold, Double lowerThreshold, IHMProgressMonitor pm) {
    final int[] point = new int[2];
    WritableRaster summedMapWR = CoverageUtilities.createWritableRaster(width, height, null, null, null);
    WritableRandomIter summedMapIter = RandomIterFactory.createWritable(summedMapWR, null);
    double uThres = Double.POSITIVE_INFINITY;
    if (upperThreshold != null) {
        uThres = upperThreshold;
    }
    double lThres = Double.NEGATIVE_INFINITY;
    if (lowerThreshold != null) {
        lThres = lowerThreshold;
    }
    pm.beginTask("Calculating downstream sum...", height);
    for (int r = 0; r < height; r++) {
        for (int c = 0; c < width; c++) {
            double mapToSumValue = mapToSumIter.getSampleDouble(c, r, 0);
            if (// 
            !isNovalue(flowIter.getSampleDouble(c, r, 0)) && // 
            mapToSumValue < uThres && // 
            mapToSumValue > lThres) {
                point[0] = c;
                point[1] = r;
                while (// 
                flowIter.getSampleDouble(point[0], point[1], 0) < 9 && !isNovalue(flowIter.getSampleDouble(point[0], point[1], 0)) && (checkRange(mapToSumIter.getSampleDouble(point[0], point[1], 0), uThres, lThres))) {
                    double sumValue = summedMapIter.getSampleDouble(point[0], point[1], 0) + mapToSumIter.getSampleDouble(c, r, 0);
                    summedMapIter.setSample(point[0], point[1], 0, sumValue);
                    // }
                    if (!go_downstream(point, flowIter.getSampleDouble(point[0], point[1], 0)))
                        return null;
                }
                if (!isNovalue(flowIter.getSampleDouble(point[0], point[1], 0))) {
                    double summedMapValue = summedMapIter.getSampleDouble(point[0], point[1], 0);
                    if (!isNovalue(summedMapValue)) {
                        double sumValue = summedMapValue + mapToSumIter.getSampleDouble(c, r, 0);
                        summedMapIter.setSample(point[0], point[1], 0, sumValue);
                    }
                }
            } else {
                summedMapIter.setSample(c, r, 0, doubleNovalue);
            }
        }
        pm.worked(1);
    }
    pm.done();
    return summedMapWR;
}
Also used : WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) WritableRaster(java.awt.image.WritableRaster)

Aggregations

WritableRandomIter (javax.media.jai.iterator.WritableRandomIter)99 WritableRaster (java.awt.image.WritableRaster)85 RandomIter (javax.media.jai.iterator.RandomIter)60 RegionMap (org.hortonmachine.gears.utils.RegionMap)59 Execute (oms3.annotations.Execute)49 Coordinate (org.locationtech.jts.geom.Coordinate)20 GridCoverage2D (org.geotools.coverage.grid.GridCoverage2D)18 ModelsIllegalargumentException (org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException)18 GridGeometry2D (org.geotools.coverage.grid.GridGeometry2D)17 RenderedImage (java.awt.image.RenderedImage)16 Point (java.awt.Point)11 ArrayList (java.util.ArrayList)11 Geometry (org.locationtech.jts.geom.Geometry)11 GridCoordinates2D (org.geotools.coverage.grid.GridCoordinates2D)10 FlowNode (org.hortonmachine.gears.libs.modules.FlowNode)10 DirectPosition2D (org.geotools.geometry.DirectPosition2D)9 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)8 Envelope (org.locationtech.jts.geom.Envelope)7 DirectPosition (org.opengis.geometry.DirectPosition)7 SampleModel (java.awt.image.SampleModel)6