public static BufferedImage rotateImage(BufferedImage image, double theta) { int degrees = (int) Math.abs(Math.toDegrees(theta)); double xCenter = image.getWidth() / 2; double yCenter = image.getHeight() / 2; AffineTransform rotateTransform = AffineTransform.getRotateInstance(-theta, xCenter, yCenter); // Translation adjustments so image still centered after rotate width/height changes if (image.getHeight() != image.getWidth() && degrees != 180 && degrees != 0) { Point2D origin = new Point2D.Double(0.0, 0.0); origin = rotateTransform.transform(origin, null); double yTranslate = origin.getY(); Point2D yMax = new Point2D.Double(0, image.getHeight()); yMax = rotateTransform.transform(yMax, null); double xTranslate = yMax.getX(); AffineTransform translationAdjustment = AffineTransform.getTranslateInstance(-xTranslate, -yTranslate); rotateTransform.preConcatenate(translationAdjustment); } AffineTransformOp op = new AffineTransformOp(rotateTransform, AffineTransformOp.TYPE_BILINEAR); // Have to recopy image because of JDK bug #4723021, AffineTransformationOp throwing exception // sometimes image = copyImage(image, BufferedImage.TYPE_INT_ARGB); // Need to create filter dest image ourselves since AffineTransformOp's own dest image creation // throws exceptions in some cases. Rectangle bounds = op.getBounds2D(image).getBounds(); BufferedImage finalImage = new BufferedImage( (int) bounds.getWidth(), (int) bounds.getHeight(), BufferedImage.TYPE_INT_ARGB); return op.filter(image, finalImage); }
public static BufferedImage doFilter(BufferedImage img) { BufferedImage img2 = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // img.getSubimage(0, 0, img.getWidth(), img.getHeight()); for (int i = 0; i < img2.getWidth(); i++) { for (int j = 0; j < img2.getHeight(); j++) { img2.setRGB(i, j, img.getRGB(i, j)); // img2.setRGB(i, j, Color.BLACK.getRGB()); } } int a = 32; for (int j = 0; j < img2.getHeight(); j++) { for (int i = 0; i < img2.getWidth(); i++) { int c = img.getRGB(i, j); Color c2 = new Color(c); Error er = new Error(); er.r = (int) (a * matrix[i % 2][j % 2]); er.g = er.r; er.b = er.r; c2 = addToPixel(c2, er, 1); Color c3 = getClosestPixel(c2); setPixel(img2, i, j, c3); // oldpixel := pixel[x][y] + threshold_map_4x4[x mod 4][y mod 4] // newpixel := find_closest_palette_color(oldpixel) // pixel[x][y] := newpixel } } return img2; }
private static ImageElement fetchImageProperties( final BufferedImage source, final ImageType imageType, final String id, final Date modifiedDate, final String mimeType) throws NullPointerException, IOException { if (verifyNotNull(source)) { ImageElement image = new ImageElement(); image.setBitDepth( verifyNotNull(source.getColorModel().getPixelSize()) ? source.getColorModel().getPixelSize() : 0); image.setHeight(verifyNotNull(source.getHeight()) ? source.getHeight() : 0); image.setWidth(verifyNotNull(source.getWidth()) ? source.getWidth() : 0); image.setSizeInBytes(determineSizeOfBufferedImage(source, imageType.toString())); image.setCreated(new Date(System.currentTimeMillis())); image.setTransparent( determineTransparencyType(source.getGraphics().getColor().getTransparency())); if (verifyNotNull(modifiedDate)) image.setModified(modifiedDate); image.setId((verifyNotNull(id) ? id : "")); image.setFontType( verifyNotNull(source.getGraphics().getFont()) ? source.getGraphics().getFont() : new Font("Default", 0, 0)); image.setMediaType(MediaType.Missing); return image; } throw new NullPointerException(E_OBJECT_WAS_NULL); }
public ImageRadioButton(String imageURL) { try { normalImage = cleanImageEdges(ImageIO.read(getClass().getResource(imageURL))); shift = normalImage.getWidth() / 20; shift = shift < 2 ? 2 : shift; selectedImage = addSelectionBorder(normalImage, shift); setSize(selectedImage.getWidth(), selectedImage.getHeight()); } catch (Exception e) { e.printStackTrace(); } final ImageRadioButton self = this; addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { setSelected(true); if (otherButtons != null) { for (ImageRadioButton b : otherButtons) { if (b != self) { b.setSelected(false); } } } if (callback != null) { callback.run(); } } }); }
/** * 将照片logo添加到二维码中间 * * @param image 生成的二维码照片对象 * @param imagePath 照片保存路径 * @param logoPath logo照片路径 * @param formate 照片格式 */ public static void overlapImage( BufferedImage image, String formate, String imagePath, String logoPath, MatrixToLogoImageConfig logoConfig) { try { BufferedImage logo = ImageIO.read(new File(logoPath)); Graphics2D g = image.createGraphics(); // 考虑到logo照片贴到二维码中,建议大小不要超过二维码的1/5; int width = image.getWidth() / logoConfig.getLogoPart(); int height = image.getHeight() / logoConfig.getLogoPart(); // logo起始位置,此目的是为logo居中显示 int x = (image.getWidth() - width) / 2; int y = (image.getHeight() - height) / 2; // 绘制图 g.drawImage(logo, x, y, width, height, null); // 给logo画边框 // 构造一个具有指定线条宽度以及 cap 和 join 风格的默认值的实心 BasicStroke g.setStroke(new BasicStroke(logoConfig.getBorder())); g.setColor(logoConfig.getBorderColor()); g.drawRect(x, y, width, height); g.dispose(); // 写入logo照片到二维码 ImageIO.write(image, formate, new File(imagePath)); } catch (Exception e) { e.printStackTrace(); } }
public AnimatedTextureFX(int targetTextureID, BufferedImage image, int scale) { super(targetTextureID); file = image; int frames = file.getHeight() / file.getWidth(); int frameSize = file.getWidth(); unStitch(frames, frameSize); }
public void loadWorldFromImage(String filepath) { try { BufferedImage image = ImageIO.read(World.class.getResourceAsStream(filepath)); width = image.getWidth(); height = image.getHeight(); data.clear(); for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { int rgb = image.getRGB(x, y); int red = (rgb >> 16) & 0x000000FF; int green = (rgb >> 8) & 0x000000FF; int blue = (rgb >> 0) & 0x000000FF; String colour = red + "-" + green + "-" + blue; switch (colour) { case "0-102-0": data.add(0); break; case "102-102-102": data.add(1); break; } } } } catch (IOException e) { e.printStackTrace(); } }
public static Image getScaledInstance(File file) throws Exception { srcBImage = javax.imageio.ImageIO.read(file); if (srcBImage.getWidth() > srcBImage.getHeight()) { width = 100; height = (srcBImage.getHeight() * 100) / srcBImage.getWidth(); } else { height = 100; width = (srcBImage.getWidth() * 100) / srcBImage.getHeight(); } dest = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); dest2 = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); g = dest.getGraphics(); g.setColor(Color.white); g.fillRect(0, 0, 100, 100); g.drawImage(srcBImage, 0, 0, width, height, null); g.dispose(); srcBImage = null; blurOperator.filter(dest, dest2); return dest2; }
public void drawPixelatedImage(BufferedImage img, int locationX, int locationY) { if (isDrawingPixelatedImages()) { BufferedImage bi = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) bi.getGraphics(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, img.getWidth(), img.getHeight()); g2.drawImage(img, 0, 0, observer); g2.dispose(); for (int x = 0; x < bi.getWidth(observer); x++) { for (int y = 0; y < bi.getHeight(observer); y++) { int rgb = bi.getRGB(x, y); gc.setColor(new Color(rgb)); gc.setStroke(new BasicStroke(1.0f)); gc.drawLine( locationX + xOffset + x, locationY + yOffset + y, locationX + xOffset + x, locationY + yOffset + y); // gc.drawLine(locationX+xOffset+x, locationY+yOffset+y, // locationX+xOffset+x+1, locationY+yOffset+y); // gc.drawLine(locationX+xOffset+x, locationY+yOffset+y+1, // locationX+xOffset+x+1, locationY+yOffset+y+1); // gc.fillRect(locationX+xOffset+x, locationY+yOffset+y, 1, 1); } } } else { while (!gc.drawImage(img, locationX, locationY, observer)) ; } }
public synchronized void paint(Graphics g) { if (needToStartThread) { totalDrawTime = 0; counter = 0; needToStartThread = false; startThread(beginAngle, endAngle); if (firstImage == null) { firstImage = createImageFromComponent(component1); } if (secondImage == null) { secondImage = createImageFromComponent(component2); } } if (firstImage == null || secondImage == null) return; Graphics2D g2d = (Graphics2D) g; int ww = firstImage.getWidth(); int hh = firstImage.getHeight(); { BufferedImage currImage = null; int[] currPixels = null; int w = firstImage.getWidth(); int offset = (int) (w * angle / 180); if (offset < 0) offset = 0; if (offset > w) offset = w; long beforeDraw = System.currentTimeMillis(); g2d.drawImage(firstImage, null, 0, 0); g2d.drawImage(secondImage, null, w - offset, 0); totalDrawTime += (System.currentTimeMillis() - beforeDraw); counter++; } }
private void pickHeliImage() { String image = null; if (this.getXSpeed() > 0) image = "heli_right"; else if (this.getXSpeed() < 0) image = "heli_left"; String lastImage = this.helicopter.getCurrentImageName(); if (image == null) if (lastImage.equals("heli_left") || lastImage.equals("heli_still_left")) image = "heli_still_left"; else image = "heli_still_right"; if (!image.equals(lastImage)) { if (lastImage.equals("heli_still_left") || lastImage.equals("heli_still_right") || image.equals("heli_still_right") || image.equals("heli_still_left")) { BufferedImage before = this.helicopter.getImageGroupHolder().getImage(lastImage); BufferedImage after = this.helicopter.getImageGroupHolder().getImage(image); this.moveBy( (before.getWidth() - after.getWidth()) / 2, (before.getHeight() - after.getHeight()) / 2); } this.helicopter.setCurrentImage(image); this.clearHitboxes(); this.addHitboxes(HeliSprite.hitboxes.get(image)); } }
public RigidBodyTransform detect(BufferedImage image) { if (intrinsicParameters == null) setDefaultIntrinsicParameter(image.getHeight(), image.getWidth(), Math.PI / 4); ImageFloat32 gray = new ImageFloat32(image.getWidth(), image.getHeight()); ConvertBufferedImage.convertFrom(image, gray); detector.setIntrinsic(intrinsicParameters); detector.detect(gray); // display the results if (detector.totalFound() == 0) { return null; } else { int closestIndex = -1; double closestDistance = Double.MAX_VALUE; Se3_F64 targetToSensor = new Se3_F64(); for (int i = 0; i < detector.totalFound(); i++) { detector.getFiducialToCamera(i, targetToSensor); double dist = targetToSensor.getT().norm(); if (dist < closestDistance) { closestIndex = i; closestDistance = dist; } } detector.getFiducialToCamera(closestIndex, targetToSensor); Vector3D_F64 translation = targetToSensor.getT(); Matrix3d rotation = new Matrix3d(targetToSensor.getR().data); RigidBodyTransform transform = new RigidBodyTransform( rotation, new Vector3d(translation.x, translation.y, translation.z)); return transform; } }
public static Icon getFixedBoundIcon(String filePath, int height, int width) throws Exception { double Ratio = 0.0; // 缩放比例 File F = new File(filePath); if (!F.isFile()) throw new Exception(F + " is not image file error in getFixedBoundIcon! "); Icon ret = new ImageIcon(filePath); BufferedImage Bi = ImageIO.read(F); if ((Bi.getHeight() > height) || (Bi.getWidth() > width)) { if (Bi.getHeight() > Bi.getWidth()) { Ratio = (new Integer(height)).doubleValue() / Bi.getHeight(); } else { Ratio = (new Integer(width)).doubleValue() / Bi.getWidth(); } int lastLength = filePath.lastIndexOf(" . "); String subFilePath = filePath.substring(0, lastLength); String fileType = filePath.substring(lastLength); File zoomFile = new File(subFilePath + " _ " + height + " _ " + width + fileType); Image Itemp = Bi.getScaledInstance(width, height, Bi.SCALE_SMOOTH); AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null); Itemp = op.filter(Bi, null); try { ImageIO.write((BufferedImage) Itemp, " jpg ", zoomFile); ret = new ImageIcon(zoomFile.getPath()); } catch (Exception ex) { System.out.println(" ######## here error : " + ex); } } return ret; }
/** * 画像のリサイズ * * @param srcImage 元画像 * @param destWidth 横幅 * @param destHeight 高さ * @return */ public BufferedImage rescaleImage(BufferedImage srcImage, int dstWidth, int dstHeight) { BufferedImage dstImage = null; if (srcImage.getColorModel() instanceof IndexColorModel) { dstImage = new BufferedImage( dstWidth, dstHeight, srcImage.getType(), (IndexColorModel) srcImage.getColorModel()); } else { if (srcImage.getType() == 0) { dstImage = new BufferedImage(dstWidth, dstHeight, BufferedImage.TYPE_4BYTE_ABGR_PRE); } else { dstImage = new BufferedImage(dstWidth, dstHeight, srcImage.getType()); } } double x = (double) dstWidth / srcImage.getWidth(); double y = (double) dstHeight / srcImage.getHeight(); AffineTransform af = AffineTransform.getScaleInstance(x, y); if (dstImage.getColorModel().hasAlpha() && dstImage.getColorModel() instanceof IndexColorModel) { int pixel = ((IndexColorModel) dstImage.getColorModel()).getTransparentPixel(); for (int i = 0; i < dstImage.getWidth(); ++i) { for (int j = 0; j < dstImage.getHeight(); ++j) { dstImage.setRGB(i, j, pixel); } } } Graphics2D g2 = (Graphics2D) dstImage.createGraphics(); g2.drawImage(srcImage, af, null); g2.dispose(); return dstImage; }
private BufferedImage windowMonochrome( ImageListViewCell displayedCell, BufferedImage srcImg, float windowLocation, float windowWidth) { BufferedImage destImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_INT_RGB); boolean isSigned = false; int minValue = 0; { // hack: try to determine signedness and minValue from DICOM metadata if available -- // the BufferedImage's metadata don't contain that information reliably. // Only works for some special cases ImageListViewModelElement elt = displayedCell.getDisplayedModelElement(); if (elt instanceof DicomImageListViewModelElement) { DicomImageListViewModelElement delt = (DicomImageListViewModelElement) elt; DicomObject imgMetadata = delt.getDicomImageMetaData(); int bitsAllocated = imgMetadata.getInt(Tag.BitsAllocated); isSigned = (1 == imgMetadata.getInt(Tag.PixelRepresentation)); if (isSigned && (bitsAllocated > 0)) { minValue = -(1 << (bitsAllocated - 1)); } } } final int windowedImageGrayscalesCount = 256; // for BufferedImage.TYPE_INT_RGB float scale = windowedImageGrayscalesCount / windowWidth; float offset = (windowWidth / 2 - windowLocation) * scale; if (!(srcImg.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY)) { throw new IllegalArgumentException("source image must be grayscales"); } Raster srcRaster = srcImg.getRaster(); if (srcRaster.getNumBands() != 1) { throw new IllegalArgumentException( "grayscale source image must have one color band, but has " + srcRaster.getNumBands() + "??"); } WritableRaster resultRaster = destImg.getRaster(); for (int x = 0; x < srcImg.getWidth(); x++) { for (int y = 0; y < srcImg.getHeight(); y++) { int srcGrayValue = srcRaster.getSample(x, y, 0); if (isSigned) { srcGrayValue = (int) (short) srcGrayValue; // will only work for 16-bit signed... } float destGrayValue = scale * srcGrayValue + offset; // clamp if (destGrayValue < 0) { destGrayValue = 0; } else if (destGrayValue >= windowedImageGrayscalesCount) { destGrayValue = windowedImageGrayscalesCount - 1; } resultRaster.setSample(x, y, 0, destGrayValue); resultRaster.setSample(x, y, 1, destGrayValue); resultRaster.setSample(x, y, 2, destGrayValue); } } return destImg; }
/** * Gets the color of a pixel. * * @param i the pixel index * @return the color at pixel i */ public Color getColorAt(int i) { if (image == null || i < 0 || i >= pixels()) { throw new IndexOutOfBoundsException("" + i); } else { return getColorAt(i % image.getWidth(), i / image.getWidth()); } }
private BufferedImage windowRGB(BufferedImage srcImg, float windowLocation, float windowWidth) { BufferedImage destImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_INT_RGB); final int windowedImageBandValuesCount = 256; // for BufferedImage.TYPE_INT_RGB float scale = windowedImageBandValuesCount / windowWidth; float offset = (windowWidth / 2 - windowLocation) * scale; if (!srcImg.getColorModel().getColorSpace().isCS_sRGB()) { throw new IllegalArgumentException("source image must be RGB"); } Raster srcRaster = srcImg.getRaster(); if (srcRaster.getNumBands() != 3) { throw new IllegalArgumentException( "RGB source image must have three color bands, but has " + srcRaster.getNumBands() + "??"); } WritableRaster resultRaster = destImg.getRaster(); for (int x = 0; x < srcImg.getWidth(); x++) { for (int y = 0; y < srcImg.getHeight(); y++) { for (int band = 0; band < 3; band++) { int srcGrayValue = srcRaster.getSample(x, y, band); float destGrayValue = scale * srcGrayValue + offset; // clamp if (destGrayValue < 0) { destGrayValue = 0; } else if (destGrayValue >= windowedImageBandValuesCount) { destGrayValue = windowedImageBandValuesCount - 1; } resultRaster.setSample(x, y, band, destGrayValue); } } } return destImg; }
/** * Sets the color of a pixel. * * @param i the pixel index * @param color the new color for the pixel */ public void setColorAt(int i, Color color) { if (image == null || i < 0 || i >= pixels()) { throw new IndexOutOfBoundsException("" + i); } else { setColorAt(i % image.getWidth(), i / image.getWidth(), color); } }
@Override public void animate() { if (atlas.size() == 0) { return; } BufferedImage image = atlas.get(index); int width = image.getWidth(); int height = image.getHeight(); int[] pixels = new int[width * height]; image.getRGB(0, 0, width, height, pixels, 0, width); textureData = new byte[width * height * 4]; scaling = file.getWidth() / 16; for (int pixel = 0; pixel < pixels.length; pixel++) { int alpha = pixels[pixel] >>> 24; int red = pixels[pixel] >> 16 & 0xFF; int green = pixels[pixel] >> 8 & 0xFF; int blue = pixels[pixel] & 0xFF; int i = pixel << 2; textureData[i] = (byte) red; textureData[i + 1] = (byte) green; textureData[i + 2] = (byte) blue; textureData[i + 3] = (byte) alpha; } index++; if (index >= atlas.size()) { index = 0; } }
/** * Verifies that the specified images match. * * @param expected the expected image to check against * @param actual the actual image */ private static void assertEqual(BufferedImage expected, BufferedImage actual) { int w = expected.getWidth(); int h = expected.getHeight(); Assert.assertEquals("width", w, actual.getWidth()); Assert.assertEquals("height", h, actual.getHeight()); int[] expectedPixels = new int[w * h]; expected.getRGB(0, 0, w, h, expectedPixels, 0, w); int[] actualPixels = new int[w * h]; actual.getRGB(0, 0, w, h, actualPixels, 0, w); for (int i = 0; i < expectedPixels.length; i++) { int expectedPixel = expectedPixels[i]; int actualPixel = actualPixels[i]; if (expectedPixel != actualPixel) { int x = i % w; int y = i / w; throw new ComparisonFailure( "pixel at " + x + ", " + y, toHexString(expectedPixel), toHexString(actualPixel)); } } }
// TODO currently allows for collisions if same name & different filetype public void loadImage(String path) { BufferedImage readImage = null; try { readImage = ImageIO.read(new File("images/" + path)); } catch (IOException e) { e.printStackTrace(); } if (readImage != null) { BufferedImage aImages[] = new BufferedImage[8]; BufferedImage image = new BufferedImage( readImage.getWidth(), readImage.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); g.drawImage(readImage, 0, 0, null); for (int i = 0; i < 8; i++) { AffineTransform trans = new AffineTransform(); trans.translate(image.getWidth() / 2, image.getHeight() / 2); trans.rotate(Math.PI * i / 4.0); trans.translate(-image.getWidth() / 2, -image.getHeight() / 2); AffineTransformOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_BILINEAR); aImages[i] = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); op.filter(image, aImages[i]); } images.add( new Asset( path.substring(0, path.length() - 4), aImages)); // assumes standard 3 letter postfix } }
/* * create QR code with overlay */ public static void createQRCode( String qrCodeData, String outputFilePath, String overlayFilePath, String charset, Map<EncodeHintType, ErrorCorrectionLevel> hintMap, int qrCodeheight, int qrCodewidth) throws WriterException, IOException { // create QR code <BufferedImage> QRCodeWriter qrWriter = new QRCodeWriter(); BitMatrix matrix = qrWriter.encode(qrCodeData, BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight, hintMap); BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix); // read overlay image BufferedImage overlay = ImageIO.read(new File(overlayFilePath)); // Draw the new image int deltaHeight = image.getHeight() - overlay.getHeight(); int deltaWidth = image.getWidth() - overlay.getWidth(); BufferedImage combined = new BufferedImage(qrCodeheight, qrCodewidth, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) combined.getGraphics(); g.drawImage(image, 0, 0, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)); g.drawImage(overlay, (int) Math.round(deltaWidth / 2), (int) Math.round(deltaHeight / 2), null); ImageIO.write(combined, "PNG", new File(outputFilePath)); }
public static void main(String[] args) { try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); File input = new File("traffic_signal.jpg"); BufferedImage image = ImageIO.read(input); byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3); mat.put(0, 0, data); Mat mat1 = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1); Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY); byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int) (mat1.elemSize())]; mat1.get(0, 0, data1); BufferedImage image1 = new BufferedImage(mat1.cols(), mat1.rows(), BufferedImage.TYPE_BYTE_GRAY); image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1); File ouptut = new File("output\\grayscale_" + new Date().getTime() + ".jpg"); ImageIO.write(image1, "jpg", ouptut); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
public void process(BufferedImage input) { setInputImage(input); image.reshape(input.getWidth(), input.getHeight()); transform.reshape(input.getWidth(), input.getHeight()); magnitude.reshape(input.getWidth(), input.getHeight()); phase.reshape(input.getWidth(), input.getHeight()); ConvertBufferedImage.convertFrom(input, image, true); fft.forward(image, transform); GDiscreteFourierTransformOps.shiftZeroFrequency(transform, true); GDiscreteFourierTransformOps.magnitude(transform, magnitude); GDiscreteFourierTransformOps.phase(transform, phase); // Convert it to a log scale for visibility GPixelMath.log(magnitude, magnitude); SwingUtilities.invokeLater( new Runnable() { public void run() { setPreferredSize(new Dimension(image.width + 50, image.height + 20)); processedImage = true; } }); doRefreshAll(); }
private BufferedImage aplicaFiltroMatrizConvolucion( double[][] filter, double factor, double bias, BufferedImage img) { imgTmp = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()); for (int x = 0; x < img.getWidth(); x++) { for (int y = 0; y < img.getHeight(); y++) { int r = 0, g = 0, b = 0; for (int filterX = 0; filterX < filter.length; filterX++) for (int filterY = 0; filterY < filter.length; filterY++) { int imageX = (x - filter.length / 2 + filterX + img.getWidth()) % img.getWidth(); int imageY = (y - filter.length / 2 + filterY + img.getHeight()) % img.getHeight(); Color c = new Color(img.getRGB(imageX, imageY)); r += c.getRed() * filter[filterX][filterY]; g += c.getGreen() * filter[filterX][filterY]; b += c.getBlue() * filter[filterX][filterY]; } imgTmp.setRGB( x, y, new Color( Math.min(Math.max((int) (factor * r + bias), 0), 255), Math.min(Math.max((int) (factor * g + bias), 0), 255), Math.min(Math.max((int) (factor * b + bias), 0), 255)) .getRGB()); } } return imgTmp; }
@Override protected void paintComponent(Graphics graphics) { // Fill in the background: Graphics2D g = (Graphics2D) graphics; Shape clip = g.getClip(); g.setColor(LightZoneSkin.Colors.NeutralGray); g.fill(clip); if (preview == null) { PlanarImage image = currentImage.get(); if (image == null) { engine.update(null, false); } else if (visibleRect != null && getHeight() > 1 && getWidth() > 1) { preview = cropScaleGrayscale(visibleRect, image); } } if (preview != null) { int dx, dy; AffineTransform transform = new AffineTransform(); if (getSize().width > preview.getWidth()) dx = (getSize().width - preview.getWidth()) / 2; else dx = 0; if (getSize().height > preview.getHeight()) dy = (getSize().height - preview.getHeight()) / 2; else dy = 0; transform.setToTranslation(dx, dy); try { g.drawRenderedImage(preview, transform); } catch (Exception e) { e.printStackTrace(); } } }
/** * Simple image flipper. Can flip image either vertically, horizontally or both directions * * @param source _ * @param flipType _ * @return BufferedImage * @throws NullPointerException _ * @throws IllegalArgumentException _ */ public static <T> BufferedImage flipImage(final T source, final FlipType flipType) throws NullPointerException, IllegalArgumentException, IOException { if (verifyNotNull(source, flipType)) { BufferedImage sourceImage = convertToBufferedImage(source); BufferedImage target = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType()); AffineTransform affineTransform; AffineTransformOp affineTransformOp; if (flipType.equals(FlipType.HORIZONTAL) || flipType.equals(FlipType.BOTH)) { affineTransform = AffineTransform.getScaleInstance(1, -1); affineTransform.translate(-sourceImage.getWidth(), 0); affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); target = affineTransformOp.filter(sourceImage, target); } if (flipType.equals(FlipType.VERTICAL) || flipType.equals(FlipType.BOTH)) { affineTransform = AffineTransform.getScaleInstance(1, -1); affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); affineTransform.translate(0, -sourceImage.getHeight()); target = affineTransformOp.filter(sourceImage, target); } return target; } throw new NullPointerException(E_OBJECT_WAS_NULL); }
public void extract(BufferedImage image) { histogram = new double[18]; double[] directionality; ColorConvertOp op = new ColorConvertOp( image.getColorModel().getColorSpace(), ColorSpace.getInstance(ColorSpace.CS_GRAY), new RenderingHints( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY)); BufferedImage bimg = op.filter(image, null); bimg = ImageUtils.scaleImage(bimg, MAX_IMG_HEIGHT); Raster raster = bimg.getRaster(); int[] tmp = new int[3]; this.grayScales = new int[raster.getWidth()][raster.getHeight()]; for (int i = 0; i < raster.getWidth(); i++) { for (int j = 0; j < raster.getHeight(); j++) { raster.getPixel(i, j, tmp); this.grayScales[i][j] = tmp[0]; } } imgWidth = bimg.getWidth(); imgHeight = bimg.getHeight(); histogram[0] = this.coarseness(bimg.getWidth(), bimg.getHeight()); histogram[1] = this.contrast(); directionality = this.directionality(); for (int i = 2; i < histogram.length; i++) { histogram[i] = directionality[i - 2]; } }
public BufferedImage filter(BufferedImage i) { BufferedImage result = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_RGB); // For each pixel in the image . . . for (int y = 0; y < i.getHeight(); y++) for (int x = 0; x < i.getWidth(); x++) { int pixel = i.getRGB(x, y); // Decompose the pixel in the amounts of red, green, and blue. int redAmount = (pixel >> 16) & 0xff; int greenAmount = (pixel >> 8) & 0xff; int blueAmount = pixel & 0xff; // Build a new pixel with the red and blue the same as the original, // but all green components set to the max value of 255. greenAmount = 255; // Compose the new pixel. int newPixel = (redAmount << 16) | (greenAmount << 8) | blueAmount; // Set the pixel of the new image. result.setRGB(x, y, newPixel); } return result; }
@Override public List<Frame> execute(CVParticle particle) throws Exception { List<Frame> result = new ArrayList<Frame>(); if (!(particle instanceof Frame)) return result; Frame frame = (Frame) particle; BufferedImage image = frame.getImage(); if (image == null) return result; if (image.getWidth() < 2 * cols || image.getHeight() < 2 * rows) return result; int width = image.getWidth() / cols; int height = image.getHeight() / rows; int tileIndex = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { Rectangle box = new Rectangle(c * width, r * height, width + pixelOverlap, height + pixelOverlap); box = box.intersection(frame.getBoundingBox()); BufferedImage tile = image.getSubimage(box.x, box.y, box.width, box.height); byte[] buffer = ImageUtils.imageToBytes(tile, imageType); result.add( new Frame( frame.getStreamId() + "_" + tileIndex, frame.getSequenceNr(), imageType, buffer, frame.getTimestamp(), box)); tileIndex++; } } return result; }