List of usage examples for java.awt.image BufferedImage TYPE_BYTE_GRAY
int TYPE_BYTE_GRAY
To view the source code for java.awt.image BufferedImage TYPE_BYTE_GRAY.
Click Source Link
From source file:com.occamlab.te.parsers.ImageParser.java
private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes) throws Exception { HashMap<Object, Object> bandMap = new HashMap<Object, Object>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getLocalName().equals("subimage")) { Element e = (Element) node; int x = Integer.parseInt(e.getAttribute("x")); int y = Integer.parseInt(e.getAttribute("y")); int w = Integer.parseInt(e.getAttribute("width")); int h = Integer.parseInt(e.getAttribute("height")); processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes()); } else if (node.getLocalName().equals("checksum")) { CRC32 checksum = new CRC32(); Raster raster = buffimage.getRaster(); DataBufferByte buffer; if (node.getParentNode().getLocalName().equals("subimage")) { WritableRaster outRaster = raster.createCompatibleWritableRaster(); buffimage.copyData(outRaster); buffer = (DataBufferByte) outRaster.getDataBuffer(); } else { buffer = (DataBufferByte) raster.getDataBuffer(); }/*from w w w. ja va2 s. c om*/ int numbanks = buffer.getNumBanks(); for (int j = 0; j < numbanks; j++) { checksum.update(buffer.getData(j)); } Document doc = node.getOwnerDocument(); node.appendChild(doc.createTextNode(Long.toString(checksum.getValue()))); } else if (node.getLocalName().equals("count")) { String band = ((Element) node).getAttribute("bands"); String sample = ((Element) node).getAttribute("sample"); if (sample.equals("all")) { bandMap.put(band, null); } else { HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band); if (sampleMap == null) { if (!bandMap.containsKey(band)) { sampleMap = new HashMap<Object, Object>(); bandMap.put(band, sampleMap); } } sampleMap.put(Integer.decode(sample), new Integer(0)); } } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24 // PwD String transparentNodata = checkTransparentNodata(buffimage, node); node.setTextContent(transparentNodata); } } } Iterator bandIt = bandMap.keySet().iterator(); while (bandIt.hasNext()) { String band_str = (String) bandIt.next(); int band_indexes[]; if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) { band_indexes = new int[1]; band_indexes[0] = 0; } else { band_indexes = new int[band_str.length()]; for (int i = 0; i < band_str.length(); i++) { if (band_str.charAt(i) == 'A') band_indexes[i] = 3; if (band_str.charAt(i) == 'B') band_indexes[i] = 2; if (band_str.charAt(i) == 'G') band_indexes[i] = 1; if (band_str.charAt(i) == 'R') band_indexes[i] = 0; } } Raster raster = buffimage.getRaster(); java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str); boolean addall = (sampleMap == null); if (sampleMap == null) { sampleMap = new java.util.HashMap(); bandMap.put(band_str, sampleMap); } int minx = raster.getMinX(); int maxx = minx + raster.getWidth(); int miny = raster.getMinY(); int maxy = miny + raster.getHeight(); int bands[][] = new int[band_indexes.length][raster.getWidth()]; for (int y = miny; y < maxy; y++) { for (int i = 0; i < band_indexes.length; i++) { raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]); } for (int x = minx; x < maxx; x++) { int sample = 0; for (int i = 0; i < band_indexes.length; i++) { sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8); } Integer sampleObj = new Integer(sample); boolean add = addall; if (!addall) { add = sampleMap.containsKey(sampleObj); } if (add) { Integer count = (Integer) sampleMap.get(sampleObj); if (count == null) { count = new Integer(0); } count = new Integer(count.intValue() + 1); sampleMap.put(sampleObj, count); } } } } Node node = nodes.item(0); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getLocalName().equals("count")) { String band = ((Element) node).getAttribute("bands"); String sample = ((Element) node).getAttribute("sample"); HashMap sampleMap = (HashMap) bandMap.get(band); Document doc = node.getOwnerDocument(); if (sample.equals("all")) { Node parent = node.getParentNode(); Node prevSibling = node.getPreviousSibling(); Iterator sampleIt = sampleMap.keySet().iterator(); Element countnode = null; int digits; String prefix; switch (buffimage.getType()) { case BufferedImage.TYPE_BYTE_BINARY: digits = 1; prefix = ""; break; case BufferedImage.TYPE_BYTE_GRAY: digits = 2; prefix = "0x"; break; default: prefix = "0x"; digits = band.length() * 2; } while (sampleIt.hasNext()) { countnode = doc.createElementNS(node.getNamespaceURI(), "count"); Integer sampleInt = (Integer) sampleIt.next(); Integer count = (Integer) sampleMap.get(sampleInt); if (band.length() > 0) { countnode.setAttribute("bands", band); } countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits)); Node textnode = doc.createTextNode(count.toString()); countnode.appendChild(textnode); parent.insertBefore(countnode, node); if (sampleIt.hasNext()) { if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) { parent.insertBefore(prevSibling.cloneNode(false), node); } } } parent.removeChild(node); node = countnode; } else { Integer count = (Integer) sampleMap.get(Integer.decode(sample)); if (count == null) count = new Integer(0); Node textnode = doc.createTextNode(count.toString()); node.appendChild(textnode); } } } node = node.getNextSibling(); } }
From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java
/** * Rescales using plate intensities and converts to 8bit. Works for gray- and rgb color images. * * @param bi16//from w ww. j a v a2s .c om * @return */ public static BufferedImage convertTo8bit(int rdfId, BufferedImage bi16, PlateScalingMin plateScalingMin, PlateScalingMax plateScalingMax) throws Exception { RawDataFile rdf = DALConfig.getImageProvider().LoadRawDataFile(rdfId); /* if (plateScalingMin==defaultPlateScalingMin && plateScalingMax==defaultPlateScalingMax) { // /orbitvol1/2014-11/4309324.1002.jpg String url = RawUtils.STR_SERVER+"/rawFile?rawFile="+rdf.getDataPath()+"/"+rdfId+"."+RawUtils.LEVEL_8BITPREVIEW+".jpg"; System.out.println("url: " + url); return ImageIO.read(new URL(url)); } */ RawData rd = DALConfig.getImageProvider().LoadRawData(rdf.getRawDataId()); List<RawMeta> rmList = DALConfig.getImageProvider().LoadRawMetasByRawDataFile(rdfId); List<RawMeta> rmDataList = DALConfig.getImageProvider().LoadRawMetasByRawData(rd.getRawDataId()); rmList.addAll(rmDataList); HashMap<String, RawMeta> rmHash = RawUtilsCommon.getHashFromMetaList(rmList); if (!rmHash.containsKey(RawUtilsCommon.STR_META_CHANNEL)) throw new Exception("Error: Meta data 'Channel' not available for RawDataFile " + rdfId); //int channel = Integer.parseInt(rmHash.get(RawUtils.STR_META_CHANNEL).getValue()) - 1; int channel = Integer.parseInt(rmHash.get(RawUtilsCommon.STR_META_CHANNEL).getValue()); String metaKey = "Percentiles_wvlength_" + channel + "_channel_0"; if (!rmHash.containsKey(metaKey)) throw new Exception("Error: Meta data '" + metaKey + "' not available for RawDataFile " + rdfId); String val = rmHash.get(metaKey).getValue(); int[] minmax = parseMinMax(val, plateScalingMin, plateScalingMax); BufferedImage bi = null; if (bi16.getSampleModel().getNumBands() == 1) { bi16 = ImageUtils.scaleIntensities(bi16, new int[] { minmax[0] }, new int[] { minmax[1] }); bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY); } else { throw new IllegalArgumentException("Only images with 1 band (gray-color) supported. This image has " + bi16.getSampleModel().getNumBands() + " bands."); } Graphics2D g2d = bi.createGraphics(); g2d.drawImage(bi16, 0, 0, null); g2d.dispose(); return bi; }
From source file:javafx1.JavaFX1.java
public Image bildLaden() { Image zwischenBild = null; try {/*from w ww .j av a2 s . c om*/ File input = new File("D:/_piCam/bild.jpg"); //FileInputStream bi = ImageIO.read(input); BufferedImage bi = ImageIO.read(input); byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData(); Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3); mat.put(0, 0, data); Mat bild = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC1); Imgproc.cvtColor(mat, bild, Imgproc.COLOR_BGR2GRAY); byte[] data1 = new byte[bild.rows() * bild.cols() * (int) (bild.elemSize())]; bild.get(0, 0, data1); BufferedImage image1 = new BufferedImage(bild.cols(), bild.rows(), BufferedImage.TYPE_BYTE_GRAY); image1.getRaster().setDataElements(0, 0, bild.cols(), bild.rows(), data1); File ouptut = new File("D:/xml/grayscale2.jpg"); //ImageIO.write(image1, "jpg", ouptut); BufferedImage gray = image1.getSubimage(0, 0, image1.getTileWidth(), image1.getHeight()); zwischenBild = SwingFXUtils.toFXImage(gray, null); } catch (IOException ex) { System.out.println("Fehler beim Bild laden..."); } return zwischenBild; }
From source file:com.mikenimer.familydam.services.photos.ThumbnailService.java
/** * using the metadata orientation transformation information rotate the image. * @param image//from w ww. j a va2 s .c o m * @param transform * @return * @throws Exception */ public static BufferedImage transformImage(BufferedImage image, AffineTransform transform) throws Exception { AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC); BufferedImage destinationImage = op.createCompatibleDestImage(image, (image.getType() == BufferedImage.TYPE_BYTE_GRAY) ? image.getColorModel() : null); Graphics2D g = destinationImage.createGraphics(); g.setBackground(Color.WHITE); g.clearRect(0, 0, destinationImage.getWidth(), destinationImage.getHeight()); destinationImage = op.filter(image, destinationImage); return destinationImage; }
From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java
/** * Rescales using predefined min,max intensities and converts to 8bit. Works for gray- and rgb color images. * * @param bi16/* w w w. j av a 2s. co m*/ * @return */ public static BufferedImage convertTo8bit(BufferedImage bi16, int min, int max) { BufferedImage bi = null; if (bi16.getSampleModel().getNumBands() == 1) { bi16 = ImageUtils.scaleIntensities(bi16, new int[] { min }, new int[] { max }); bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY); } else if (bi16.getSampleModel().getNumBands() == 3) { throw new IllegalArgumentException("only grayscale images supported"); } else { throw new IllegalArgumentException( "Only images with 1 band (gray-color) or 3 bands (rgb) supported. This image has " + bi16.getSampleModel().getNumBands() + " bands."); } Graphics2D g2d = bi.createGraphics(); g2d.drawImage(bi16, 0, 0, null); g2d.dispose(); return bi; }
From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java
/** * Calculate the PSNR between two files/* w w w . ja va 2 s . com*/ * @param pOne first image to compare * @param pTwo second image to compare * @return calculated psnr */ public static double calcPSNR(final File pOne, final File pTwo) { BufferedImage imageOne = null; try { imageOne = Imaging.getBufferedImage(pOne); } catch (IOException e) { printError(pOne, false, false, pTwo, false); return -1; } catch (NullPointerException e) { printError(pOne, false, false, pTwo, false); return -1; } catch (ImageReadException e) { printError(pOne, false, false, pTwo, false); return -1; } //getRGB only returns 8 bits per component, so what about 16-bit images? final int[] oneA = imageOne.getRGB(0, 0, imageOne.getWidth(), imageOne.getHeight(), null, 0, imageOne.getWidth()); final boolean greyscale = (imageOne.getType() == BufferedImage.TYPE_BYTE_GRAY || imageOne.getType() == BufferedImage.TYPE_USHORT_GRAY); imageOne = null; BufferedImage imageTwo = null; try { imageTwo = Imaging.getBufferedImage(pTwo); } catch (IOException e) { printError(pOne, true, true, pTwo, false); return -1; } catch (NullPointerException e) { printError(pOne, true, true, pTwo, false); return -1; } catch (ImageReadException e) { printError(pOne, true, true, pTwo, false); return -1; } //getRGB only returns 8 bits per component, so what about 16-bit images? final int[] twoA = imageTwo.getRGB(0, 0, imageTwo.getWidth(), imageTwo.getHeight(), null, 0, imageTwo.getWidth()); imageTwo = null; final double psnr = calcPSNR(oneA, twoA, greyscale); return psnr; }
From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java
private BufferedImage getFallbackBufferedImage(ImageReader reader, int pageIndex, ImageReadParam param) throws IOException { //Work-around found at: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903 //There are some additional ideas there if someone wants to go further. // Try reading a Raster (no color conversion). Raster raster = reader.readRaster(pageIndex, param); // Arbitrarily select a BufferedImage type. int imageType; switch (raster.getNumBands()) { case 1://from w w w .ja v a 2 s .c o m imageType = BufferedImage.TYPE_BYTE_GRAY; break; case 3: imageType = BufferedImage.TYPE_3BYTE_BGR; break; case 4: imageType = BufferedImage.TYPE_4BYTE_ABGR; break; default: throw new UnsupportedOperationException(); } // Create a BufferedImage. BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(), imageType); // Set the image data. bi.getRaster().setRect(raster); return bi; }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
private static SizeAndBufferedImage calcScaledSize(ImageInputStream stream, String suffix, int maxWidth, int maxHeight, boolean fill) { Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix); if (iter.hasNext()) { ImageReader reader = iter.next(); try {// ww w .ja v a 2 s. c om reader.setInput(stream, true, true); int width = reader.getWidth(reader.getMinIndex()); int height = reader.getHeight(reader.getMinIndex()); Size size = new Size(width, height, false); Size scaledSize = computeScaledSize(width, height, maxWidth, maxHeight, fill); SizeAndBufferedImage all = new SizeAndBufferedImage(size, scaledSize); int readerMinIndex = reader.getMinIndex(); ImageReadParam param = reader.getDefaultReadParam(); Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0); while (imageTypes.hasNext()) { try { ImageTypeSpecifier imageTypeSpecifier = imageTypes.next(); int bufferedImageType = imageTypeSpecifier.getBufferedImageType(); if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) { param.setDestinationType(imageTypeSpecifier); } double memoryKB = (width * height * 4) / 1024d; if (memoryKB > 2000) {// check limit at 20MB double free = Runtime.getRuntime().freeMemory() / 1024d; if (free > memoryKB) { all.setImage(reader.read(readerMinIndex, param)); } else { // make sub sampling to save memory int ratio = (int) Math.round(Math.sqrt(memoryKB / free)); param.setSourceSubsampling(ratio, ratio, 0, 0); all.setImage(reader.read(readerMinIndex, param)); } } else { all.setImage(reader.read(readerMinIndex, param)); } return all; } catch (IllegalArgumentException e) { log.warn(e.getMessage(), e); } } } catch (IOException e) { log.error(e.getMessage(), e); } finally { reader.dispose(); } } else { log.error("No reader found for given format: " + suffix, null); } return null; }
From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java
/** * Calculate the SSIM between two files//from www. j a v a 2 s . c o m * @param pOne first image to compare * @param pTwo second image to compare * @param pHeatMapFilename ssim heat map image filename (can be null) * @param pMin list for return value - ssim minimum (can be null) * @param pVariance list for return value - ssim variance (can be null) * @return calculated ssim */ public static double calcSSIM(final File pOne, final File pTwo, final String pHeatMapFilename, List<Double> pMin, List<Double> pVariance) { BufferedImage imageOne = null; try { imageOne = Imaging.getBufferedImage(pOne); } catch (IOException e) { printError(pOne, false, false, pTwo, false); return -1; } catch (NullPointerException e) { printError(pOne, false, false, pTwo, false); return -1; } catch (ImageReadException e) { printError(pOne, false, false, pTwo, false); return -1; } //getRGB only returns 8 bits per component, so what about 16-bit images? final int[] oneA = imageOne.getRGB(0, 0, imageOne.getWidth(), imageOne.getHeight(), null, 0, imageOne.getWidth()); final int width = imageOne.getWidth(); final int height = imageOne.getHeight(); final boolean greyscale = (imageOne.getType() == BufferedImage.TYPE_BYTE_GRAY || imageOne.getType() == BufferedImage.TYPE_USHORT_GRAY); imageOne = null; BufferedImage imageTwo = null; try { imageTwo = Imaging.getBufferedImage(pTwo); } catch (IOException e) { printError(pOne, true, true, pTwo, false); return -1; } catch (NullPointerException e) { printError(pOne, true, true, pTwo, false); return -1; } catch (ImageReadException e) { printError(pOne, true, true, pTwo, false); return -1; } //getRGB only returns 8 bits per component, so what about 16-bit images? final int[] twoA = imageTwo.getRGB(0, 0, imageTwo.getWidth(), imageTwo.getHeight(), null, 0, imageTwo.getWidth()); imageTwo = null; final double ssim = calcSSIM(oneA, twoA, width, height, greyscale, pHeatMapFilename, pMin, pVariance); return ssim; }
From source file:org.codice.alliance.imaging.chip.transformer.CatalogOutputAdapter.java
private void setImageDataFields(BufferedImage chip, ImageSegment chipImageSegment) throws IOException { int[] componentSizes = chip.getColorModel().getComponentSize(); int pixelSize = chip.getColorModel().getPixelSize(); switch (chip.getType()) { case BufferedImage.TYPE_BYTE_GRAY: case BufferedImage.TYPE_USHORT_GRAY: case BufferedImage.TYPE_BYTE_BINARY: setMonochrome(chipImageSegment, componentSizes[0], pixelSize); break;//from w w w .ja v a 2s .com case BufferedImage.TYPE_3BYTE_BGR: case BufferedImage.TYPE_INT_BGR: setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBTRUECOLOUR, componentSizes[0], pixelSize / 3, new String[] { "B", "G", "R" }); break; case BufferedImage.TYPE_4BYTE_ABGR: case BufferedImage.TYPE_4BYTE_ABGR_PRE: setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBTRUECOLOUR, componentSizes[0], pixelSize / 4, new String[] { "B", "G", "R" }); break; case BufferedImage.TYPE_INT_ARGB_PRE: case BufferedImage.TYPE_INT_ARGB: setARGB(chipImageSegment, componentSizes[0], pixelSize); break; case BufferedImage.TYPE_INT_RGB: case BufferedImage.TYPE_USHORT_555_RGB: setRGB(chipImageSegment, componentSizes[0], pixelSize); break; case BufferedImage.TYPE_CUSTOM: if (componentSizes.length == 1) { setMonochrome(chipImageSegment, componentSizes[0], pixelSize); } else if (componentSizes.length == 3) { setRGB(chipImageSegment, componentSizes[0], pixelSize); } else if (componentSizes.length == 4) { setARGB(chipImageSegment, componentSizes[0], pixelSize); } else { throw new IOException( "unsupported color model for image type CUSTOM, only monochrome and 32-bit argb are supported"); } break; case BufferedImage.TYPE_BYTE_INDEXED: setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBLUT, componentSizes[0], pixelSize, new String[] { "LU" }); break; case BufferedImage.TYPE_USHORT_565_RGB: // don't know how to handle this one, since the bitsPerPixelPerBand is not consistent break; default: throw new IOException("unsupported image data type: type=" + chip.getType()); } }