List of usage examples for java.awt Rectangle intersection
public Rectangle intersection(Rectangle r)
From source file:edu.uchc.octane.ParticleAnalysis.java
/** * Analyze the image//from w ww . j av a 2 s .c o m * @param ip The image to be analyzed * @param mask A rectangle of region of interest * @param threshold Lowest intensity to be analyzed * @param noise The noise threshold of the watershed algorithm * @throws InterruptedException */ public void process(ImageProcessor ip, Rectangle mask, int threshold, int noise) throws InterruptedException { int border = 1; if (g_ != null) { // g_.setImageData(ip, isZeroBg_); border = g_.getWindowSize(); } width_ = ip.getWidth(); height_ = ip.getHeight(); int[] offsets = { -width_, -width_ + 1, +1, +width_ + 1, +width_, +width_ - 1, -1, -width_ - 1 }; Rectangle bbox = new Rectangle(border, border, width_ - 2 * border, height_ - 2 * border); bbox = bbox.intersection(mask); ArrayList<Pixel> pixels = new ArrayList<Pixel>(); for (int y = bbox.y; y < bbox.y + bbox.height; y++) { for (int x = bbox.x; x < bbox.x + bbox.width; x++) { int v = ip.get(x, y); if (v > threshold) { pixels.add(new Pixel(x, y, v)); } } } Collections.sort(pixels); nParticles_ = 0; x_ = new double[pixels.size()]; y_ = new double[pixels.size()]; z_ = new double[pixels.size()]; h_ = new double[pixels.size()]; e_ = new double[pixels.size()]; FloodState floodState = new FloodState(width_, height_); floodState.floodBorders(bbox); int idxList, lenList; int[] listOfIndexes = new int[width_ * height_]; for (Pixel p : pixels) { if (Thread.interrupted()) { throw (new InterruptedException()); } int index = p.x + width_ * p.y; if (floodState.isProcessed(index)) { continue; } int v = p.value; boolean isMax = true; idxList = 0; lenList = 1; listOfIndexes[0] = index; floodState.flood(index); do { index = listOfIndexes[idxList]; for (int d = 0; d < 8; d++) { // analyze all neighbors (in 8 directions) at the same level int index2 = index + offsets[d]; if (floodState.isProcessed(index2)) { //conflict isMax = false; break; } if (!floodState.isFlooded(index2)) { int v2 = ip.get(index2); if (v2 >= v - noise) { listOfIndexes[lenList++] = index2; floodState.flood(index2); } } } } while (++idxList < lenList); for (idxList = 0; idxList < lenList; idxList++) { floodState.process(listOfIndexes[idxList]); } if (isMax) { if (g_ != null) { g_.setInitialCoordinates(p.x, p.y); try { double[] result = g_.fit(); if (result == null) { continue; } double h = g_.getH(); if (h < noise || h < getHeightMin() || h > getHeightMax()) { continue; } double e = g_.getE(); if (e < getFittingQualityMin()) { continue; } x_[nParticles_] = g_.getX(); y_[nParticles_] = g_.getY(); z_[nParticles_] = g_.getZ(); h_[nParticles_] = h; e_[nParticles_] = e; nParticles_++; } catch (MathIllegalStateException e) { //failed fitting continue; } } else { x_[nParticles_] = (double) p.x; y_[nParticles_] = (double) p.y; h_[nParticles_] = (double) p.value; nParticles_++; } } } }
From source file:gdsc.core.ij.AlignImagesFFT.java
private double[] alignImages(FHT refFHT, double[] s, double[] ss, ImageProcessor targetIp, WindowMethod windowMethod, Rectangle bounds, SubPixelMethod subPixelMethod) { lastXOffset = lastYOffset = 0;/*from ww w .ja v a 2 s.c om*/ if (noValue(targetIp)) { // Zero correlation with empty image return new double[] { 0, 0, 0 }; } // Perform correlation analysis in Fourier space (A and B transform to F and G) // using the complex conjugate of G multiplied by F: // C(u,v) = F(u,v) G*(u,v) int maxN = refFHT.getWidth(); // Allow the input target to be a FHT FHT targetFHT; if (targetIp instanceof FHT && targetIp.getWidth() == maxN) { targetFHT = (FHT) targetIp; } else { targetFHT = transformTarget(targetIp, windowMethod); } FloatProcessor subCorrMat = correlate(refFHT, targetFHT); int originX = (maxN / 2); int originY = (maxN / 2); // Normalise using the denominator if (s != null) normalise(subCorrMat, s, ss, targetIp); Rectangle intersect = new Rectangle(0, 0, subCorrMat.getWidth(), subCorrMat.getHeight()); // Restrict the translation if (bounds != null) { // Restrict bounds to image limits intersect = intersect.intersection( new Rectangle(originX + bounds.x, originY + bounds.y, bounds.width, bounds.height)); } int[] iCoord = getPeak(subCorrMat, intersect.x, intersect.y, intersect.width, intersect.height); double scoreMax = subCorrMat.getf(iCoord[0], iCoord[1]); double[] dCoord = new double[] { iCoord[0], iCoord[1] }; double[] centre = null; switch (subPixelMethod) { case CUBIC: centre = performCubicFit(subCorrMat, iCoord[0], iCoord[1]); break; case GAUSSIAN: // Perform sub-peak analysis using the method taken from Jpiv centre = performGaussianFit(subCorrMat, iCoord[0], iCoord[1]); // Check the centre has not moved too far if (!(Math.abs(dCoord[0] - iCoord[0]) < intersect.width / 2 && Math.abs(dCoord[1] - iCoord[1]) < intersect.height / 2)) { centre = null; } break; default: break; } if (centre != null) { dCoord[0] = centre[0]; dCoord[1] = centre[1]; double score = subCorrMat.getBicubicInterpolatedPixel(centre[0], centre[1], subCorrMat); if (score < -1) score = -1; if (score > 1) score = 1; scoreMax = score; } // The correlation image is the size of the reference. // Offset from centre of reference lastXOffset = dCoord[0] - originX; lastYOffset = dCoord[1] - originY; return new double[] { lastXOffset, lastYOffset, scoreMax }; }
From source file:net.rptools.maptool.client.ui.ExportDialog.java
/** * Finds the extents of the map, sets up zone to be captured. If the user is * the GM, the extents include every object and everything that has any * area, such as 'fog' and 'visibility' objects. * <p>//from ww w.j av a 2 s .co m * If a background tiling texture is used, the image is aligned to it, so * that it can be used on re-import as a new base map image. * <p> * If the user is a player (or GM posing as a player), the extents only go * as far as the revealed fog-of-war. * <p> * Must be followed by postScreenshot at some point, or the Zone will be * messed up. * * @return the image to be saved */ private PlayerView preScreenshot() throws Exception, OutOfMemoryError { assert (!waitingForPostScreenshot) : "preScreenshot() called twice in a row!"; setupZoneLayers(); boolean viewAsPlayer = ExportRadioButtons.VIEW_PLAYER.isChecked(); // First, figure out the 'extents' of the canvas // This will be later modified by the fog (for players), // and by the tiling texture (for re-importing) // PlayerView view = new PlayerView(viewAsPlayer ? Player.Role.PLAYER : Player.Role.GM); Rectangle extents = renderer.zoneExtents(view); try { // Clip to what the players know about (if applicable). // This keeps the player from exporting the map to learn which // direction has more 'stuff' in it. if (viewAsPlayer) { Rectangle fogE = renderer.fogExtents(); // MapTool.showError(fogE.x + " " + fogE.y + " " + fogE.width + " " + fogE.height); if ((fogE.width < 0) || (fogE.height < 0)) { MapTool.showError(I18N.getString("dialog.screenshot.error.negativeFogExtents")); // Image is not clipped to show only fog-revealed areas!")); } else { extents = extents.intersection(fogE); } } } catch (Exception ex) { throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"), ex)); } if ((extents == null) || (extents.width == 0) || (extents.height == 0)) { throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"))); } // If output includes the tiling 'board' texture, move the upper-left corner // to an integer multiple of the background tile (so it matches up on import). // We don't need to move the lower-right corner because it doesn't matter for // aligning on importing. boolean drawBoard = ExportLayers.LAYER_BOARD.isChecked(); if (drawBoard) { DrawablePaint paint = renderer.getZone().getBackgroundPaint(); DrawableTexturePaint dummy = new DrawableTexturePaint(); Integer tileX = 0, tileY = 0; if (paint.getClass() == dummy.getClass()) { Image bgTexture = ImageManager.getImage(((DrawableTexturePaint) paint).getAsset().getId()); tileX = bgTexture.getWidth(null); tileY = bgTexture.getHeight(null); Integer x = ((int) Math.floor((float) extents.x / tileX)) * tileX; Integer y = ((int) Math.floor((float) extents.y / tileY)) * tileY; extents.width = extents.width + (extents.x - x); extents.height = extents.height + (extents.y - y); extents.x = x; extents.y = y; } } // Save the original state of the renderer to restore later. // Create a place to put the image, and // set up the renderer to encompass the whole extents of the map. origBounds = renderer.getBounds(); origScale = renderer.getZoneScale(); // Setup the renderer to use the new extents Scale s = new Scale(); s.setOffset(-extents.x, -extents.y); renderer.setZoneScale(s); renderer.setBounds(extents); waitingForPostScreenshot = true; return view; }
From source file:com.t3.client.ui.ExportDialog.java
/** * Finds the extents of the map, sets up zone to be captured. If the user is * the GM, the extents include every object and everything that has any * area, such as 'fog' and 'visibility' objects. * <p>/*from www.ja v a 2 s. c om*/ * If a background tiling texture is used, the image is aligned to it, so * that it can be used on re-import as a new base map image. * <p> * If the user is a player (or GM posing as a player), the extents only go * as far as the revealed fog-of-war. * <p> * Must be followed by postScreenshot at some point, or the Zone will be * messed up. * * @return the image to be saved */ private PlayerView preScreenshot() throws Exception, OutOfMemoryError { assert (!waitingForPostScreenshot) : "preScreenshot() called twice in a row!"; setupZoneLayers(); boolean viewAsPlayer = ExportRadioButtons.VIEW_PLAYER.isChecked(); // First, figure out the 'extents' of the canvas // This will be later modified by the fog (for players), // and by the tiling texture (for re-importing) // PlayerView view = new PlayerView(viewAsPlayer ? Player.Role.PLAYER : Player.Role.GM); Rectangle extents = renderer.zoneExtents(view); try { // Clip to what the players know about (if applicable). // This keeps the player from exporting the map to learn which // direction has more 'stuff' in it. if (viewAsPlayer) { Rectangle fogE = renderer.fogExtents(); // TabletopTool.showError(fogE.x + " " + fogE.y + " " + fogE.width + " " + fogE.height); if ((fogE.width < 0) || (fogE.height < 0)) { TabletopTool.showError(I18N.getString("dialog.screenshot.error.negativeFogExtents")); // Image is not clipped to show only fog-revealed areas!")); } else { extents = extents.intersection(fogE); } } } catch (Exception ex) { throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"), ex)); } if ((extents == null) || (extents.width == 0) || (extents.height == 0)) { throw (new Exception(I18N.getString("dialog.screenshot.error.noArea"))); } // If output includes the tiling 'board' texture, move the upper-left corner // to an integer multiple of the background tile (so it matches up on import). // We don't need to move the lower-right corner because it doesn't matter for // aligning on importing. boolean drawBoard = ExportLayers.LAYER_BOARD.isChecked(); if (drawBoard) { DrawablePaint paint = renderer.getZone().getBackgroundPaint(); DrawableTexturePaint dummy = new DrawableTexturePaint(); Integer tileX = 0, tileY = 0; if (paint.getClass() == dummy.getClass()) { Image bgTexture = ImageManager.getImage(((DrawableTexturePaint) paint).getAsset().getId()); tileX = bgTexture.getWidth(null); tileY = bgTexture.getHeight(null); Integer x = ((int) Math.floor((float) extents.x / tileX)) * tileX; Integer y = ((int) Math.floor((float) extents.y / tileY)) * tileY; extents.width = extents.width + (extents.x - x); extents.height = extents.height + (extents.y - y); extents.x = x; extents.y = y; } } // Save the original state of the renderer to restore later. // Create a place to put the image, and // set up the renderer to encompass the whole extents of the map. origBounds = renderer.getBounds(); origScale = renderer.getZoneScale(); // Setup the renderer to use the new extents Scale s = new Scale(); s.setOffset(-extents.x, -extents.y); renderer.setZoneScale(s); renderer.setBounds(extents); waitingForPostScreenshot = true; return view; }
From source file:gdsc.core.ij.AlignImagesFFT.java
private ImageProcessor alignImages(FHT refFHT, double[] s, double[] ss, ImageProcessor targetIp, int slice, WindowMethod windowMethod, Rectangle bounds, FloatProcessor fpCorrelation, FloatProcessor fpNormalised, SubPixelMethod subPixelMethod, int interpolationMethod, boolean clipOutput) { lastXOffset = lastYOffset = 0;//from w w w. ja va2 s . co m if (noValue(targetIp)) { // Zero correlation with empty image IJ.log(String.format("Best Slice %d x %g y %g = %g", slice, 0, 0, 0)); if (fpCorrelation != null) fpCorrelation.setPixels(new float[refFHT.getPixelCount()]); if (fpNormalised != null) fpNormalised.setPixels(new float[refFHT.getPixelCount()]); return targetIp.duplicate(); } // Perform correlation analysis in Fourier space (A and B transform to F and G) // using the complex conjugate of G multiplied by F: // C(u,v) = F(u,v) G*(u,v) int maxN = refFHT.getWidth(); ImageProcessor paddedTargetIp = padAndZero(targetIp, maxN, windowMethod, targetImageBounds); FloatProcessor normalisedTargetIp = normalise(paddedTargetIp); FHT targetFHT = fft(normalisedTargetIp, maxN); FloatProcessor subCorrMat = correlate(refFHT, targetFHT); //new ImagePlus("Unnormalised correlation", subCorrMat.duplicate()).show(); int originX = (maxN / 2); int originY = (maxN / 2); // Normalise using the denominator if (s != null) normalise(subCorrMat, s, ss, targetIp); // Copy back result images if (fpCorrelation != null) fpCorrelation.setPixels(subCorrMat.getPixels()); if (fpNormalised != null) fpNormalised.setPixels(normalisedTargetIp.getPixels()); Rectangle intersect = new Rectangle(0, 0, subCorrMat.getWidth(), subCorrMat.getHeight()); // Restrict the translation if (bounds != null) { // Restrict bounds to image limits intersect = intersect.intersection( new Rectangle(originX + bounds.x, originY + bounds.y, bounds.width, bounds.height)); } int[] iCoord = getPeak(subCorrMat, intersect.x, intersect.y, intersect.width, intersect.height); float scoreMax = subCorrMat.getf(iCoord[0], iCoord[1]); double[] dCoord = new double[] { iCoord[0], iCoord[1] }; String estimatedScore = ""; if (subPixelMethod != SubPixelMethod.NONE) { double[] centre = null; if (subPixelMethod == SubPixelMethod.CUBIC) { centre = performCubicFit(subCorrMat, iCoord[0], iCoord[1]); } else { // Perform sub-peak analysis using the method taken from Jpiv centre = performGaussianFit(subCorrMat, iCoord[0], iCoord[1]); // Check the centre has not moved too far if (!(Math.abs(dCoord[0] - iCoord[0]) < intersect.width / 2 && Math.abs(dCoord[1] - iCoord[1]) < intersect.height / 2)) { centre = null; } } if (centre != null) { dCoord[0] = centre[0]; dCoord[1] = centre[1]; double score = subCorrMat.getBicubicInterpolatedPixel(centre[0], centre[1], subCorrMat); // if (score < -1) // score = -1; // if (score > 1) // score = 1; estimatedScore = String.format(" (interpolated score %g)", score); } } else if (IJ.debugMode) { // Used for debugging - Check if interpolation rounds to a different integer double[] centre = performCubicFit(subCorrMat, iCoord[0], iCoord[1]); if (centre != null) { centre[0] = Math.round(centre[0]); centre[1] = Math.round(centre[1]); if (centre[0] != iCoord[0] || centre[1] != iCoord[1]) IJ.log(String.format("Cubic rounded to different integer: %d,%d => %d,%d", iCoord[0], iCoord[1], (int) centre[0], (int) centre[1])); } centre = performGaussianFit(subCorrMat, iCoord[0], iCoord[1]); if (centre != null) { centre[0] = Math.round(centre[0]); centre[1] = Math.round(centre[1]); if (centre[0] != iCoord[0] || centre[1] != iCoord[1]) IJ.log(String.format("Gaussian rounded to different integer: %d,%d => %d,%d", iCoord[0], iCoord[1], (int) centre[0], (int) centre[1])); } } // The correlation image is the size of the reference. // Offset from centre of reference lastXOffset = dCoord[0] - originX; lastYOffset = dCoord[1] - originY; IJ.log(String.format("Best Slice %d x %g y %g = %g%s", slice, lastXOffset, lastYOffset, scoreMax, estimatedScore)); // Translate the result and crop to the original size if (!doTranslation) return targetIp; ImageProcessor resultIp = translate(interpolationMethod, targetIp, lastXOffset, lastYOffset, clipOutput); return resultIp; }
From source file:org.esa.snap.rcp.statistics.ScatterPlotPanel.java
private void compute(final Mask selectedMask) { final RasterDataNode raster = getRaster(); final AttributeDescriptor dataField = scatterPlotModel.dataField; if (raster == null || dataField == null) { return;/*from w ww. j a v a 2s. c om*/ } SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() { @Override protected ComputedData[] doInBackground() throws Exception { SystemUtils.LOG.finest("start computing scatter plot data"); final List<ComputedData> computedDataList = new ArrayList<>(); final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource .getFeatureCollection(); final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]); final int boxSize = scatterPlotModel.boxSize; final Rectangle sceneRect = new Rectangle(raster.getRasterWidth(), raster.getRasterHeight()); final GeoCoding geoCoding = raster.getGeoCoding(); final AffineTransform imageToModelTransform; imageToModelTransform = Product.findImageToModelTransform(geoCoding); for (SimpleFeature feature : features) { final Point point = (Point) feature.getDefaultGeometryProperty().getValue(); Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY()); final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null); if (!sceneRect.contains(imagePos)) { continue; } final float imagePosX = (float) imagePos.getX(); final float imagePosY = (float) imagePos.getY(); final Rectangle imageRect = sceneRect.intersection(new Rectangle( ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize)); if (imageRect.isEmpty()) { continue; } final double[] rasterValues = new double[imageRect.width * imageRect.height]; raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues); final int[] maskBuffer = new int[imageRect.width * imageRect.height]; Arrays.fill(maskBuffer, 1); if (selectedMask != null) { selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, maskBuffer); } final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2); if (maskBuffer[centerIndex] == 0) { continue; } double sum = 0; double sumSqr = 0; int n = 0; boolean valid = false; for (int y = 0; y < imageRect.height; y++) { for (int x = 0; x < imageRect.width; x++) { final int index = y * imageRect.height + x; if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) { final double rasterValue = rasterValues[index]; sum += rasterValue; sumSqr += rasterValue * rasterValue; n++; valid = true; } } } if (!valid) { continue; } double rasterMean = sum / n; double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0; String localName = dataField.getLocalName(); Number attribute = (Number) feature.getAttribute(localName); final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties(); final float correlativeData = attribute.floatValue(); final GeoPos geoPos = new GeoPos(); if (geoCoding.canGetGeoPos()) { final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY); geoCoding.getGeoPos(pixelPos, geoPos); } else { geoPos.setInvalid(); } computedDataList.add( new ComputedData(imagePosX, imagePosY, (float) geoPos.getLat(), (float) geoPos.getLon(), (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties)); } return computedDataList.toArray(new ComputedData[computedDataList.size()]); } @Override public void done() { try { final ValueAxis xAxis = getPlot().getDomainAxis(); final ValueAxis yAxis = getPlot().getRangeAxis(); xAxis.setAutoRange(false); yAxis.setAutoRange(false); scatterpointsDataset.removeAllSeries(); acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); computedDatas = null; final ComputedData[] data = get(); if (data.length == 0) { return; } computedDatas = data; final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName()); for (ComputedData computedData : computedDatas) { final float rasterMean = computedData.rasterMean; final float rasterSigma = computedData.rasterSigma; final float correlativeData = computedData.correlativeData; scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean, rasterMean - rasterSigma, rasterMean + rasterSigma); } computingData = true; scatterpointsDataset.addSeries(scatterValues); xAxis.setAutoRange(true); yAxis.setAutoRange(true); xAxis.setAutoRange(false); yAxis.setAutoRange(false); xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound()); yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound()); if (xAxisRangeControl.isAutoMinMax()) { xAxisRangeControl.adjustComponents(xAxis, 3); } else { xAxisRangeControl.adjustAxis(xAxis, 3); } if (yAxisRangeControl.isAutoMinMax()) { yAxisRangeControl.adjustComponents(yAxis, 3); } else { yAxisRangeControl.adjustAxis(yAxis, 3); } computeRegressionAndAcceptableDeviationData(); computingData = false; } catch (InterruptedException | CancellationException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e); Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n" + "Calculation canceled.", JOptionPane.ERROR_MESSAGE, null); } catch (ExecutionException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e); Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n" + "An error occurred:\n" + e.getCause().getMessage(), JOptionPane.ERROR_MESSAGE, null); } } }; swingWorker.execute(); }
From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java
private void compute(final Mask selectedMask) { final RasterDataNode raster = getRaster(); final AttributeDescriptor dataField = scatterPlotModel.dataField; if (raster == null || dataField == null) { return;//from ww w . j ava 2 s .c o m } SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() { @Override protected ComputedData[] doInBackground() throws Exception { BeamLogManager.getSystemLogger().finest("start computing scatter plot data"); final List<ComputedData> computedDataList = new ArrayList<>(); final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource .getFeatureCollection(); final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]); final int boxSize = scatterPlotModel.boxSize; final Rectangle sceneRect = new Rectangle(raster.getSceneRasterWidth(), raster.getSceneRasterHeight()); final GeoCoding geoCoding = raster.getGeoCoding(); final AffineTransform imageToModelTransform; imageToModelTransform = ImageManager.getImageToModelTransform(geoCoding); for (SimpleFeature feature : features) { final Point point = (Point) feature.getDefaultGeometryProperty().getValue(); Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY()); final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null); if (!sceneRect.contains(imagePos)) { continue; } final float imagePosX = (float) imagePos.getX(); final float imagePosY = (float) imagePos.getY(); final Rectangle imageRect = sceneRect.intersection(new Rectangle( ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize)); if (imageRect.isEmpty()) { continue; } final double[] rasterValues = new double[imageRect.width * imageRect.height]; raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues); final int[] maskBuffer = new int[imageRect.width * imageRect.height]; Arrays.fill(maskBuffer, 1); if (selectedMask != null) { selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, maskBuffer); } final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2); if (maskBuffer[centerIndex] == 0) { continue; } double sum = 0; double sumSqr = 0; int n = 0; boolean valid = false; for (int y = 0; y < imageRect.height; y++) { for (int x = 0; x < imageRect.width; x++) { final int index = y * imageRect.height + x; if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) { final double rasterValue = rasterValues[index]; sum += rasterValue; sumSqr += rasterValue * rasterValue; n++; valid = true; } } } if (!valid) { continue; } double rasterMean = sum / n; double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0; String localName = dataField.getLocalName(); Number attribute = (Number) feature.getAttribute(localName); final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties(); final float correlativeData = attribute.floatValue(); final GeoPos geoPos = new GeoPos(); if (geoCoding.canGetGeoPos()) { final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY); geoCoding.getGeoPos(pixelPos, geoPos); } else { geoPos.setInvalid(); } computedDataList.add(new ComputedData(imagePosX, imagePosY, geoPos.getLat(), geoPos.getLon(), (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties)); } return computedDataList.toArray(new ComputedData[computedDataList.size()]); } @Override public void done() { try { final ValueAxis xAxis = getPlot().getDomainAxis(); final ValueAxis yAxis = getPlot().getRangeAxis(); xAxis.setAutoRange(false); yAxis.setAutoRange(false); scatterpointsDataset.removeAllSeries(); acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); computedDatas = null; final ComputedData[] data = get(); if (data.length == 0) { return; } computedDatas = data; final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName()); for (ComputedData computedData : computedDatas) { final float rasterMean = computedData.rasterMean; final float rasterSigma = computedData.rasterSigma; final float correlativeData = computedData.correlativeData; scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean, rasterMean - rasterSigma, rasterMean + rasterSigma); } computingData = true; scatterpointsDataset.addSeries(scatterValues); xAxis.setAutoRange(true); yAxis.setAutoRange(true); xAxis.setAutoRange(false); yAxis.setAutoRange(false); xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound()); yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound()); if (xAxisRangeControl.isAutoMinMax()) { xAxisRangeControl.adjustComponents(xAxis, 3); } else { xAxisRangeControl.adjustAxis(xAxis, 3); } if (yAxisRangeControl.isAutoMinMax()) { yAxisRangeControl.adjustComponents(yAxis, 3); } else { yAxisRangeControl.adjustAxis(yAxis, 3); } computeRegressionAndAcceptableDeviationData(); computingData = false; } catch (InterruptedException | CancellationException e) { BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e); JOptionPane.showMessageDialog(getParentDialogContentPane(), "Failed to compute correlative plot.\n" + "Calculation canceled.", /*I18N*/ CHART_TITLE, /*I18N*/ JOptionPane.ERROR_MESSAGE); } catch (ExecutionException e) { BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e); JOptionPane.showMessageDialog(getParentDialogContentPane(), "Failed to compute correlative plot.\n" + "An error occurred:\n" + e.getCause().getMessage(), CHART_TITLE, /*I18N*/ JOptionPane.ERROR_MESSAGE); } } }; swingWorker.execute(); }
From source file:gdsc.core.ij.AlignImagesFFT.java
/** * Normalise the correlation matrix using the standard deviation of the region from the reference that is covered by * the target//from w w w . ja va 2 s.com * * @param subCorrMat * @param s * @param ss * @param targetIp */ private void normalise(FloatProcessor subCorrMat, double[] s, double[] ss, ImageProcessor targetIp) { int maxx = subCorrMat.getWidth(); int maxy = subCorrMat.getHeight(); Rectangle imageBounds = new Rectangle(0, 0, maxx, maxy); //refImageBounds; int NU = targetIp.getWidth(); int NV = targetIp.getHeight(); // Locate where the target image was inserted when padding int x = targetImageBounds.x; // (maxx - NU) / 2; int y = targetImageBounds.y; // (maxy - NV) / 2; //IJ.log(String.format("maxx=%d, maxy=%d, NU=%d, NV=%d, x=%d, y=%d", maxx, maxy, NU, NV, x, y)); // Calculate overlap: // Assume a full size target image relative to the reference and then compensate with the insert location int halfNU = maxx / 2 - x; int halfNV = maxy / 2 - y; // Normalise within the bounds of the largest image (i.e. only allow translation // up to half of the longest edge from the reference or target). // The further the translation from the half-max translation the more likely there // can be errors in the normalisation score due to floating point summation errors. // This is observed mainly at the very last pixel overlap between images. // To see this set: // union = imageBounds; // TODO - More analysis to determine under what conditions this occurs. Rectangle union = refImageBounds.union(targetImageBounds); // Normalise using the denominator float[] data = (float[]) subCorrMat.getPixels(); float[] newData = new float[data.length]; for (int yyy = union.y; yyy < union.y + union.height; yyy++) { int i = yyy * maxx + union.x; for (int xxx = union.x; xxx < union.x + union.width; xxx++, i++) { double sum = 0; double sumSquares = 0; int minU = xxx - halfNU - 1; int maxU = FastMath.min(minU + NU, maxx - 1); int minV = yyy - halfNV - 1; int maxV = FastMath.min(minV + NV, maxy - 1); // Compute sum from rolling sum using: // sum(u,v) = // + s(u+N-1,v+N-1) // - s(u-1,v+N-1) // - s(u+N-1,v-1) // + s(u-1,v-1) // Note: // s(u,v) = 0 when either u,v < 0 // s(u,v) = s(umax,v) when u>umax // s(u,v) = s(u,vmax) when v>vmax // s(u,v) = s(umax,vmax) when u>umax,v>vmax // Likewise for ss // + s(u+N-1,v+N-1) int index = maxV * maxx + maxU; sum += s[index]; sumSquares += ss[index]; if (minU >= 0) { // - s(u-1,v+N-1) index = maxV * maxx + minU; sum -= s[index]; sumSquares -= ss[index]; } if (minV >= 0) { // - s(u+N-1,v-1) index = minV * maxx + maxU; sum -= s[index]; sumSquares -= ss[index]; if (minU >= 0) { // + s(u-1,v-1) index = minV * maxx + minU; sum += s[index]; sumSquares += ss[index]; } } // Reset to bounds to calculate the number of pixels if (minU < 0) minU = 0; if (minV < 0) minV = 0; Rectangle regionBounds = new Rectangle(xxx - halfNU, yyy - halfNV, NU, NV); Rectangle r = imageBounds.intersection(regionBounds); //int n = (maxU - minU + 1) * (maxV - minV + 1); int n = r.width * r.height; if (n < 1) continue; // Get the sum of squared differences double residuals = sumSquares - sum * sum / n; // // Check using the original data // double sx = 0; // double ssx = 0; // int nn = 0; // for (int yy = yyy - halfNV; yy < yyy - halfNV + NV; yy++) // for (int xx = xxx - halfNU; xx < xxx - halfNU + NU; xx++) // { // if (xx >= 0 && xx < maxx && yy >= 0 && yy < maxy) // { // float value = normalisedRefIp.getf(xx, yy); // sx += value; // ssx += value * value; // nn++; // } // } // gdsc.fitting.utils.DoubleEquality eq = new gdsc.fitting.utils.DoubleEquality(8, 1e-16); // if (n != nn) // { // System.out.printf("Wrong @ %d,%d %d <> %d\n", xxx, yyy, n, nn); // residuals = ssx - sx * sx / nn; // } // else if (!eq.almostEqualComplement(sx, sum) || !eq.almostEqualComplement(ssx, sumSquares)) // { // System.out.printf("Wrong @ %d,%d %g <> %g : %g <> %g\n", xxx, yyy, sx, sum, ssx, sumSquares); // residuals = ssx - sx * sx / nn; // } double normalisation = (residuals > 0) ? Math.sqrt(residuals) : 0; if (normalisation > 0) { newData[i] = (float) (data[i] / normalisation); // Watch out for normalisation errors which cause problems when displaying the image data. if (newData[i] < -1.1f) newData[i] = -1.1f; if (newData[i] > 1.1f) newData[i] = 1.1f; } } } subCorrMat.setPixels(newData); }
From source file:Distortions.java
public void singleSensorExtrapolationMapped(int sensoNum, double[][] gridPCorr, double[] sensorMask, int width, int decimation, double alphaThreshold, double step, double[] centerPXY, double interpolationSigma, // sensor pixels double tangentialRadius, int scanDistance, // sensor pixels int resultDistance, int interpolationDegree, boolean useAlpha, // false - sensor mask boolean showDebugImages, int debugLevel) { int dxIndex = 0; int alphaIndex = 2; int rIndex = 3; int height = gridPCorr[0].length / width; double gaussianK = -0.5 / (interpolationSigma * interpolationSigma); double tangR0 = tangentialRadius * Math.sqrt(width * height) * decimation / 2; // sigma in tangential direction is interpolationSigma*(1+r/tangR0), in radial - interpolationSigma PolynomialApproximation polynomialApproximation = new PolynomialApproximation(0);// no debug int length = gridPCorr[0].length; DirInc dirInc = new DirInc(width, height); int[] iMap = new int[length]; for (int i = 0; i < length; i++) iMap[i] = (gridPCorr[alphaIndex][i] >= alphaThreshold) ? 1 : 0; List<Integer> waveList = new ArrayList<Integer>(1000); for (int index0 = 0; index0 < length; index0++) if (iMap[index0] == 0) { for (int iDir = 0; iDir < 8; iDir += 2) { int index = dirInc.newIndex(index0, iDir); if ((index >= 0) && (iMap[index] == 1)) { iMap[index0] = 2;//from ww w. ja va 2 s . com waveList.add(new Integer(index0)); break; } } } // decimate the wave list List<Integer> seedList = new ArrayList<Integer>(1000); int oldIndex = 0; // find better start? int s2 = (int) Math.floor(step * step); while (waveList.size() > 0) { int oldX = oldIndex % width; int oldY = oldIndex / width; int bestD2 = height * height + width * width; int nBest = -1; for (int n = 0; n < waveList.size(); n++) { int index = waveList.get(n); int dx = index % width - oldX; int dy = index / width - oldY; int d2 = dx * dx + dy * dy; if (d2 < bestD2) { bestD2 = d2; nBest = n; } } oldIndex = waveList.remove(nBest); seedList.add(new Integer(oldIndex)); oldX = oldIndex % width; oldY = oldIndex / width; // remove all closer than step for (int n = 0; n < waveList.size(); n++) { // size will change int index = waveList.get(n); int dx = index % width - oldX; int dy = index / width - oldY; int d2 = dx * dx + dy * dy; if (d2 < s2) { waveList.remove(n); } } } //while (waveList.size()>0) // debug show waves? Rectangle full = new Rectangle(0, 0, width, height); double[][] extrapolated = new double[gridPCorr.length][length]; for (int n = 0; n < extrapolated.length; n++) for (int i = 0; i < extrapolated[n].length; i++) extrapolated[n][i] = 0.0; int halfScanSize = scanDistance / decimation + 1; int halfInterpolteSize = resultDistance / decimation + 1; for (int n = 0; n < seedList.size(); n++) { int index0 = seedList.get(n); int x0 = index0 % width; int y0 = index0 / width; double[] dCxy0 = { x0 * decimation - centerPXY[0], y0 * decimation - centerPXY[1] }; double r0 = Math.sqrt(dCxy0[0] * dCxy0[0] + dCxy0[1] * dCxy0[1]); final Rectangle scan = full.intersection(new Rectangle(x0 - halfScanSize, y0 - halfScanSize, 2 * halfScanSize + 1, 2 * halfScanSize + 1)); waveList.clear(); for (int y = scan.y; y < (scan.y + scan.height); y++) for (int x = scan.x; x < (scan.x + scan.width); x++) { int index = y * width + x; if (iMap[index] == 1) waveList.add(new Integer(index)); } double[][][] data = new double[5][waveList.size()][3]; // x,y,w double sumWeights = 0.0; double rScaleTangSigma = 1.0 / (1.0 + r0 / tangR0); // for (int i = 0; i < data[0].length; i++) { int index = waveList.get(i); int x = index % width; int y = index / width; double[] dCxy = { x * decimation - centerPXY[0], y * decimation - centerPXY[1] }; double[] ddCxy = { dCxy[0] - dCxy0[0], dCxy[1] - dCxy0[1] }; double rc = Math.sqrt(dCxy[0] * dCxy[0] + dCxy[1] * dCxy[1]); // distance from lens center (in sensor pixels) double rDiff = rc - r0; double[] uRadVect = { (rc > 0.0) ? (dCxy[0] / rc) : 0.0, (rc > 0.0) ? (dCxy[1] / rc) : 0.0 }; double distRad = ddCxy[0] * uRadVect[0] + ddCxy[1] * uRadVect[1]; // radial distance form the center (seed point) double distTan = -ddCxy[0] * uRadVect[1] + ddCxy[1] * uRadVect[0]; // tangential distance form the center (seed point) distTan *= rScaleTangSigma; // // for the center (seed point). was distTan/=(1.0+rc/tangR0); double w = Math.exp(gaussianK * (distRad * distRad + distTan * distTan)) * gridPCorr[alphaIndex][index]; sumWeights += w; double dRad = gridPCorr[dxIndex + 0][index] * uRadVect[0] + gridPCorr[dxIndex + 1][index] * uRadVect[1]; // radial component double dTan = -gridPCorr[dxIndex + 0][index] * uRadVect[1] + gridPCorr[dxIndex + 1][index] * uRadVect[0]; // tangential component data[0][i][1] = dRad; data[1][i][1] = dTan; data[2][i][1] = gridPCorr[rIndex + 0][index]; // R data[3][i][1] = gridPCorr[rIndex + 1][index]; // G data[4][i][1] = gridPCorr[rIndex + 2][index]; // B for (int j = 0; j < data.length; j++) { data[j][i][0] = rDiff; data[j][i][2] = w; } } sumWeights *= rScaleTangSigma; // normalize for expanded in one dimension gaussian double[][] poly = new double[data.length][]; for (int j = 0; j < poly.length; j++) { poly[j] = polynomialApproximation.polynomialApproximation1d(data[j], interpolationDegree); } if (poly[0] == null) { // all will be either null, or not - [0] testing is enough System.out.println("singleSensorExtrapolationMapped() BUG - poly[0]==null"); // stageReprojPXY[index0]=null; continue; } final Rectangle rInterpolate = full.intersection(new Rectangle(x0 - halfInterpolteSize, y0 - halfInterpolteSize, 2 * halfInterpolteSize + 1, 2 * halfInterpolteSize + 1)); for (int y = rInterpolate.y; y < (rInterpolate.y + rInterpolate.height); y++) for (int x = rInterpolate.x; x < (rInterpolate.x + rInterpolate.width); x++) { int index = y * width + x; double[] dCxy = { x * decimation - centerPXY[0], y * decimation - centerPXY[1] }; double[] ddCxy = { dCxy[0] - dCxy0[0], dCxy[1] - dCxy0[1] }; double rc = Math.sqrt(dCxy[0] * dCxy[0] + dCxy[1] * dCxy[1]); // distance from lens center (in sensor pixels) double rDiff = rc - r0; double[] uRadVect = { (rc > 0.0) ? (dCxy[0] / rc) : 0.0, (rc > 0.0) ? (dCxy[1] / rc) : 0.0 }; double distRad = ddCxy[0] * uRadVect[0] + ddCxy[1] * uRadVect[1]; // radial distance form the center (seed point) double distTan = -ddCxy[0] * uRadVect[1] + ddCxy[1] * uRadVect[0]; // tangential distance form the center (seed point) distTan *= rScaleTangSigma; double w = Math.exp(gaussianK * (distRad * distRad + distTan * distTan)); //*gridPCorr[alphaIndex][index]; w *= sumWeights; // more points were used in coefficients calculation, more trust to that extrapolation // extrapolate each value using polynomial coefficients double[] results = new double[poly.length]; for (int nPar = 0; nPar < results.length; nPar++) { double rN = 1.0; results[nPar] = 0.0; for (int dgr = 0; dgr < poly[nPar].length; dgr++) { results[nPar] += poly[nPar][dgr] * rN; rN *= rDiff; } } // restore dX, dY from radial/tangential double[] diffPXY = { results[0] * uRadVect[0] - results[1] * uRadVect[1], results[0] * uRadVect[1] + results[1] * uRadVect[0] }; //accumulate extrapolated[dxIndex + 0][index] += diffPXY[0] * w; extrapolated[dxIndex + 1][index] += diffPXY[1] * w; extrapolated[rIndex + 0][index] += results[2] * w; extrapolated[rIndex + 1][index] += results[3] * w; extrapolated[rIndex + 2][index] += results[4] * w; extrapolated[alphaIndex][index] += w; } } // for (int n=0; n<seedList.size();n++) { // divide by weight for (int index = 0; index < length; index++) if (extrapolated[alphaIndex][index] > 0.0) { for (int i = 0; i < extrapolated.length; i++) if (i != alphaIndex) { extrapolated[i][index] /= extrapolated[alphaIndex][index]; } } // debug show here extrapolated if (showDebugImages) { String[] debugTiles = { "dX", "dY", "alpha", "R", "G", "B", "mask" }; double[] debugMask = new double[length]; for (int i = 0; i < length; i++) debugMask[i] = iMap[i]; for (int n = 0; n < seedList.size(); n++) { int index = seedList.get(n); debugMask[index] += 3.0; } //iMap[index0] double[][] debugData = { extrapolated[0], extrapolated[1], extrapolated[2], extrapolated[3], extrapolated[4], extrapolated[5], debugMask }; (new showDoubleFloatArrays()).showArrays(debugData, width, height, true, "EX-" + sensoNum, debugTiles); } // mix interpolated with original data // double [] sensorMask, //gridPCorr for (int index = 0; index < length; index++) if (extrapolated[alphaIndex][index] > 0.0) { for (int i = 0; i < extrapolated.length; i++) if (i != alphaIndex) { double w = useAlpha ? (gridPCorr[alphaIndex][index]) : ((gridPCorr[alphaIndex][index] > 0.0) ? sensorMask[index] : 0.0); gridPCorr[i][index] = gridPCorr[i][index] * w + extrapolated[i][index] * (1.0 - w); } } }
From source file:org.eclipse.jubula.rc.javafx.tester.adapter.TreeOperationContext.java
@Override public Rectangle getVisibleRowBounds(final Rectangle rowBounds) { Rectangle result = EventThreadQueuerJavaFXImpl.invokeAndWait("getVisibleRowBounds", //$NON-NLS-1$ new Callable<Rectangle>() { @Override/* w ww. j a va2 s . com*/ public Rectangle call() throws Exception { TreeView<?> tree = ((TreeView<?>) getTree()); // Update the layout coordinates otherwise // we would get old position values tree.layout(); Rectangle visibleTreeBounds = new Rectangle(0, 0, Rounding.round(tree.getWidth()), Rounding.round(tree.getHeight())); return rowBounds.intersection(visibleTreeBounds); } }); return result; }