use of javax.media.jai.iterator.RandomIter in project geotoolkit by Geomatys.
the class NodataFilter method computeRect.
/**
* Computes a rectangle of outputs.
*
* @param sources The source images. Should be an array of length 1.
* @param dest The raster to be filled in.
* @param destRect The region within the raster to be filled.
*/
@Override
protected void computeRect(final PlanarImage[] sources, final WritableRaster dest, final Rectangle destRect) {
assert sources.length == 1;
final PlanarImage source = sources[0];
Rectangle sourceRect = mapDestRect(destRect, 0);
sourceRect = sourceRect.intersection(source.getBounds());
final RandomIter iter = RandomIterFactory.create(source, sourceRect);
// Minimum inclusive
final int minX = destRect.x;
// Minimum inclusive
final int minY = destRect.y;
// Maximum exclusive
final int maxX = destRect.width + minX;
// Maximum exclusive
final int maxY = destRect.height + minY;
// Horizontal padding
final int hPad = leftPadding + rightPadding + 1;
for (int band = source.getNumBands(); --band >= 0; ) {
for (int y = minY; y < maxY; y++) {
// Inclusive
final int minScanY = max(minY, y - topPadding);
// Exclusive
final int maxScanY = min(maxY, y + bottomPadding + 1);
final int minScanI = (minScanY - (y - topPadding)) * hPad;
assert minScanI >= 0 && minScanI <= distances.length : minScanI;
for (int x = minX; x < maxX; x++) {
final double current = iter.getSampleDouble(x, y, band);
if (!Double.isNaN(current)) {
/*
* Pixel is already valid: no operation here.
*/
dest.setSample(x, y, band, current);
continue;
}
/*
* Computes the average and set the value if the amount of
* valid pixels is at least equal to the threshold amount.
*/
// Number of valid values.
int count = 0;
// Weighted sum of values.
double sumValue = 0;
// Sum of distances of valid values.
double sumDistance = 0;
// Inclusive
final int minScanX = max(minX, x - leftPadding);
// Exclusive
final int maxScanX = min(maxX, x + rightPadding + 1);
final int lineOffset = hPad - (maxScanX - minScanX);
int index = minScanI + (minScanX - (x - leftPadding));
for (int sy = minScanY; sy < maxScanY; sy++) {
for (int sx = minScanX; sx < maxScanX; sx++) {
final double scan = iter.getSampleDouble(sx, sy, band);
if (!Double.isNaN(scan)) {
final double d = distances[index];
assert (abs(d - hypot(sx - x, sy - y)) < 1E-6) && (d > 0) : d;
sumValue += d * scan;
sumDistance += d;
count++;
}
index++;
}
index += lineOffset;
}
final double value = (count >= validityThreshold) ? sumValue / sumDistance : current;
dest.setSample(x, y, band, value);
}
}
}
iter.done();
}
use of javax.media.jai.iterator.RandomIter in project qaf by qmetry.
the class ImageCompareUtil method doMatch.
/**
* @param search
* : image to search.
* @param template
* : base/template image to which target image
* @param rectangles
* : arg[0] area of image to search, arg[1] area of template
* @return
*/
public boolean doMatch(RenderedImage search, RenderedImage template, Rectangle... rectangles) {
RandomIter searchiterator = RandomIterFactory.create(search, null);
RandomIter templateiterator = RandomIterFactory.create(template, null);
double minSAD = Double.MAX_VALUE;
Rectangle sRect = (rectangles == null) || (rectangles.length < 1) ? new Rectangle() : rectangles[0];
Rectangle tRect = (rectangles == null) || (rectangles.length < 2) ? new Rectangle() : rectangles[1];
int T_rows = tRect.width > 0 ? tRect.x + tRect.width : template.getWidth();
int S_rows = sRect.width > 0 ? sRect.x + sRect.width : (tRect.width > 0 ? search.getWidth() - tRect.width : search.getWidth() - template.getWidth());
int T_cols = tRect.height > 0 ? tRect.y + tRect.height : template.getHeight();
int S_cols = (sRect.height > 0 ? sRect.y + sRect.height : ((tRect.height > 0 ? (search.getHeight() - tRect.height) : search.getHeight() - template.getHeight())));
// loop through the search image
double[] p_SearchIMG = new double[5];
double[] p_TemplateIMG = new double[5];
double[] S_accum = new double[3];
Point bMatch = null;
boolean match = false;
double SAD = 0.0;
int samplesCnt = 0;
int x = 0, y = 0, i = 0, j = 0;
for (x = sRect.x; x <= S_rows; x += 1) {
for (y = sRect.y; y <= S_cols; y += 1) {
match = true;
SAD = 0.0;
samplesCnt = 0;
// loop through the template image
for (i = tRect.x; i < T_rows - 5; i += 5) {
for (j = tRect.y; j < T_cols - 5; j += 5) {
S_accum[0] = S_accum[1] = S_accum[2] = 0;
for (int ploat = 0; ploat < 5; ploat++) {
searchiterator.getPixel(x + i + ploat - tRect.x, y + j + ploat - tRect.y, p_SearchIMG);
templateiterator.getPixel(i + ploat, j + ploat, p_TemplateIMG);
S_accum[0] += Math.abs(p_SearchIMG[0] - p_TemplateIMG[0]);
S_accum[1] += Math.abs(p_SearchIMG[1] - p_TemplateIMG[1]);
S_accum[2] += Math.abs(p_SearchIMG[2] - p_TemplateIMG[2]);
}
Double tempSad = (S_accum[0] + S_accum[1] + S_accum[2]) / 5;
SAD += tempSad;
if (tempSad < minSAD) {
minSAD = tempSad;
bMatch = new Point(x, y);
}
samplesCnt += 5;
if ((tempSad > maxDiff)) {
match = false;
break;
}
// System.out.println("***************\nLast SAD: " +
// tempSad
// + " for : " + samplesCnt + " samples: i: " + i +
// "j: "
// + j);
}
}
// int samplecnt = (i + 1) * (i + 1) / 25;
SAD = SAD / samplesCnt;
if (match) {
break;
}
}
if (match) {
break;
}
// System.out.println("Match: " + match + " x: " + x + " y: " + y +
// " dist: "
// + minSAD + " bMatch: " + bMatch);
}
System.out.print("Match: " + match + " x: " + x + " y: " + y + " dist: " + minSAD + " bMatch: " + bMatch + tRect);
return match;
}
use of javax.media.jai.iterator.RandomIter 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 javax.media.jai.iterator.RandomIter in project hortonmachine by TheHortonMachine.
the class OmsZonalStatsIM method process.
@Execute
public void process() throws Exception {
checkNull(inVector);
addSource(new File(inRaster));
boolean hasUserTotalMean = false;
if (pTotalMean != null) {
hasUserTotalMean = true;
tm_usertm_tactivecells[1] = pTotalMean;
}
ReferencedEnvelope bounds = inVector.getBounds();
double[] xBins = NumericsUtilities.range2Bins(bounds.getMinX(), bounds.getMaxX(), pBinSize, false);
double[] yBins = NumericsUtilities.range2Bins(bounds.getMinY(), bounds.getMaxY(), pBinSize, false);
SimpleFeatureBuilder featureBuilder = OmsZonalStats.createFeatureBuilder(bounds.getCoordinateReferenceSystem(), hasUserTotalMean);
outVector = new DefaultFeatureCollection();
List<Geometry> geometriesList = FeatureUtilities.featureCollectionToGeometriesList(inVector, true, null);
ConcurrentLinkedQueue<Geometry> allGeometriesQueue = new ConcurrentLinkedQueue<Geometry>();
allGeometriesQueue.addAll(geometriesList);
ConcurrentLinkedQueue<Geometry> keepGeometriesQueue;
ConcurrentLinkedQueue<Geometry> removeGeometriesQueue;
pm.beginTask("Processing polygons...", xBins.length - 1);
for (int x = 0; x < xBins.length - 1; x++) {
for (int y = 0; y < yBins.length - 1; y++) {
Envelope envelope = new Envelope(xBins[x], xBins[x + 1], yBins[y], yBins[y + 1]);
Envelope readEnvelope = null;
keepGeometriesQueue = new ConcurrentLinkedQueue<Geometry>();
removeGeometriesQueue = new ConcurrentLinkedQueue<Geometry>();
for (Geometry geometry : allGeometriesQueue) {
Envelope geometryenvelope = geometry.getEnvelopeInternal();
if (geometryenvelope.intersects(envelope)) {
removeGeometriesQueue.add(geometry);
if (readEnvelope == null) {
readEnvelope = new Envelope(geometryenvelope);
} else {
readEnvelope.expandToInclude(geometryenvelope);
}
} else {
keepGeometriesQueue.add(geometry);
}
}
allGeometriesQueue = keepGeometriesQueue;
if (removeGeometriesQueue.size() == 0) {
continue;
}
// pm.message("" + readEnvelope);
GridCoverage2D readGC = getGridCoverage(0, readEnvelope);
double novalue = HMConstants.getNovalue(readGC);
GridGeometry2D gridGeometry = readGC.getGridGeometry();
Raster readRaster = readGC.getRenderedImage().getData();
RandomIter readIter = RandomIterFactory.create(readRaster, null);
for (Geometry geometry : removeGeometriesQueue) {
double[] polygonStats = OmsZonalStats.polygonStats(geometry, gridGeometry, readIter, novalue, hasUserTotalMean, tm_usertm_tactivecells, pPercentageThres, pm);
if (polygonStats == null) {
continue;
}
Object[] values;
if (pTotalMean == null) {
values = new Object[] { //
geometry, //
polygonStats[0], //
polygonStats[1], //
polygonStats[2], //
polygonStats[3], //
polygonStats[4], //
(int) polygonStats[5], //
(int) polygonStats[6] };
} else {
values = new Object[] { //
geometry, //
polygonStats[0], //
polygonStats[1], //
polygonStats[2], //
polygonStats[3], //
polygonStats[4], //
polygonStats[5], //
(int) polygonStats[6], //
(int) polygonStats[7] };
}
featureBuilder.addAll(values);
SimpleFeature feature = featureBuilder.buildFeature(null);
((DefaultFeatureCollection) outVector).add(feature);
}
}
pm.worked(1);
}
pm.done();
if (!hasUserTotalMean) {
tm_usertm_tactivecells[0] = tm_usertm_tactivecells[0] / tm_usertm_tactivecells[2];
pm.message("Total mean: " + tm_usertm_tactivecells[0]);
}
dispose();
}
use of javax.media.jai.iterator.RandomIter in project hortonmachine by TheHortonMachine.
the class OmsHoughCirclesRasterCleaner method process.
// VARS DESCR END
@SuppressWarnings("unchecked")
@Execute
public void process() throws Exception {
checkNull(inVector, pMaxOverlap, inRaster);
RandomIter rasterIter = CoverageUtilities.getRandomIterator(inRaster);
double novalue = HMConstants.getNovalue(inRaster);
GridGeometry2D gridGeometry = inRaster.getGridGeometry();
double[] tm_utm_tac = new double[3];
STRtree circlesTree = FeatureUtilities.featureCollectionToSTRtree(inVector);
List<SimpleFeature> circlesList = FeatureUtilities.featureCollectionToList(inVector);
DefaultFeatureCollection outFC = new DefaultFeatureCollection();
for (SimpleFeature circleFeature : circlesList) {
Geometry geometry = (Geometry) circleFeature.getDefaultGeometry();
Polygon circle = (Polygon) geometry.getGeometryN(0);
PreparedGeometry preparedCircle = PreparedGeometryFactory.prepare(circle);
List<SimpleFeature> circlesAround = circlesTree.query(circle.getEnvelopeInternal());
List<Geometry> intersectedCircles = new ArrayList<Geometry>();
for (SimpleFeature circleAround : circlesAround) {
if (circleAround.equals(circleFeature)) {
continue;
}
Geometry circleAroundGeometry = (Geometry) circleAround.getDefaultGeometry();
if (preparedCircle.intersects(circleAroundGeometry)) {
intersectedCircles.add(circleAroundGeometry);
}
}
Point centroid = circle.getCentroid();
int intersectionsCount = intersectedCircles.size();
if (intersectionsCount != 0) {
// check how many circles overlapped
if (intersectionsCount > pMaxOverlapCount) {
continue;
}
// check if the circles overlap too much, i.e. cover their baricenter
boolean intersected = false;
for (Geometry intersectedCircle : intersectedCircles) {
if (intersectedCircle.intersects(centroid)) {
intersected = true;
break;
}
}
if (intersected) {
continue;
}
}
// check if the center has a raster value, i.e. is not empty
double value = CoverageUtilities.getValue(inRaster, centroid.getCoordinate());
if (!HMConstants.isNovalue(value)) {
continue;
}
// check if the inner part of the circle is indeed rather empty
// min, max, mean, var, sdev, activeCellCount, passiveCellCount
double[] stats = OmsZonalStats.polygonStats(circle, gridGeometry, rasterIter, novalue, false, tm_utm_tac, 0, pm);
// if we have many more active cells than passive cells, that is not a circle
double activeCells = stats[5];
double novalues = stats[6];
if (activeCells * 1.5 > novalues) {
continue;
}
// take it as valid circle
outFC.add(circleFeature);
}
outCircles = outFC;
rasterIter.done();
}
Aggregations