/** Checks if the player collides with a blip, power blip, or a ghost. */ public void checkCollision() { Rectangle playerRect = new Rectangle(player.getCenter().x - 8, player.getCenter().y - 8, 13, 13); for (Enemy enemy : enemies) { Rectangle enemyRect = new Rectangle(enemy.getCenter().x - 8, enemy.getCenter().y - 8, 13, 13); if (playerRect.intersects(enemyRect)) { if (!enemy.isAlive()) { continue; } if (Globals.state == ENEMY_HUNTER_STATE) { Globals.game.playerKilled(); player.loseALife(); // player is dead, so we paint the dead player screen paintDeadPlayer(); try { // sleep to make it stay on screen Thread.sleep(1500); } catch (InterruptedException e) { // DO nothing } resetCanvas(); // we return because only one enemy should be able to make a player lose a life return; } else if (Globals.state == ENEMY_HUNTED_STATE) { if (enemy.isAlive()) { enemy.setAlive(false); player.addPoints(POINTS_FOR_KILLING_ENEMY); } } } else { continue; } } }
public void zoomIn() { Dimension asz = this.getSize(); int maxzf = 3; int coef = 1; int r; cmdline = "/bin/sh get.sh " + j2kfilename + " " + iw + " " + ih + " " + rect.x + " " + rect.y + " " + rect.width + " " + rect.height; Exec.execPrint(cmdline); rect.x = rect.y = rect.width = rect.height = 0; img = pgm.open("out.pgm"); iw = img.getWidth(this); ih = img.getHeight(this); bi = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB); big = bi.createGraphics(); selected = 0; fullRefresh = true; repaint(); }
/** Enlarge the canvas if the user enlarges the window. */ void resizeCanvas(int width, int height) { ImageWindow win = imp.getWindow(); // IJ.log("resizeCanvas: "+srcRect+" "+imageWidth+" "+imageHeight+" "+width+" "+height+" // "+dstWidth+" "+dstHeight+" "+win.maxBounds); if (!maxBoundsReset && (width > dstWidth || height > dstHeight) && win != null && win.maxBounds != null && width != win.maxBounds.width - 10) { if (resetMaxBoundsCount != 0) resetMaxBounds(); // Works around problem that prevented window from being larger than // maximized size resetMaxBoundsCount++; } if (IJ.altKeyDown()) { fitToWindow(); return; } if (srcRect.width < imageWidth || srcRect.height < imageHeight) { if (width > imageWidth * magnification) width = (int) (imageWidth * magnification); if (height > imageHeight * magnification) height = (int) (imageHeight * magnification); setDrawingSize(width, height); srcRect.width = (int) (dstWidth / magnification); srcRect.height = (int) (dstHeight / magnification); if ((srcRect.x + srcRect.width) > imageWidth) srcRect.x = imageWidth - srcRect.width; if ((srcRect.y + srcRect.height) > imageHeight) srcRect.y = imageHeight - srcRect.height; repaint(); } // IJ.log("resizeCanvas2: "+srcRect+" "+dstWidth+" "+dstHeight+" "+width+" "+height); }
private void drawSelection(Graphics2D g2d) { if (srcx != destx || srcy != desty) { int x1 = (srcx < destx) ? srcx : destx; int y1 = (srcy < desty) ? srcy : desty; int x2 = (srcx > destx) ? srcx : destx; int y2 = (srcy > desty) ? srcy : desty; rectSelection.x = x1; rectSelection.y = y1; rectSelection.width = (x2 - x1) + 1; rectSelection.height = (y2 - y1) + 1; if (rectSelection.width > 0 && rectSelection.height > 0) { g2d.drawImage(scr_img.getSubimage(x1, y1, x2 - x1 + 1, y2 - y1 + 1), null, x1, y1); } g2d.setColor(selFrameColor); g2d.setStroke(bs); g2d.draw(rectSelection); int cx = (x1 + x2) / 2; int cy = (y1 + y2) / 2; g2d.setColor(selCrossColor); g2d.setStroke(_StrokeCross); g2d.drawLine(cx, y1, cx, y2); g2d.drawLine(x1, cy, x2, cy); if (Screen.getNumberScreens() > 1) { drawScreenFrame(g2d, srcScreenId); } } }
/* * Create a BufferedImage for AWT components. * * @param component AWT component to create image from * @param fileName name of file to be created or null * @return image the image for the given region * @exception AWTException see Robot class constructors * @exception IOException if an error occurs during writing */ public static BufferedImage createImage(Component component, String fileName) throws AWTException, IOException { Point p = new Point(0, 0); SwingUtilities.convertPointToScreen(p, component); Rectangle region = component.getBounds(); region.x = p.x; region.y = p.y; return ScreenCapture.createImage(region, fileName); }
/** * Zooms out by making the source rectangle (srcRect) larger and centering it on (x,y). If we * can't make it larger, then make the window smaller. */ public void zoomOut(int x, int y) { if (magnification <= 0.03125) return; double oldMag = magnification; double newMag = getLowerZoomLevel(magnification); double srcRatio = (double) srcRect.width / srcRect.height; double imageRatio = (double) imageWidth / imageHeight; double initialMag = imp.getWindow().getInitialMagnification(); if (Math.abs(srcRatio - imageRatio) > 0.05) { double scale = oldMag / newMag; int newSrcWidth = (int) Math.round(srcRect.width * scale); int newSrcHeight = (int) Math.round(srcRect.height * scale); if (newSrcWidth > imageWidth) newSrcWidth = imageWidth; if (newSrcHeight > imageHeight) newSrcHeight = imageHeight; int newSrcX = srcRect.x - (newSrcWidth - srcRect.width) / 2; int newSrcY = srcRect.y - (newSrcHeight - srcRect.height) / 2; if (newSrcX < 0) newSrcX = 0; if (newSrcY < 0) newSrcY = 0; srcRect = new Rectangle(newSrcX, newSrcY, newSrcWidth, newSrcHeight); // IJ.log(newMag+" "+srcRect+" "+dstWidth+" "+dstHeight); int newDstWidth = (int) (srcRect.width * newMag); int newDstHeight = (int) (srcRect.height * newMag); setMagnification(newMag); setMaxBounds(); // IJ.log(newDstWidth+" "+dstWidth+" "+newDstHeight+" "+dstHeight); if (newDstWidth < dstWidth || newDstHeight < dstHeight) { // IJ.log("pack"); setDrawingSize(newDstWidth, newDstHeight); imp.getWindow().pack(); } else repaint(); return; } if (imageWidth * newMag > dstWidth) { int w = (int) Math.round(dstWidth / newMag); if (w * newMag < dstWidth) w++; int h = (int) Math.round(dstHeight / newMag); if (h * newMag < dstHeight) h++; x = offScreenX(x); y = offScreenY(y); Rectangle r = new Rectangle(x - w / 2, y - h / 2, w, h); if (r.x < 0) r.x = 0; if (r.y < 0) r.y = 0; if (r.x + w > imageWidth) r.x = imageWidth - w; if (r.y + h > imageHeight) r.y = imageHeight - h; srcRect = r; } else { srcRect = new Rectangle(0, 0, imageWidth, imageHeight); setDrawingSize((int) (imageWidth * newMag), (int) (imageHeight * newMag)); // setDrawingSize(dstWidth/2, dstHeight/2); imp.getWindow().pack(); } // IJ.write(newMag + " " + srcRect.x+" "+srcRect.y+" "+srcRect.width+" "+srcRect.height+" // "+dstWidth + " " + dstHeight); setMagnification(newMag); // IJ.write(srcRect.x + " " + srcRect.width + " " + dstWidth); setMaxBounds(); repaint(); }
/** * With segmented selections, ignore first mouse up and finalize when user double-clicks, * control-clicks or clicks in start box. */ protected void handleMouseUp(int sx, int sy) { if (state == MOVING) { state = NORMAL; return; } if (state == MOVING_HANDLE) { cachedMask = null; // mask is no longer valid state = NORMAL; updateClipRect(); oldX = x; oldY = y; oldWidth = width; oldHeight = height; return; } if (state != CONSTRUCTING) return; if (IJ.spaceBarDown()) // is user scrolling image? return; boolean samePoint = false; if (xpf != null) samePoint = (xpf[nPoints - 2] == xpf[nPoints - 1] && ypf[nPoints - 2] == ypf[nPoints - 1]); else samePoint = (xp[nPoints - 2] == xp[nPoints - 1] && yp[nPoints - 2] == yp[nPoints - 1]); Rectangle biggerStartBox = new Rectangle(ic.screenXD(startXD) - 5, ic.screenYD(startYD) - 5, 10, 10); if (nPoints > 2 && (biggerStartBox.contains(sx, sy) || (ic.offScreenXD(sx) == startXD && ic.offScreenYD(sy) == startYD) || (samePoint && (System.currentTimeMillis() - mouseUpTime) <= 500))) { nPoints--; addOffset(); finishPolygon(); return; } else if (!samePoint) { mouseUpTime = System.currentTimeMillis(); if (type == ANGLE && nPoints == 3) { addOffset(); finishPolygon(); return; } // add point to polygon if (xpf != null) { xpf[nPoints] = xpf[nPoints - 1]; ypf[nPoints] = ypf[nPoints - 1]; nPoints++; if (nPoints == xpf.length) enlargeArrays(); } else { xp[nPoints] = xp[nPoints - 1]; yp[nPoints] = yp[nPoints - 1]; nPoints++; if (nPoints == xp.length) enlargeArrays(); } // if (lineWidth>1) fitSpline(); } }
/** [Internal] */ public void paintComponent(Graphics g) { boolean opq = true; if (theOpaque != null) opq = theOpaque; super.setOpaque(opq); // if(theBackground!=null)super.setBackground(theBackground); super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; Rectangle rt = getBounds(); rt.x = 0; rt.y = 0; doBuffer(g2, opq, rt); chkFPS(); }
public ScreenImage getSelection() { if (canceled) { return null; } BufferedImage cropImg = cropSelection(); if (cropImg == null) { return null; } rectSelection.x += scrOCP.getX(); rectSelection.y += scrOCP.getY(); ScreenImage ret = new ScreenImage(rectSelection, cropImg); return ret; }
/** * Writes the <code>shape</code>, <code>coords</code>, <code>href</code>, * <code>nohref</code> Attribute for the specified figure and ellipse. * * @return Returns true, if the circle is inside of the image bounds. */ private boolean writeCircleAttributes(IXMLElement elem, SVGFigure f, Ellipse2D.Double ellipse) { AffineTransform t = TRANSFORM.getClone(f); if (t == null) { t = drawingTransform; } else { t.preConcatenate(drawingTransform); } if ((t.getType() & (AffineTransform.TYPE_UNIFORM_SCALE | AffineTransform.TYPE_TRANSLATION)) == t.getType() && ellipse.width == ellipse.height ) { Point2D.Double start = new Point2D.Double(ellipse.x, ellipse.y); Point2D.Double end = new Point2D.Double(ellipse.x + ellipse.width, ellipse.y + ellipse.height); t.transform(start, start); t.transform(end, end); ellipse.x = Math.min(start.x, end.x); ellipse.y = Math.min(start.y, end.y); ellipse.width = Math.abs(start.x - end.x); ellipse.height = Math.abs(start.y - end.y); elem.setAttribute("shape", "circle"); elem.setAttribute("coords", (int) (ellipse.x + ellipse.width / 2d)+","+ (int) (ellipse.y + ellipse.height / 2d)+","+ (int) (ellipse.width / 2d) ); writeHrefAttribute(elem, f); return bounds.intersects(ellipse.getBounds()); } else { return writePolyAttributes(elem, f, (Shape) ellipse); } }
protected void scroll(int sx, int sy) { int ox = xSrcStart + (int) (sx / magnification); // convert to offscreen coordinates int oy = ySrcStart + (int) (sy / magnification); // IJ.log("scroll: "+ox+" "+oy+" "+xMouseStart+" "+yMouseStart); int newx = xSrcStart + (xMouseStart - ox); int newy = ySrcStart + (yMouseStart - oy); if (newx < 0) newx = 0; if (newy < 0) newy = 0; if ((newx + srcRect.width) > imageWidth) newx = imageWidth - srcRect.width; if ((newy + srcRect.height) > imageHeight) newy = imageHeight - srcRect.height; srcRect.x = newx; srcRect.y = newy; // IJ.log(sx+" "+sy+" "+newx+" "+newy+" "+srcRect); imp.draw(); Thread.yield(); }
void adjustSourceRect(double newMag, int x, int y) { // IJ.log("adjustSourceRect1: "+newMag+" "+dstWidth+" "+dstHeight); int w = (int) Math.round(dstWidth / newMag); if (w * newMag < dstWidth) w++; int h = (int) Math.round(dstHeight / newMag); if (h * newMag < dstHeight) h++; x = offScreenX(x); y = offScreenY(y); Rectangle r = new Rectangle(x - w / 2, y - h / 2, w, h); if (r.x < 0) r.x = 0; if (r.y < 0) r.y = 0; if (r.x + w > imageWidth) r.x = imageWidth - w; if (r.y + h > imageHeight) r.y = imageHeight - h; srcRect = r; setMagnification(newMag); // IJ.log("adjustSourceRect2: "+srcRect+" "+dstWidth+" "+dstHeight); }
private WritableRaster clipToRect( final WritableRaster raster, final Rectangle rect, final int[] bands) { if (rect.contains(raster.getMinX(), raster.getMinY(), raster.getWidth(), raster.getHeight()) && bands == null /* TODO: Compare bands with that of raster */) { return raster; } return raster.createWritableChild(rect.x, rect.y, rect.width, rect.height, 0, 0, bands); }
private Raster clipRowToRect( final Raster raster, final Rectangle rect, final int[] bands, final int xSub) { if (rect.contains(raster.getMinX(), 0, raster.getWidth(), 1) && xSub == 1 && bands == null /* TODO: Compare bands with that of raster */) { return raster; } return raster.createChild(rect.x / xSub, 0, rect.width / xSub, 1, 0, 0, bands); }
@Override public Rectangle getBounds() { if (_bounds == null) { _bounds = new Rectangle(); for (int i = 0; i < Screen.getNumberScreens(); i++) { _bounds = _bounds.union(Screen.getBounds(i)); } } return _bounds; }
/** Processes the data and renders it to a component */ public synchronized int process(Buffer buffer) { if (component == null) return BUFFER_PROCESSED_FAILED; Format inf = buffer.getFormat(); if (inf == null) return BUFFER_PROCESSED_FAILED; if (inf != inputFormat || !buffer.getFormat().equals(inputFormat)) { if (setInputFormat(inf) != null) return BUFFER_PROCESSED_FAILED; } Object data = buffer.getData(); if (!(data instanceof int[])) return BUFFER_PROCESSED_FAILED; if (lastBuffer != buffer) { lastBuffer = buffer; newImage(buffer); } sourceImage.newPixels(0, 0, inWidth, inHeight); Graphics g = component.getGraphics(); if (g != null) { if (reqBounds == null) { bounds = component.getBounds(); bounds.x = 0; bounds.y = 0; } else bounds = reqBounds; g.drawImage( destImage, bounds.x, bounds.y, bounds.width, bounds.height, 0, 0, inWidth, inHeight, component); } return BUFFER_PROCESSED_OK; }
private BufferedImage cropScaleGrayscale(Rectangle visibleRect, RenderedImage image) { int minX = image.getMinX(); int minY = image.getMinY(); int width = image.getWidth(); int height = image.getHeight(); Rectangle bounds = new Rectangle(minX, minY, width, height); visibleRect = bounds.intersection(visibleRect); if (bounds.contains(visibleRect)) { ParameterBlock pb = new ParameterBlock(); pb.addSource(image); pb.add((float) visibleRect.x); pb.add((float) visibleRect.y); pb.add((float) visibleRect.width); pb.add((float) visibleRect.height); image = JAI.create("Crop", pb, JAIContext.noCacheHint); } Dimension previewSize = getSize(); if ((visibleRect.width > previewSize.width) || (visibleRect.height > previewSize.height)) { float scale = Math.min( previewSize.width / (float) visibleRect.width, previewSize.height / (float) visibleRect.height); image = ConvolveDescriptor.create(image, Functions.getGaussKernel(.25 / scale), null); ParameterBlock pb = new ParameterBlock(); pb.addSource(image); pb.add(scale); pb.add(scale); image = JAI.create("Scale", pb, JAIContext.noCacheHint); } image = Functions.toColorSpace(image, JAIContext.systemColorSpace, null); if (image.getSampleModel().getDataType() == DataBuffer.TYPE_USHORT) { image = Functions.fromUShortToByte(image, null); } return Functions.toFastBufferedImage(image); }
/** * Method to check that the current position is in the viewing area and if not scroll to center * the current position if possible */ public void checkScroll() { // get the x and y position in pixels int xPos = (int) (colIndex * zoomFactor); int yPos = (int) (rowIndex * zoomFactor); // only do this if the image is larger than normal if (zoomFactor > 1) { // get the rectangle that defines the current view JViewport viewport = scrollPane.getViewport(); Rectangle rect = viewport.getViewRect(); int rectMinX = (int) rect.getX(); int rectWidth = (int) rect.getWidth(); int rectMaxX = rectMinX + rectWidth - 1; int rectMinY = (int) rect.getY(); int rectHeight = (int) rect.getHeight(); int rectMaxY = rectMinY + rectHeight - 1; // get the maximum possible x and y index int macolIndexX = (int) (picture.getWidth() * zoomFactor) - rectWidth - 1; int macolIndexY = (int) (picture.getHeight() * zoomFactor) - rectHeight - 1; // calculate how to position the current position in the middle of the viewing // area int viewX = xPos - (int) (rectWidth / 2); int viewY = yPos - (int) (rectHeight / 2); // reposition the viewX and viewY if outside allowed values if (viewX < 0) viewX = 0; else if (viewX > macolIndexX) viewX = macolIndexX; if (viewY < 0) viewY = 0; else if (viewY > macolIndexY) viewY = macolIndexY; // move the viewport upper left point viewport.scrollRectToVisible(new Rectangle(viewX, viewY, rectWidth, rectHeight)); } }
private void drawScreenFrame(Graphics2D g2d, int scrId) { g2d.setColor(screenFrameColor); g2d.setStroke(strokeScreenFrame); if (screenFrame == null) { screenFrame = Screen.getBounds(scrId); Rectangle ubound = scrOCP.getBounds(); screenFrame.x -= ubound.x; screenFrame.y -= ubound.y; int sw = (int) (strokeScreenFrame.getLineWidth() / 2); screenFrame.x += sw; screenFrame.y += sw; screenFrame.width -= sw * 2; screenFrame.height -= sw * 2; } g2d.draw(screenFrame); }
/** * Writes the <code>shape</code>, <code>coords</code>, <code>href</code>, * <code>nohref</code> Attribute for the specified figure and rectangle. * * @return Returns true, if the rect is inside of the image bounds. */ private boolean writeRectAttributes(IXMLElement elem, SVGFigure f, Rectangle2D.Double rect) { AffineTransform t = TRANSFORM.getClone(f); if (t == null) { t = drawingTransform; } else { t.preConcatenate(drawingTransform); } if ((t.getType() & (AffineTransform.TYPE_UNIFORM_SCALE | AffineTransform.TYPE_TRANSLATION)) == t.getType() ) { Point2D.Double start = new Point2D.Double(rect.x, rect.y); Point2D.Double end = new Point2D.Double(rect.x + rect.width, rect.y + rect.height); t.transform(start, start); t.transform(end, end); Rectangle r = new Rectangle( (int) Math.min(start.x, end.x), (int) Math.min(start.y, end.y), (int) Math.abs(start.x - end.x), (int) Math.abs(start.y - end.y) ); elem.setAttribute("shape", "rect"); elem.setAttribute("coords", r.x + ","+ r.y + ","+ (r.x + r.width) + ","+ (r.y + r.height) ); writeHrefAttribute(elem, f); return bounds.intersects(r); } else { return writePolyAttributes(elem, f, (Shape) rect); } }
@Override public ScreenImage capture(Rectangle rect) { Debug.log(5, "capture: " + rect); BufferedImage ret = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = ret.createGraphics(); for (int i = 0; i < Screen.getNumberScreens(); i++) { Rectangle scrBound = Screen.getBounds(i); if (scrBound.intersects(rect)) { Rectangle inter = scrBound.intersection(rect); Debug.log(5, "scrBound: " + scrBound + ", inter: " + inter); int ix = inter.x, iy = inter.y; inter.x -= scrBound.x; inter.y -= scrBound.y; ScreenImage img = robots[i].captureScreen(inter); g2d.drawImage(img.getImage(), ix - rect.x, iy - rect.y, null); } } g2d.dispose(); return new ScreenImage(rect, ret); }
protected Dimension canEnlarge(int newWidth, int newHeight) { // if ((flags&Event.CTRL_MASK)!=0 || IJ.controlKeyDown()) return null; ImageWindow win = imp.getWindow(); if (win == null) return null; Rectangle r1 = win.getBounds(); Insets insets = win.getInsets(); Point loc = getLocation(); if (loc.x > insets.left + 5 || loc.y > insets.top + 5) { r1.width = newWidth + insets.left + insets.right + 10; r1.height = newHeight + insets.top + insets.bottom + 10; if (win instanceof StackWindow) r1.height += 20; } else { r1.width = r1.width - dstWidth + newWidth + 10; r1.height = r1.height - dstHeight + newHeight + 10; } Rectangle max = win.getMaxWindow(r1.x, r1.y); boolean fitsHorizontally = r1.x + r1.width < max.x + max.width; boolean fitsVertically = r1.y + r1.height < max.y + max.height; if (fitsHorizontally && fitsVertically) return new Dimension(newWidth, newHeight); else if (fitsVertically && newHeight < dstWidth) return new Dimension(dstWidth, newHeight); else if (fitsHorizontally && newWidth < dstHeight) return new Dimension(newWidth, dstHeight); else return null; }
// Graphics2D g=getG();return g==null?null:g.getClipBounds();} public Rectangle getClipBounds(Rectangle r) { Shape s = bufferClip(); if (s == null) return null; r.setBounds(bufferClip().getBounds()); return r; }
@Override protected void paintText( Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) { g.setFont(font); int titleWidth = SwingUtilities.computeStringWidth(metrics, title); int preferredWidth = 0; if (isOneActionButtonEnabled()) { preferredWidth = calculateTabWidth(tabPlacement, tabIndex, metrics) - WIDTHDELTA - 15; if (isCloseEnabled()) preferredWidth -= BUTTONSIZE; if (isMaxEnabled()) preferredWidth -= BUTTONSIZE; } else { preferredWidth = titleWidth; } while (titleWidth > preferredWidth) { if (title.endsWith("...")) title = title.substring(0, title.indexOf("...") - 1).concat("..."); else title = title.substring(0, title.length() - 4).concat("..."); titleWidth = SwingUtilities.computeStringWidth(metrics, title); } textRect.width = titleWidth; View v = getTextViewForTab(tabIndex); if (v != null) { // html v.paint(g, textRect); } else { // plain text int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex); if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) { if (isSelected) g.setColor(TAB_SELECTED_FOREGROUND_COLOR); else { if (this.isTabHighlighted(tabIndex)) { g.setColor(TAB_HIGHLIGHT_FOREGROUND_COLOR); } else g.setColor(tabPane.getForegroundAt(tabIndex)); } BasicGraphicsUtils.drawString( g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); } else { // tab disabled g.setColor(tabPane.getBackgroundAt(tabIndex).brighter()); BasicGraphicsUtils.drawStringUnderlineCharAt( g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); g.setColor(tabPane.getBackgroundAt(tabIndex).darker()); BasicGraphicsUtils.drawStringUnderlineCharAt( g, title, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1); } } }
/** * Gets the template location at which the best match occurs in a rectangle. May return null. * * @param target the image to search * @param searchRect the rectangle to search within the target image * @return the optimized template location at which the best match, if any, is found */ public TPoint getMatchLocation(BufferedImage target, Rectangle searchRect) { wTarget = target.getWidth(); hTarget = target.getHeight(); // determine insets needed to accommodate template int left = wTemplate / 2, right = left; if (wTemplate % 2 > 0) right++; int top = hTemplate / 2, bottom = top; if (hTemplate % 2 > 0) bottom++; // trim search rectangle if necessary searchRect.x = Math.max(left, Math.min(wTarget - right, searchRect.x)); searchRect.y = Math.max(top, Math.min(hTarget - bottom, searchRect.y)); searchRect.width = Math.min(wTarget - searchRect.x - right, searchRect.width); searchRect.height = Math.min(hTarget - searchRect.y - bottom, searchRect.height); if (searchRect.width <= 0 || searchRect.height <= 0) { peakHeight = Double.NaN; peakWidth = Double.NaN; return null; } // set up test pixels to search (rectangle plus template) int xMin = Math.max(0, searchRect.x - left); int xMax = Math.min(wTarget, searchRect.x + searchRect.width + right); int yMin = Math.max(0, searchRect.y - top); int yMax = Math.min(hTarget, searchRect.y + searchRect.height + bottom); wTest = xMax - xMin; hTest = yMax - yMin; if (target.getType() != BufferedImage.TYPE_INT_RGB) { BufferedImage image = new BufferedImage(wTarget, hTarget, BufferedImage.TYPE_INT_RGB); image.createGraphics().drawImage(target, 0, 0, null); target = image; } targetPixels = new int[wTest * hTest]; target.getRaster().getDataElements(xMin, yMin, wTest, hTest, targetPixels); // find the rectangle point with the minimum difference double matchDiff = largeNumber; // larger than typical differences int xMatch = 0, yMatch = 0; double avgDiff = 0; for (int x = 0; x <= searchRect.width; x++) { for (int y = 0; y <= searchRect.height; y++) { double diff = getDifferenceAtTestPoint(x, y); avgDiff += diff; if (diff < matchDiff) { matchDiff = diff; xMatch = x; yMatch = y; } } } avgDiff /= (searchRect.width * searchRect.height); peakHeight = avgDiff / matchDiff - 1; peakWidth = Double.NaN; double dx = 0, dy = 0; // if match is not exact, fit a Gaussian and find peak if (!Double.isInfinite(peakHeight)) { // fill data arrays xValues[1] = yValues[1] = peakHeight; for (int i = -1; i < 2; i++) { if (i == 0) continue; double diff = getDifferenceAtTestPoint(xMatch + i, yMatch); xValues[i + 1] = avgDiff / diff - 1; diff = getDifferenceAtTestPoint(xMatch, yMatch + i); yValues[i + 1] = avgDiff / diff - 1; } // estimate peakHeight = peak of gaussian // estimate offset dx of gaussian double pull = 1 / (xValues[1] - xValues[0]); double push = 1 / (xValues[1] - xValues[2]); if (Double.isNaN(pull)) pull = LARGE_NUMBER; if (Double.isNaN(push)) push = LARGE_NUMBER; dx = 0.6 * (push - pull) / (push + pull); // estimate width wx of gaussian double ratio = dx > 0 ? peakHeight / xValues[0] : peakHeight / xValues[2]; double wx = dx > 0 ? dx + 1 : dx - 1; wx = wx * wx / Math.log(ratio); // estimate offset dy of gaussian pull = 1 / (yValues[1] - yValues[0]); push = 1 / (yValues[1] - yValues[2]); if (Double.isNaN(pull)) pull = LARGE_NUMBER; if (Double.isNaN(push)) push = LARGE_NUMBER; dy = 0.6 * (push - pull) / (push + pull); // estimate width wy of gaussian ratio = dy > 0 ? peakHeight / yValues[0] : peakHeight / yValues[2]; double wy = dy > 0 ? dy + 1 : dy - 1; wy = wy * wy / Math.log(ratio); // set x parameters and fit to x data dataset.clear(); dataset.append(pixelOffsets, xValues); double rmsDev = 1; for (int k = 0; k < 3; k++) { double c = k == 0 ? wx : k == 1 ? wx / 3 : wx * 3; f.setParameterValue(0, peakHeight); f.setParameterValue(1, dx); f.setParameterValue(2, c); rmsDev = fitter.fit(f); if (rmsDev < 0.01) { // fitter succeeded (3-point fit should be exact) dx = f.getParameterValue(1); peakWidth = f.getParameterValue(2); break; } } if (!Double.isNaN(peakWidth)) { // set y parameters and fit to y data dataset.clear(); dataset.append(pixelOffsets, yValues); for (int k = 0; k < 3; k++) { double c = k == 0 ? wy : k == 1 ? wy / 3 : wy * 3; f.setParameterValue(0, peakHeight); f.setParameterValue(1, dx); f.setParameterValue(2, c); rmsDev = fitter.fit(f); if (rmsDev < 0.01) { // fitter succeeded (3-point fit should be exact) dy = f.getParameterValue(1); peakWidth = (peakWidth + f.getParameterValue(2)) / 2; break; } } if (rmsDev > 0.01) peakWidth = Double.NaN; } } double xImage = xMatch + searchRect.x - left - trimLeft + dx; double yImage = yMatch + searchRect.y - top - trimTop + dy; return new TPoint(xImage, yImage); }
/** * This returns the full current drawing area * * @return full drawing area */ public Rectangle getClipBounds(Rectangle r) { r.setBounds(0, 0, m_extent.width, m_extent.height); return r; }
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException { checkIndex(imageIndex); readHeader(); if (iis == null) throw new IllegalStateException("input is null"); BufferedImage img; clearAbortRequest(); processImageStarted(imageIndex); if (param == null) param = getDefaultReadParam(); sourceRegion = new Rectangle(0, 0, 0, 0); destinationRegion = new Rectangle(0, 0, 0, 0); computeRegions( param, this.width, this.height, param.getDestination(), sourceRegion, destinationRegion); scaleX = param.getSourceXSubsampling(); scaleY = param.getSourceYSubsampling(); // If the destination band is set used it sourceBands = param.getSourceBands(); destBands = param.getDestinationBands(); seleBand = (sourceBands != null) && (destBands != null); noTransform = destinationRegion.equals(new Rectangle(0, 0, width, height)) || seleBand; if (!seleBand) { sourceBands = new int[colorPlanes]; destBands = new int[colorPlanes]; for (int i = 0; i < colorPlanes; i++) destBands[i] = sourceBands[i] = i; } // If the destination is provided, then use it. Otherwise, create new one bi = param.getDestination(); // Get the image data. WritableRaster raster = null; if (bi == null) { if (sampleModel != null && colorModel != null) { sampleModel = sampleModel.createCompatibleSampleModel( destinationRegion.width + destinationRegion.x, destinationRegion.height + destinationRegion.y); if (seleBand) sampleModel = sampleModel.createSubsetSampleModel(sourceBands); raster = Raster.createWritableRaster(sampleModel, new Point(0, 0)); bi = new BufferedImage(colorModel, raster, false, null); } } else { raster = bi.getWritableTile(0, 0); sampleModel = bi.getSampleModel(); colorModel = bi.getColorModel(); noTransform &= destinationRegion.equals(raster.getBounds()); } byte bdata[] = null; // buffer for byte data if (sampleModel.getDataType() == DataBuffer.TYPE_BYTE) bdata = (byte[]) ((DataBufferByte) raster.getDataBuffer()).getData(); readImage(bdata); if (abortRequested()) processReadAborted(); else processImageComplete(); return bi; }
/** * Gets the template location at which the best match occurs in a rectangle and along a line. May * return null. * * @param target the image to search * @param searchRect the rectangle to search within the target image * @param x0 the x-component of a point on the line * @param y0 the y-component of a point on the line * @param slope the slope of the line * @param spread the spread of the line (line width = 1+2*spread) * @return the optimized template location of the best match, if any */ public TPoint getMatchLocation( BufferedImage target, Rectangle searchRect, double x0, double y0, double theta, int spread) { wTarget = target.getWidth(); hTarget = target.getHeight(); // determine insets needed to accommodate template int left = wTemplate / 2, right = left; if (wTemplate % 2 > 0) right++; int top = hTemplate / 2, bottom = top; if (hTemplate % 2 > 0) bottom++; // trim search rectangle if necessary searchRect.x = Math.max(left, Math.min(wTarget - right, searchRect.x)); searchRect.y = Math.max(top, Math.min(hTarget - bottom, searchRect.y)); searchRect.width = Math.min(wTarget - searchRect.x - right, searchRect.width); searchRect.height = Math.min(hTarget - searchRect.y - bottom, searchRect.height); if (searchRect.width <= 0 || searchRect.height <= 0) { peakHeight = Double.NaN; peakWidth = Double.NaN; return null; } // set up test pixels to search (rectangle plus template) int xMin = Math.max(0, searchRect.x - left); int xMax = Math.min(wTarget, searchRect.x + searchRect.width + right); int yMin = Math.max(0, searchRect.y - top); int yMax = Math.min(hTarget, searchRect.y + searchRect.height + bottom); wTest = xMax - xMin; hTest = yMax - yMin; if (target.getType() != BufferedImage.TYPE_INT_RGB) { BufferedImage image = new BufferedImage(wTarget, hTarget, BufferedImage.TYPE_INT_RGB); image.createGraphics().drawImage(target, 0, 0, null); target = image; } targetPixels = new int[wTest * hTest]; target.getRaster().getDataElements(xMin, yMin, wTest, hTest, targetPixels); // get the points to search along the line ArrayList<Point2D> searchPts = getSearchPoints(searchRect, x0, y0, theta); if (searchPts == null) { peakHeight = Double.NaN; peakWidth = Double.NaN; return null; } // collect differences in a map as they are measured HashMap<Point2D, Double> diffs = new HashMap<Point2D, Double>(); // find the point with the minimum difference from template double matchDiff = largeNumber; // larger than typical differences int xMatch = 0, yMatch = 0; double avgDiff = 0; Point2D matchPt = null; for (Point2D pt : searchPts) { int x = (int) pt.getX(); int y = (int) pt.getY(); double diff = getDifferenceAtTestPoint(x, y); diffs.put(pt, diff); avgDiff += diff; if (diff < matchDiff) { matchDiff = diff; xMatch = x; yMatch = y; matchPt = pt; } } avgDiff /= searchPts.size(); peakHeight = avgDiff / matchDiff - 1; peakWidth = Double.NaN; double dl = 0; int matchIndex = searchPts.indexOf(matchPt); // if match is not exact, fit a Gaussian and find peak if (!Double.isInfinite(peakHeight) && matchIndex > 0 && matchIndex < searchPts.size() - 1) { // fill data arrays Point2D pt = searchPts.get(matchIndex - 1); double diff = diffs.get(pt); xValues[0] = -pt.distance(matchPt); yValues[0] = avgDiff / diff - 1; xValues[1] = 0; yValues[1] = peakHeight; pt = searchPts.get(matchIndex + 1); diff = diffs.get(pt); xValues[2] = pt.distance(matchPt); yValues[2] = avgDiff / diff - 1; // determine approximate offset (dl) and width (w) values double pull = -xValues[0] / (yValues[1] - yValues[0]); double push = xValues[2] / (yValues[1] - yValues[2]); if (Double.isNaN(pull)) pull = LARGE_NUMBER; if (Double.isNaN(push)) push = LARGE_NUMBER; dl = 0.3 * (xValues[2] - xValues[0]) * (push - pull) / (push + pull); double ratio = dl > 0 ? peakHeight / yValues[0] : peakHeight / yValues[2]; double w = dl > 0 ? dl - xValues[0] : dl - xValues[2]; w = w * w / Math.log(ratio); // set parameters and fit to x data dataset.clear(); dataset.append(xValues, yValues); double rmsDev = 1; for (int k = 0; k < 3; k++) { double c = k == 0 ? w : k == 1 ? w / 3 : w * 3; f.setParameterValue(0, peakHeight); f.setParameterValue(1, dl); f.setParameterValue(2, c); rmsDev = fitter.fit(f); if (rmsDev < 0.01) { // fitter succeeded (3-point fit should be exact) dl = f.getParameterValue(1); peakWidth = f.getParameterValue(2); break; } } } double dx = dl * Math.cos(theta); double dy = dl * Math.sin(theta); double xImage = xMatch + searchRect.x - left - trimLeft + dx; double yImage = yMatch + searchRect.y - top - trimTop + dy; return new TPoint(xImage, yImage); }
/** * Paint the image onto a Graphics object. The painting is performed tile-by-tile, and includes a * grey region covering the unused portion of image tiles as well as the general background. At * this point the image must be byte data. */ public synchronized void paintComponent(Graphics g) { Graphics2D g2D = null; if (g instanceof Graphics2D) { g2D = (Graphics2D) g; } else { return; } // if source is null, it's just a component if (source == null) { g2D.setColor(getBackground()); g2D.fillRect(0, 0, componentWidth, componentHeight); return; } int transX = -originX; int transY = -originY; // Get the clipping rectangle and translate it into image coordinates. Rectangle clipBounds = g.getClipBounds(); if (clipBounds == null) { clipBounds = new Rectangle(0, 0, componentWidth, componentHeight); } // clear the background (clip it) [minimal optimization here] if (transX > 0 || transY > 0 || transX < (componentWidth - source.getWidth()) || transY < (componentHeight - source.getHeight())) { g2D.setColor(getBackground()); g2D.fillRect(0, 0, componentWidth, componentHeight); } clipBounds.translate(-transX, -transY); // Determine the extent of the clipping region in tile coordinates. int txmin, txmax, tymin, tymax; int ti, tj; txmin = XtoTileX(clipBounds.x); txmin = Math.max(txmin, minTileX); txmin = Math.min(txmin, maxTileX); txmax = XtoTileX(clipBounds.x + clipBounds.width - 1); txmax = Math.max(txmax, minTileX); txmax = Math.min(txmax, maxTileX); tymin = YtoTileY(clipBounds.y); tymin = Math.max(tymin, minTileY); tymin = Math.min(tymin, maxTileY); tymax = YtoTileY(clipBounds.y + clipBounds.height - 1); tymax = Math.max(tymax, minTileY); tymax = Math.min(tymax, maxTileY); Insets insets = getInsets(); // Loop over tiles within the clipping region for (tj = tymin; tj <= tymax; tj++) { for (ti = txmin; ti <= txmax; ti++) { int tx = TileXtoX(ti); int ty = TileYtoY(tj); Raster tile = source.getTile(ti, tj); if (tile != null) { DataBuffer dataBuffer = tile.getDataBuffer(); WritableRaster wr = tile.createWritableRaster(sampleModel, dataBuffer, null); BufferedImage bi = new BufferedImage(colorModel, wr, colorModel.isAlphaPremultiplied(), null); // correctly handles band offsets if (brightnessEnabled == true) { SampleModel sm = sampleModel.createCompatibleSampleModel(tile.getWidth(), tile.getHeight()); WritableRaster raster = RasterFactory.createWritableRaster(sm, null); BufferedImage bimg = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null); // don't move this code ByteLookupTable lutTable = new ByteLookupTable(0, lutData); LookupOp lookup = new LookupOp(lutTable, null); lookup.filter(bi, bimg); g2D.drawImage(bimg, biop, tx + transX + insets.left, ty + transY + insets.top); } else { AffineTransform transform; transform = AffineTransform.getTranslateInstance( tx + transX + insets.left, ty + transY + insets.top); g2D.drawRenderedImage(bi, transform); } } } } }
public void setRGeom(int x1, int y1, int x2, int y2) { rect.x = Math.min(x1, x2) - offset.x; rect.y = Math.min(y1, y2) - offset.y; rect.width = Math.abs(x2 - x1); rect.height = Math.abs(y2 - y1); }