Search in sources :

Example 1 with IHMProgressMonitor

use of org.hortonmachine.gears.libs.monitor.IHMProgressMonitor in project hortonmachine by TheHortonMachine.

the class SqlTemplatesAndActions method doTiles.

private static void doTiles(GuiBridgeHandler guiBridge, DatabaseViewer databaseViewer, boolean isRaster) {
    try {
        String label = isRaster ? "raster" : "vector";
        FileFilter fileFilter = isRaster ? HMConstants.rasterFileFilter : HMConstants.vectorFileFilter;
        String title = "Open " + label + " file";
        File[] openFiles = GuiUtilities.showOpenFilesDialog(databaseViewer, title, true, PreferencesHandler.getLastFile(), fileFilter);
        if (openFiles != null && openFiles.length > 0) {
            try {
                PreferencesHandler.setLastPath(openFiles[0].getAbsolutePath());
            } catch (Exception e1) {
                logger.insertError("SqlTemplatesAndActions", "ERROR", e1);
            }
        } else {
            return;
        }
        try {
            String targetEpsg = "epsg:" + GeopackageCommonDb.MERCATOR_SRID;
            CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(targetEpsg, null);
            GeopackageCommonDb db = (GeopackageCommonDb) databaseViewer.currentConnectedSqlDatabase;
            List<FeatureEntry> features4326 = db.features();
            PreparedGeometry limitsGeom3857 = null;
            if (features4326.size() > 0) {
                List<String> names = features4326.stream().map(f -> f.getTableName()).collect(Collectors.toList());
                String selectedTable = GuiUtilities.showComboDialog(databaseViewer, "Area of interest", "It is possible to use one of the vector tables as area of interest. Tiles outside the area will be ignored.", names.toArray(new String[0]), "");
                if (selectedTable != null) {
                    SqlName tName = SqlName.m(selectedTable);
                    GeometryColumn gc = db.getGeometryColumnsForTable(tName);
                    List<Geometry> geometries = db.getGeometriesIn(tName, (Envelope) null, (String[]) null);
                    int dataSrid = db.feature(tName).getSrid();
                    List<Geometry> geometries3857;
                    if (dataSrid == GeopackageCommonDb.MERCATOR_SRID) {
                        geometries3857 = geometries;
                    } else {
                        String sourceEpsg = "epsg:" + dataSrid;
                        CoordinateReferenceSystem sourceCRS = CrsUtilities.getCrsFromEpsg(sourceEpsg, null);
                        ;
                        MathTransform transform = CRS.findMathTransform(sourceCRS, mercatorCrs);
                        geometries3857 = geometries.stream().map(g -> {
                            try {
                                return JTS.transform(g, transform);
                            } catch (Exception e) {
                                e.printStackTrace();
                                return null;
                            }
                        }).collect(Collectors.toList());
                    }
                    if (gc.geometryType.isPolygon()) {
                        // use polygons
                        Geometry union = CascadedPolygonUnion.union(geometries3857);
                        limitsGeom3857 = PreparedGeometryFactory.prepare(union);
                    } else {
                        // use envelopes
                        Envelope env = new Envelope();
                        for (Geometry geometry : geometries3857) {
                            env.expandToInclude(geometry.getEnvelopeInternal());
                        }
                        Polygon polyEnv = GeometryUtilities.createPolygonFromEnvelope(env);
                        limitsGeom3857 = PreparedGeometryFactory.prepare(polyEnv);
                    }
                }
            }
            String nameForTable = FileUtilities.getNameWithoutExtention(openFiles[0]);
            String[] zoomLevels = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" };
            HashMap<String, String[]> fields2ValuesMap = new HashMap<>();
            String newTableLabel = "name of the new table";
            String minZoomLevelLabel = "min zoom level";
            String maxZoomLevelLabel = "max zoom level";
            fields2ValuesMap.put(minZoomLevelLabel, zoomLevels);
            fields2ValuesMap.put(maxZoomLevelLabel, zoomLevels);
            String[] result = // 
            GuiUtilities.showMultiInputDialog(// 
            databaseViewer, // 
            "Select parameters", // 
            new String[] { newTableLabel, minZoomLevelLabel, maxZoomLevelLabel }, // 
            new String[] { nameForTable, "8", "16" }, null);
            if (result == null) {
                return;
            }
            PreparedGeometry _limitsGeom3857 = limitsGeom3857;
            final LogConsoleController logConsole = new LogConsoleController(null);
            IHMProgressMonitor pm = logConsole.getProgressMonitor();
            Logger.INSTANCE.setOutPrintStream(logConsole.getLogAreaPrintStream());
            Logger.INSTANCE.setErrPrintStream(logConsole.getLogAreaPrintStream());
            guiBridge.showWindow(logConsole.asJComponent(), "Console Log");
            new Thread(() -> {
                try {
                    logConsole.beginProcess("Import " + label + " to tileset");
                    pm.message("Checking input parameters...");
                    String _nameForTable = result[0];
                    int minZoom = 8;
                    int maxZoom = 16;
                    try {
                        minZoom = Integer.parseInt(result[1]);
                        maxZoom = Integer.parseInt(result[2]);
                    } catch (Exception e1) {
                        pm.errorMessage("The min or max zoomlevel were not entered correctly, exiting.");
                        return;
                    }
                    for (File file : openFiles) {
                        String dataPath = file.getAbsolutePath();
                        Envelope envelopeInternal = null;
                        if (isRaster) {
                            AbstractGridFormat format = GridFormatFinder.findFormat(file);
                            AbstractGridCoverage2DReader reader = format.getReader(file, null);
                            GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
                            CoordinateReferenceSystem crs = reader.getCoordinateReferenceSystem();
                            double[] ll = originalEnvelope.getLowerCorner().getCoordinate();
                            double[] ur = originalEnvelope.getUpperCorner().getCoordinate();
                            ReferencedEnvelope renv = new ReferencedEnvelope(ll[0], ur[0], ll[1], ur[1], crs);
                            envelopeInternal = renv.transform(mercatorCrs, true);
                        } else {
                            ReferencedEnvelope renv = OmsVectorReader.readEnvelope(file.getAbsolutePath());
                            envelopeInternal = renv.transform(mercatorCrs, true);
                        }
                        ITilesProducer tileProducer = new GeopackageTilesProducer(pm, dataPath, isRaster, minZoom, maxZoom, 256, _limitsGeom3857);
                        String description = "HM import of " + openFiles[0].getName();
                        int addedTiles = ((GeopackageCommonDb) databaseViewer.currentConnectedSqlDatabase).addTilestable(SqlName.m(_nameForTable), description, envelopeInternal, tileProducer);
                        pm.message("Inserted " + addedTiles + " new tiles.");
                    }
                    databaseViewer.refreshDatabaseTree();
                } catch (Exception ex) {
                    pm.errorMessage(ex.getLocalizedMessage());
                } finally {
                    logConsole.finishProcess();
                    logConsole.stopLogging();
                    Logger.INSTANCE.resetStreams();
                }
            }, "DatabaseController->Import " + label + " to tileset").start();
        } catch (Exception e1) {
            GuiUtilities.handleError(databaseViewer, e1);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Also used : GeneralEnvelope(org.geotools.geometry.GeneralEnvelope) Logger(org.hortonmachine.dbs.log.Logger) CRS(org.geotools.referencing.CRS) ObjectOutput(java.io.ObjectOutput) SpatialDbsImportUtils(org.hortonmachine.gears.spatialite.SpatialDbsImportUtils) MainController(org.hortonmachine.style.MainController) ObjectInputStream(java.io.ObjectInputStream) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) ByteArrayInputStream(java.io.ByteArrayInputStream) PreferencesHandler(org.hortonmachine.gears.utils.PreferencesHandler) IHmExtrasDb(org.hortonmachine.dbs.compat.IHmExtrasDb) HMConstants(org.hortonmachine.gears.libs.modules.HMConstants) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) QueryResult(org.hortonmachine.dbs.compat.objects.QueryResult) JTS(org.geotools.geometry.jts.JTS) ConnectionData(org.hortonmachine.dbs.compat.ConnectionData) JFrame(javax.swing.JFrame) TableLevel(org.hortonmachine.dbs.compat.objects.TableLevel) EDataType(org.hortonmachine.dbs.datatypes.EDataType) Collectors(java.util.stream.Collectors) GeopackageCommonDb(org.hortonmachine.dbs.geopackage.GeopackageCommonDb) List(java.util.List) AbstractAction(javax.swing.AbstractAction) DbsUtilities(org.hortonmachine.dbs.utils.DbsUtilities) ITilesProducer(org.hortonmachine.dbs.utils.ITilesProducer) CrsUtilities(org.hortonmachine.gears.utils.CrsUtilities) Polygon(org.locationtech.jts.geom.Polygon) Geometry(org.locationtech.jts.geom.Geometry) ObjectInput(java.io.ObjectInput) FeatureEntry(org.hortonmachine.dbs.geopackage.FeatureEntry) IHMProgressMonitor(org.hortonmachine.gears.libs.monitor.IHMProgressMonitor) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) PreparedGeometryFactory(org.locationtech.jts.geom.prep.PreparedGeometryFactory) CascadedPolygonUnion(org.locationtech.jts.operation.union.CascadedPolygonUnion) DbFormHandler(org.hortonmachine.gforms.DbFormHandler) GuiUtilities(org.hortonmachine.gui.utils.GuiUtilities) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) ASpatialDb(org.hortonmachine.dbs.compat.ASpatialDb) AbstractGridCoverage2DReader(org.geotools.coverage.grid.io.AbstractGridCoverage2DReader) HashMap(java.util.HashMap) Action(javax.swing.Action) ArrayList(java.util.ArrayList) SqlName(org.hortonmachine.dbs.utils.SqlName) ASqlTemplates(org.hortonmachine.dbs.compat.ASqlTemplates) ImageIcon(javax.swing.ImageIcon) GeometryUtilities(org.hortonmachine.gears.utils.geometry.GeometryUtilities) ObjectOutputStream(java.io.ObjectOutputStream) GuiBridgeHandler(org.hortonmachine.gui.utils.GuiBridgeHandler) Iterator(java.util.Iterator) INosqlCollection(org.hortonmachine.dbs.nosql.INosqlCollection) PGDb(org.hortonmachine.dbs.postgis.PGDb) FileUtilities(org.hortonmachine.gears.utils.files.FileUtilities) FormBuilderController(org.hortonmachine.gforms.FormBuilderController) INosqlDb(org.hortonmachine.dbs.nosql.INosqlDb) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) JOptionPane(javax.swing.JOptionPane) FileFilter(javax.swing.filechooser.FileFilter) OmsVectorReader(org.hortonmachine.gears.io.vectorreader.OmsVectorReader) ActionEvent(java.awt.event.ActionEvent) File(java.io.File) LogConsoleController(org.hortonmachine.gui.console.LogConsoleController) ColumnLevel(org.hortonmachine.dbs.compat.objects.ColumnLevel) EDb(org.hortonmachine.dbs.compat.EDb) GeometryColumn(org.hortonmachine.dbs.compat.GeometryColumn) MathTransform(org.opengis.referencing.operation.MathTransform) ADb(org.hortonmachine.dbs.compat.ADb) IFormHandler(org.hortonmachine.gforms.IFormHandler) DefaultGuiBridgeImpl(org.hortonmachine.gui.utils.DefaultGuiBridgeImpl) GridFormatFinder(org.geotools.coverage.grid.io.GridFormatFinder) Envelope(org.locationtech.jts.geom.Envelope) IHMProgressMonitor(org.hortonmachine.gears.libs.monitor.IHMProgressMonitor) MathTransform(org.opengis.referencing.operation.MathTransform) HashMap(java.util.HashMap) LogConsoleController(org.hortonmachine.gui.console.LogConsoleController) AbstractGridCoverage2DReader(org.geotools.coverage.grid.io.AbstractGridCoverage2DReader) GeopackageCommonDb(org.hortonmachine.dbs.geopackage.GeopackageCommonDb) GeneralEnvelope(org.geotools.geometry.GeneralEnvelope) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.locationtech.jts.geom.Envelope) FeatureEntry(org.hortonmachine.dbs.geopackage.FeatureEntry) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) SqlName(org.hortonmachine.dbs.utils.SqlName) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) GeometryColumn(org.hortonmachine.dbs.compat.GeometryColumn) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) FileFilter(javax.swing.filechooser.FileFilter) Polygon(org.locationtech.jts.geom.Polygon) IOException(java.io.IOException) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Geometry(org.locationtech.jts.geom.Geometry) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) GeneralEnvelope(org.geotools.geometry.GeneralEnvelope) ITilesProducer(org.hortonmachine.dbs.utils.ITilesProducer) File(java.io.File)

Example 2 with IHMProgressMonitor

use of org.hortonmachine.gears.libs.monitor.IHMProgressMonitor in project hortonmachine by TheHortonMachine.

the class CoverageUtilities method gridcoverageToCellPolygons.

/**
 * Extracts a list of polygons from the cell bounds of a given {@link GridCoverage2D coverage}.
 *
 * <p><b>Note that the cells are added in a rows
 * and cols order (for each row evaluate each column).</b></p>
 *
 * <p>The userdata of the geometry contains the value of the raster.
 *
 * @param coverage the coverage to use.
 * @param keepCoordinatePredicate an optional predicate to filter out some of the cells.
 * @return the list of envelope geometries.
 */
public static List<Polygon> gridcoverageToCellPolygons(GridCoverage2D coverage, Predicate<Coordinate> keepCoordinatePredicate, boolean doIncrementalMerge, IHMProgressMonitor pm) {
    if (pm == null) {
        pm = new DummyProgressMonitor();
    }
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(coverage);
    double west = regionMap.getWest();
    double north = regionMap.getNorth();
    double xres = regionMap.getXres();
    double yres = regionMap.getYres();
    int cols = regionMap.getCols();
    int rows = regionMap.getRows();
    int everyRows = 1000;
    GeometryFactory gf = GeometryUtilities.gf();
    RandomIter iter = CoverageUtilities.getRandomIterator(coverage);
    List<Geometry> bigPolygons = new ArrayList<Geometry>();
    List<Polygon> polygons = new ArrayList<Polygon>();
    pm.beginTask("Vectorizing raster cells...", rows);
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            double w = west + xres * c;
            double e = w + xres;
            double n = north - yres * r;
            double s = n - yres;
            if (keepCoordinatePredicate != null && !keepCoordinatePredicate.test(new Coordinate(w + xres / 2, s + yres / 2))) {
                continue;
            }
            Coordinate[] coords = new Coordinate[5];
            coords[0] = new Coordinate(w, n);
            coords[1] = new Coordinate(e, n);
            coords[2] = new Coordinate(e, s);
            coords[3] = new Coordinate(w, s);
            coords[4] = new Coordinate(w, n);
            LinearRing linearRing = gf.createLinearRing(coords);
            Polygon polygon = gf.createPolygon(linearRing, null);
            polygons.add(polygon);
            double value = iter.getSampleDouble(c, r, 0);
            polygon.setUserData(value);
        }
        if (doIncrementalMerge && ((r > 0 && r % everyRows == 0) || r == rows - 1)) {
            // merge same value to single geometries to save memory
            Map<Integer, List<Geometry>> collected = polygons.parallelStream().filter(poly -> ((Number) poly.getUserData()).doubleValue() != HMConstants.doubleNovalue).collect(Collectors.groupingBy(poly -> ((Number) poly.getUserData()).intValue()));
            pm.message(r + " of " + rows);
            polygons = new ArrayList<Polygon>();
            int size = collected.size();
            int count = 0;
            for (Entry<Integer, List<Geometry>> entry : collected.entrySet()) {
                count++;
                if (count % 10 == 0)
                    pm.message("   -> " + count + " of " + size);
                Integer basinId = entry.getKey();
                List<Geometry> value = entry.getValue();
                Geometry tmpGeom = CascadedPolygonUnion.union(value);
                for (int i = 0; i < tmpGeom.getNumGeometries(); i++) {
                    Polygon geometryN = (Polygon) tmpGeom.getGeometryN(i);
                    geometryN.setUserData(basinId);
                    bigPolygons.add(geometryN);
                }
            }
        }
        pm.worked(1);
    }
    pm.done();
    if (doIncrementalMerge) {
        polygons = new ArrayList<Polygon>();
        for (Geometry tmpGeom : bigPolygons) {
            Object userData = tmpGeom.getUserData();
            for (int i = 0; i < tmpGeom.getNumGeometries(); i++) {
                Polygon geometryN = (Polygon) tmpGeom.getGeometryN(i);
                geometryN.setUserData(userData);
                polygons.add(geometryN);
            }
        }
    }
    return polygons;
}
Also used : Envelope2D(org.geotools.geometry.Envelope2D) Point2D(java.awt.geom.Point2D) RandomIter(javax.media.jai.iterator.RandomIter) ImageMosaicReader(org.geotools.gce.imagemosaic.ImageMosaicReader) ROIShape(javax.media.jai.ROIShape) GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) DummyProgressMonitor(org.hortonmachine.gears.libs.monitor.DummyProgressMonitor) Coordinate(org.locationtech.jts.geom.Coordinate) Point(java.awt.Point) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) Envelope(org.opengis.geometry.Envelope) SampleModel(java.awt.image.SampleModel) Parameter(org.geotools.parameter.Parameter) HMConstants.intNovalue(org.hortonmachine.gears.libs.modules.HMConstants.intNovalue) FastLiteShape(org.hortonmachine.gears.utils.features.FastLiteShape) DouglasPeuckerSimplifier(org.locationtech.jts.simplify.DouglasPeuckerSimplifier) Map(java.util.Map) HMConstants(org.hortonmachine.gears.libs.modules.HMConstants) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) JTS(org.geotools.geometry.jts.JTS) GridCoordinates2D(org.geotools.coverage.grid.GridCoordinates2D) ParameterValue(org.opengis.parameter.ParameterValue) TransformException(org.opengis.referencing.operation.TransformException) GridCoverage2DReader(org.geotools.coverage.grid.io.GridCoverage2DReader) NumericsUtilities(org.hortonmachine.gears.utils.math.NumericsUtilities) HMConstants.shortNovalue(org.hortonmachine.gears.libs.modules.HMConstants.shortNovalue) BufferedImage(java.awt.image.BufferedImage) Predicate(java.util.function.Predicate) GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) RenderedImage(java.awt.image.RenderedImage) Math.min(java.lang.Math.min) DefaultGeographicCRS(org.geotools.referencing.crs.DefaultGeographicCRS) AffineTransform(java.awt.geom.AffineTransform) Collectors(java.util.stream.Collectors) List(java.util.List) DirectPosition2D(org.geotools.geometry.DirectPosition2D) RasterFactory(javax.media.jai.RasterFactory) ProcessException(org.geotools.process.ProcessException) Entry(java.util.Map.Entry) Polygon(org.locationtech.jts.geom.Polygon) GeneralParameterValue(org.opengis.parameter.GeneralParameterValue) Math.max(java.lang.Math.max) Geometry(org.locationtech.jts.geom.Geometry) IHMProgressMonitor(org.hortonmachine.gears.libs.monitor.IHMProgressMonitor) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) DataBuffer(java.awt.image.DataBuffer) PreparedGeometryFactory(org.locationtech.jts.geom.prep.PreparedGeometryFactory) HMConstants.doubleNovalue(org.hortonmachine.gears.libs.modules.HMConstants.doubleNovalue) CascadedPolygonUnion(org.locationtech.jts.operation.union.CascadedPolygonUnion) ComponentSampleModel(java.awt.image.ComponentSampleModel) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) LinearRing(org.locationtech.jts.geom.LinearRing) HashMap(java.util.HashMap) NoDataContainer(it.geosolutions.jaiext.range.NoDataContainer) DoubleUnaryOperator(java.util.function.DoubleUnaryOperator) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) AffineTransform2D(org.geotools.referencing.operation.transform.AffineTransform2D) GridCoverageReader(org.opengis.coverage.grid.GridCoverageReader) Raster(java.awt.image.Raster) GeometryUtilities(org.hortonmachine.gears.utils.geometry.GeometryUtilities) GridSampleDimension(org.geotools.coverage.GridSampleDimension) CoverageFactoryFinder(org.geotools.coverage.CoverageFactoryFinder) DirectPosition(org.opengis.geometry.DirectPosition) ModelsIOException(org.hortonmachine.gears.libs.exceptions.ModelsIOException) RandomIterFactory(javax.media.jai.iterator.RandomIterFactory) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) ROI(javax.media.jai.ROI) FileUtilities(org.hortonmachine.gears.utils.files.FileUtilities) IOException(java.io.IOException) HMConstants.isNovalue(org.hortonmachine.gears.libs.modules.HMConstants.isNovalue) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) File(java.io.File) InvalidGridGeometryException(org.geotools.coverage.grid.InvalidGridGeometryException) LineString(org.locationtech.jts.geom.LineString) LengthIndexedLine(org.locationtech.jts.linearref.LengthIndexedLine) GridCoverageFactory(org.geotools.coverage.grid.GridCoverageFactory) GridEnvelope2D(org.geotools.coverage.grid.GridEnvelope2D) ColorModel(java.awt.image.ColorModel) XAffineTransform(org.geotools.referencing.operation.matrix.XAffineTransform) RegionMap(org.hortonmachine.gears.utils.RegionMap) WritableRaster(java.awt.image.WritableRaster) PreparedGeometryFactory(org.locationtech.jts.geom.prep.PreparedGeometryFactory) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) RegionMap(org.hortonmachine.gears.utils.RegionMap) ArrayList(java.util.ArrayList) RandomIter(javax.media.jai.iterator.RandomIter) WritableRandomIter(javax.media.jai.iterator.WritableRandomIter) Point(java.awt.Point) PreparedGeometry(org.locationtech.jts.geom.prep.PreparedGeometry) Geometry(org.locationtech.jts.geom.Geometry) Coordinate(org.locationtech.jts.geom.Coordinate) DummyProgressMonitor(org.hortonmachine.gears.libs.monitor.DummyProgressMonitor) List(java.util.List) ArrayList(java.util.ArrayList) Polygon(org.locationtech.jts.geom.Polygon) LinearRing(org.locationtech.jts.geom.LinearRing)

Example 3 with IHMProgressMonitor

use of org.hortonmachine.gears.libs.monitor.IHMProgressMonitor in project hortonmachine by TheHortonMachine.

the class LasOnDtmBuildingsExtractor method process.

@Execute
public void process() throws Exception {
    checkNull(inLas, inDtm, outBuildings);
    SimpleFeatureCollection buildingsFC = null;
    GridCoverage2D inDtmGC = null;
    try (ALasDataManager lasHandler = ALasDataManager.getDataManager(new File(inLas), inDtmGC, 0, null)) {
        lasHandler.open();
        ReferencedEnvelope3D e = lasHandler.getEnvelope3D();
        if (pRasterResolution != null) {
            OmsRasterReader reader = new OmsRasterReader();
            reader.file = inDtm;
            reader.pNorth = e.getMaxY();
            reader.pSouth = e.getMinY();
            reader.pWest = e.getMinX();
            reader.pEast = e.getMaxX();
            reader.pXres = pRasterResolution;
            reader.pYres = pRasterResolution;
            reader.process();
            inDtmGC = reader.outRaster;
        } else {
            inDtmGC = getRaster(inDtm);
            RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inDtmGC);
            pRasterResolution = regionMap.getXres();
        }
        Envelope2D envelope2d = inDtmGC.getEnvelope2D();
        Polygon regionPolygon = FeatureUtilities.envelopeToPolygon(envelope2d);
        WritableRaster[] buildingsHolder = new WritableRaster[1];
        GridCoverage2D newBuildingsRaster = CoverageUtilities.createCoverageFromTemplate(inDtmGC, 1.0, buildingsHolder);
        GridGeometry2D gridGeometry = newBuildingsRaster.getGridGeometry();
        java.awt.Point p = new java.awt.Point();
        IHMProgressMonitor pm = new LogProgressMonitor();
        pm.beginTask("Reading points...", IHMProgressMonitor.UNKNOWN);
        List<LasRecord> pointsInGeometry = lasHandler.getPointsInGeometry(regionPolygon, true);
        pm.done();
        pm.beginTask("Buildings filtering...", (int) pointsInGeometry.size());
        for (LasRecord dot : pointsInGeometry) {
            Coordinate c = new Coordinate(dot.x, dot.y);
            if (!envelope2d.contains(dot.x, dot.y)) {
                continue;
            }
            double dtmValue = CoverageUtilities.getValue(inDtmGC, c);
            double height = abs(dot.z - dtmValue);
            CoverageUtilities.colRowFromCoordinate(c, gridGeometry, p);
            if (height < pDtmThres) {
                buildingsHolder[0].setSample(p.x, p.y, 0, doubleNovalue);
            }
            pm.worked(1);
        }
        pm.done();
        OmsMorpher morpher = new OmsMorpher();
        morpher.pm = pm;
        morpher.inMap = newBuildingsRaster;
        morpher.pMode = Variables.OPEN;
        morpher.process();
        newBuildingsRaster = morpher.outMap;
        OmsVectorizer buildingsVectorizer = new OmsVectorizer();
        buildingsVectorizer.pm = pm;
        buildingsVectorizer.inRaster = newBuildingsRaster;
        buildingsVectorizer.doRemoveHoles = true;
        double minAreaInCells = pMinArea / pRasterResolution / pRasterResolution;
        buildingsVectorizer.pThres = minAreaInCells;
        buildingsVectorizer.fDefault = "rast";
        buildingsVectorizer.process();
        buildingsFC = buildingsVectorizer.outVector;
        dumpVector(buildingsFC, outBuildings);
        if (doSmoothing && outCleanBuildings != null) {
            // smooth
            SimpleFeatureCollection smoothedFC = smoothBuildings(pDensifyResolution, buildingsFC);
            // remove trees
            DefaultFeatureCollection removedAndSmoothedFC = removeNonBuildings(lasHandler, smoothedFC, inDtmGC, pBuildingsBuffer);
            dumpVector(removedAndSmoothedFC, outCleanBuildings);
        }
    }
}
Also used : GridGeometry2D(org.geotools.coverage.grid.GridGeometry2D) IHMProgressMonitor(org.hortonmachine.gears.libs.monitor.IHMProgressMonitor) RegionMap(org.hortonmachine.gears.utils.RegionMap) LogProgressMonitor(org.hortonmachine.gears.libs.monitor.LogProgressMonitor) LasRecord(org.hortonmachine.gears.io.las.core.LasRecord) WritableRaster(java.awt.image.WritableRaster) OmsMorpher(org.hortonmachine.gears.modules.r.morpher.OmsMorpher) Polygon(org.locationtech.jts.geom.Polygon) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) OmsRasterReader(org.hortonmachine.gears.io.rasterreader.OmsRasterReader) Envelope2D(org.geotools.geometry.Envelope2D) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) ALasDataManager(org.hortonmachine.gears.io.las.ALasDataManager) Coordinate(org.locationtech.jts.geom.Coordinate) OmsVectorizer(org.hortonmachine.gears.modules.v.vectorize.OmsVectorizer) ReferencedEnvelope3D(org.geotools.geometry.jts.ReferencedEnvelope3D) File(java.io.File) Execute(oms3.annotations.Execute)

Aggregations

File (java.io.File)3 WritableRaster (java.awt.image.WritableRaster)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 GridCoverage2D (org.geotools.coverage.grid.GridCoverage2D)2 GridGeometry2D (org.geotools.coverage.grid.GridGeometry2D)2 Envelope2D (org.geotools.geometry.Envelope2D)2 IHMProgressMonitor (org.hortonmachine.gears.libs.monitor.IHMProgressMonitor)2 RegionMap (org.hortonmachine.gears.utils.RegionMap)2 Coordinate (org.locationtech.jts.geom.Coordinate)2 Polygon (org.locationtech.jts.geom.Polygon)2 NoDataContainer (it.geosolutions.jaiext.range.NoDataContainer)1 Point (java.awt.Point)1 ActionEvent (java.awt.event.ActionEvent)1 AffineTransform (java.awt.geom.AffineTransform)1 Point2D (java.awt.geom.Point2D)1 BufferedImage (java.awt.image.BufferedImage)1