use of org.hortonmachine.gears.utils.RegionMap in project hortonmachine by TheHortonMachine.
the class LasInfoController method findCircles.
public static List<Geometry> findCircles(GridCoverage2D inRaster, int pixelsThreshold) throws Exception {
RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster);
int nCols = regionMap.getCols();
int nRows = regionMap.getRows();
RandomIter rasterIter = CoverageUtilities.getRandomIterator(inRaster);
WritableRaster[] holder = new WritableRaster[1];
GridCoverage2D outGC = CoverageUtilities.createCoverageFromTemplate(inRaster, HMConstants.doubleNovalue, holder);
WritableRandomIter outIter = RandomIterFactory.createWritable(holder[0], null);
for (int r = 0; r < nRows; r++) {
for (int c = 0; c < nCols; c++) {
double value = rasterIter.getSampleDouble(c, r, 0);
if (value != 255) {
outIter.setSample(c, r, 0, 1);
} else {
outIter.setSample(c, r, 0, -9999.0);
}
}
}
OmsVectorizer v = new OmsVectorizer();
v.inRaster = outGC;
v.doRemoveHoles = false;
v.pThres = pixelsThreshold;
v.pValue = 1.0;
v.process();
SimpleFeatureCollection outVector = v.outVector;
List<SimpleFeature> featuresList = FeatureUtilities.featureCollectionToList(outVector).stream().filter(f -> {
Object attribute = f.getAttribute(v.fDefault);
if (attribute instanceof Number) {
double value = ((Number) attribute).doubleValue();
if (value != -9999.0) {
Geometry geom = (Geometry) f.getDefaultGeometry();
// assume no centroid intersection
Point centroid = geom.getCentroid();
Envelope env = geom.getEnvelopeInternal();
double buffer = env.getWidth() * 0.01;
Geometry centroidB = centroid.buffer(buffer);
if (geom.intersects(centroidB)) {
return false;
}
return true;
}
}
return false;
}).collect(Collectors.toList());
// DefaultFeatureCollection fc = new DefaultFeatureCollection();
// fc.addAll(featuresList);
// HMMapframe mf = HMMapframe.openFrame(false);
// mf.addLayer(fc);
List<Geometry> geomsList = featuresList.stream().map(f -> {
Geometry geom = (Geometry) f.getDefaultGeometry();
Envelope env = geom.getEnvelopeInternal();
Coordinate centre = env.centre();
Point centerPoint = GeometryUtilities.gf().createPoint(centre);
double width = env.getWidth();
double height = env.getHeight();
double radius = Math.max(width, height) / 2.0;
Geometry finalBuffer = centerPoint.buffer(radius);
return finalBuffer;
}).collect(Collectors.toList());
return geomsList;
}
use of org.hortonmachine.gears.utils.RegionMap in project hortonmachine by TheHortonMachine.
the class MapcalcJiffler method exec.
public String exec(IHMProgressMonitor pm) throws Exception {
ReferencedEnvelope bounds = null;
RegionMap regionMap = null;
CoordinateReferenceSystem crs = null;
try {
pm.beginTask("Reading input maps...", name2PathMap.size());
for (Entry<String, String> entry : name2PathMap.entrySet()) {
String mapName = entry.getKey();
if (function.indexOf(mapName) != -1) {
GridCoverage2D gridCoverage2D = OmsRasterReader.readRaster(entry.getValue());
RenderedImage renderedImage = gridCoverage2D.getRenderedImage();
sourceImgParams.put(mapName, renderedImage);
if (bounds == null) {
regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(gridCoverage2D);
crs = gridCoverage2D.getCoordinateReferenceSystem();
ReferencedEnvelope renv = new ReferencedEnvelope(regionMap.getWest(), regionMap.getEast(), regionMap.getSouth(), regionMap.getNorth(), crs);
bounds = renv;
}
}
pm.worked(1);
}
pm.done();
} catch (IOException e) {
e.printStackTrace();
errorMessage = "An error occurred while reading the input maps.";
return errorMessage;
}
pm.beginTask("Adding source maps...", sourceImgParams.size());
JiffleBuilder interp = new JiffleBuilder();
interp.script(function);
for (Entry<String, RenderedImage> entry : sourceImgParams.entrySet()) {
interp.source(entry.getKey(), entry.getValue());
pm.worked(1);
}
pm.done();
pm.beginTask("Building output map...", 1);
interp.dest(RESULT_MAP_NAME, regionMap.getCols(), regionMap.getRows());
pm.worked(1);
pm.done();
pm.beginTask("Executing mapcalc...", IHMProgressMonitor.UNKNOWN);
interp.run();
RenderedImage image = interp.getImage(RESULT_MAP_NAME);
pm.done();
GridCoverage2D coverage = CoverageUtilities.buildCoverage(RESULT_MAP_NAME, image, regionMap, crs);
OmsRasterWriter.writeRaster(resultPath, coverage);
return errorMessage;
}
use of org.hortonmachine.gears.utils.RegionMap in project hortonmachine by TheHortonMachine.
the class TmsWms2Geotiff method process.
@Execute
public void process() throws Exception {
checkNull(inServiceUrl, outRaster, inRoiPath);
CoordinateReferenceSystem mercatorCrs = CrsUtilities.getCrsFromEpsg(EPSG_MERCATOR, null);
CoordinateReferenceSystem latLongCrs = DefaultGeographicCRS.WGS84;
SimpleFeatureCollection inRoi = getVector(inRoiPath);
ReferencedEnvelope inBounds = inRoi.getBounds();
ReferencedEnvelope latLongBounds = inBounds.transform(latLongCrs, true);
double w = latLongBounds.getMinX();
double s = latLongBounds.getMinY();
double e = latLongBounds.getMaxX();
double n = latLongBounds.getMaxY();
int z = 18;
if (pZoomlevel != null) {
z = pZoomlevel;
}
GlobalMercator gm = new GlobalMercator();
int[] llTileXY = gm.GoogleTile(s, w, z);
int[] urTileXY = gm.GoogleTile(n, e, z);
int startXTile = Math.min(llTileXY[0], urTileXY[0]);
int endXTile = Math.max(llTileXY[0], urTileXY[0]);
int startYTile = Math.min(llTileXY[1], urTileXY[1]);
int endYTile = Math.max(llTileXY[1], urTileXY[1]);
if (pSchemaType.equals(OGC_TMS)) {
llTileXY = gm.TMSTileFromGoogleTile(llTileXY[0], llTileXY[1], z);
urTileXY = gm.TMSTileFromGoogleTile(urTileXY[0], urTileXY[1], z);
}
startXTile = Math.min(llTileXY[0], urTileXY[0]);
endXTile = Math.max(llTileXY[0], urTileXY[0]);
startYTile = Math.min(llTileXY[1], urTileXY[1]);
endYTile = Math.max(llTileXY[1], urTileXY[1]);
int tilesCountX = endXTile - startXTile + 1;
int tilesCountY = endYTile - startYTile + 1;
int width = tilesCountX * tileSize;
int height = tilesCountY * tileSize;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
int tileNum = 0;
final ReferencedEnvelope finalMercatorBounds = new ReferencedEnvelope(mercatorCrs);
pm.beginTask("Getting tiles at zoom level: " + z, (endXTile - startXTile + 1));
int runningXPix = 0;
int runningYPix = 0;
for (int x = startXTile; x <= endXTile; x++) {
for (int y = startYTile; y <= endYTile; y++) {
tileNum++;
int yy = y;
if (pSchemaType.equalsIgnoreCase(GOOGLE))
yy = (int) ((Math.pow(2, z) - 1) - y);
double[] bounds = gm.TileBounds(x, yy, z);
double west = bounds[0];
double south = bounds[1];
double east = bounds[2];
double north = bounds[3];
final ReferencedEnvelope tmpBounds = new ReferencedEnvelope(west, east, south, north, mercatorCrs);
finalMercatorBounds.expandToInclude(tmpBounds);
String tmp = "";
if (pSourceType.equals(TMS)) {
tmp = inServiceUrl.replaceFirst("ZZZ", String.valueOf(z));
tmp = tmp.replaceFirst("XXX", String.valueOf(x));
tmp = tmp.replaceFirst("YYY", String.valueOf(y));
} else if (pSourceType.equals(WMS)) {
ReferencedEnvelope llTB = tmpBounds.transform(latLongCrs, true);
tmp = inServiceUrl.replaceFirst("SSS", String.valueOf(llTB.getMinY()));
tmp = tmp.replaceFirst("NNN", String.valueOf(llTB.getMaxY()));
tmp = tmp.replaceFirst("WWW", String.valueOf(llTB.getMinX()));
tmp = tmp.replaceFirst("EEE", String.valueOf(llTB.getMaxX()));
} else {
throw new ModelsIllegalargumentException("Source Type can be only 0 or 1.", this);
}
// System.out.println(x + "/" + y + ": " + tmp);
URL url = new URL(tmp);
try (InputStream imgStream = url.openStream()) {
BufferedImage tileImg = ImageIO.read(imgStream);
g2d.drawImage(tileImg, runningXPix, runningYPix, null);
if (doDebug) {
g2d.setColor(Color.RED);
g2d.drawRect(runningXPix, runningYPix, tileSize, tileSize);
String tileDescr = x + "/" + y + "/" + z;
g2d.drawString(tileDescr, runningXPix + 10, runningYPix + 20);
}
} catch (Exception ex) {
pm.errorMessage("Unable to get image: " + tmp);
}
runningYPix += tileSize;
}
runningXPix += tileSize;
runningYPix = 0;
pm.worked(1);
}
pm.done();
pm.message("Zoom level: " + z + " has " + tileNum + " tiles.");
double ww = finalMercatorBounds.getMinX();
double ss = finalMercatorBounds.getMinY();
double ee = finalMercatorBounds.getMaxX();
double nn = finalMercatorBounds.getMaxY();
double xres = (ee - ww) / width;
double yres = (nn - ss) / height;
RegionMap envelopeParams = new RegionMap();
envelopeParams.put(CoverageUtilities.NORTH, nn);
envelopeParams.put(CoverageUtilities.SOUTH, ss);
envelopeParams.put(CoverageUtilities.WEST, ww);
envelopeParams.put(CoverageUtilities.EAST, ee);
envelopeParams.put(CoverageUtilities.XRES, xres);
envelopeParams.put(CoverageUtilities.YRES, yres);
envelopeParams.put(CoverageUtilities.ROWS, (double) height);
envelopeParams.put(CoverageUtilities.COLS, (double) width);
GridCoverage2D coverage = CoverageUtilities.buildCoverage("tmsraster", img, envelopeParams, mercatorCrs);
OmsRasterWriter.writeRaster(outRaster, coverage);
}
use of org.hortonmachine.gears.utils.RegionMap in project hortonmachine by TheHortonMachine.
the class OmsHoughCirclesRaster method process.
@Execute
public void process() throws Exception {
checkNull(inRaster, pMinRadius, pMaxRadius, pRadiusIncrement);
if (pColorNv != null) {
colorNv = pColorNv;
useColorNv = true;
}
RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster);
offx = 0;
offy = 0;
width = regionMap.getCols();
height = regionMap.getRows();
offset = width;
xRes = regionMap.getXres();
radiusMinPixel = (int) round(width * pMinRadius / (regionMap.getEast() - regionMap.getWest()));
radiusMaxPixel = (int) round(width * pMaxRadius / (regionMap.getEast() - regionMap.getWest()));
;
radiusIncPixel = (int) round(width * pRadiusIncrement / (regionMap.getEast() - regionMap.getWest()));
if (radiusIncPixel < 1) {
radiusIncPixel = 1;
}
maxCircles = pMaxCircleCount;
depth = ((radiusMaxPixel - radiusMinPixel) / radiusIncPixel) + 1;
Geometry[] circles = getCircles();
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName("houghcircles");
b.setCRS(inRaster.getCoordinateReferenceSystem());
b.add("the_geom", Polygon.class);
b.add("value", Double.class);
SimpleFeatureType type = b.buildFeatureType();
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
DefaultFeatureCollection outFC = new DefaultFeatureCollection();
for (Geometry geometry : circles) {
Object[] values = new Object[] { geometry, referenceImageValue };
builder.addAll(values);
SimpleFeature feature = builder.buildFeature(null);
outFC.add(feature);
}
outCircles = outFC;
}
use of org.hortonmachine.gears.utils.RegionMap in project hortonmachine by TheHortonMachine.
the class OmsSurfaceInterpolator method process.
@Execute
public void process() throws Exception {
checkNull(inGrid);
gridGeometry = inGrid.getGridGeometry();
RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inGrid);
final int cols = regionMap.getCols();
int rows = regionMap.getRows();
coordinatesSpatialTree = new STRtree();
if (inVector != null) {
checkNull(fCat);
GeometryDescriptor geometryDescriptor = inVector.getSchema().getGeometryDescriptor();
if (!EGeometryType.isPoint(geometryDescriptor)) {
throw new ModelsIllegalargumentException("The geometry has to be a point geometry.", this, pm);
}
SimpleFeatureIterator featureIterator = inVector.features();
Coordinate[] coordinates = new Coordinate[inVector.size()];
int index = 0;
pm.beginTask("Indexing control points...", coordinates.length);
while (featureIterator.hasNext()) {
SimpleFeature feature = featureIterator.next();
Geometry geometry = (Geometry) feature.getDefaultGeometry();
coordinates[index] = geometry.getCoordinate();
double value = ((Number) feature.getAttribute(fCat)).doubleValue();
coordinates[index].z = value;
Envelope env = new Envelope(coordinates[index]);
coordinatesSpatialTree.insert(env, coordinates[index]);
pm.worked(1);
}
pm.done();
pm.message("Indexed control points: " + coordinates.length);
} else {
// create it from grid
pm.beginTask("Indexing control points...", cols);
RandomIter inIter = CoverageUtilities.getRandomIterator(inGrid);
int count = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
double value = inIter.getSampleDouble(c, r, 0);
if (!HMConstants.isNovalue(value)) {
Coordinate coordinate = CoverageUtilities.coordinateFromColRow(c, r, gridGeometry);
coordinate.z = value;
Envelope env = new Envelope(coordinate);
coordinatesSpatialTree.insert(env, coordinate);
count++;
}
}
pm.worked(1);
}
pm.done();
pm.message("Indexed control points (from input grid): " + count);
}
coordinatesSpatialTree.build();
if (pMode.equals(IDW)) {
interpolator = new IDWInterpolator(pBuffer);
} else {
interpolator = new TPSInterpolator(pBuffer);
}
WritableRaster interpolatedWR = CoverageUtilities.createWritableRaster(cols, rows, null, null, HMConstants.doubleNovalue);
final WritableRandomIter interpolatedIter = RandomIterFactory.createWritable(interpolatedWR, null);
boolean doMultiThread = pMaxThreads > 1;
ExecutorService fixedThreadPool = null;
if (doMultiThread)
fixedThreadPool = Executors.newFixedThreadPool(pMaxThreads);
pm.beginTask("Performing interpolation...", rows);
final double[] eval = new double[1];
for (int r = 0; r < rows; r++) {
final int row = r;
if (doMultiThread) {
Runnable runner = new Runnable() {
public void run() {
processing(cols, coordinatesSpatialTree, interpolatedIter, eval, row);
}
};
fixedThreadPool.execute(runner);
} else {
processing(cols, coordinatesSpatialTree, interpolatedIter, eval, row);
}
}
if (doMultiThread) {
try {
fixedThreadPool.shutdown();
fixedThreadPool.awaitTermination(30, TimeUnit.DAYS);
fixedThreadPool.shutdownNow();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pm.done();
outRaster = CoverageUtilities.buildCoverage("interpolatedraster", interpolatedWR, regionMap, inGrid.getCoordinateReferenceSystem());
}
Aggregations