List of usage examples for java.awt.image BufferedImage getRGB
public int getRGB(int x, int y)
From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java
public static BufferedImage cylindricalMapping(BufferedImage img, double f) { if (img == null) { return null; }//from www.j ava2 s. c o m int w = img.getWidth(); int h = img.getHeight(); BufferedImage out = new BufferedImage(w, h, img.getType()); //System.out.println("w:"+w+", h:"+h); int x0 = (int) Math.floor(w / 2) + 1; int y0 = (int) Math.floor(h / 2) + 1; double tmax = Math.atan2((double) (w - x0), f); double tmin = Math.atan2(-((double) x0), f); double tstep = (tmax - tmin) / ((double) w); double vmax = ((double) (h - y0)) / f; double vmin = (-(double) y0) / f; double vstep = (vmax - vmin) / ((double) h); double theta, tan, cos; int x, y; for (int t = 0; t < w; t++) { theta = tmin + (double) t * tstep; tan = Math.tan(theta); cos = Math.cos(theta); x = (int) Math.round(f * tan) + x0; for (int v = 0; v < h; v++) { //nearest neighbour--------------------------------------- //x = (int)Math.round(f*tan) + x0; y = (int) Math.round((vmin + (double) v * vstep) * f / cos) + y0; if (x >= 0 && y >= 0 && x < w && y < h) { //piksel nowy x,y = piksel stary xd,yd out.setRGB(t, v, img.getRGB(x, y)); } //--------------------------------------------------------- } } return out; }
From source file:nl.b3p.imagetool.ImageTool.java
/** * Reads an image from an http input stream. * * @param method Apache HttpClient GetMethod object * @param mime String representing the mime type of the image. * * @return BufferedImage/*from ww w .j a va 2s.co m*/ * * @throws Exception */ // <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method."> public static BufferedImage readImage(InputStream is, String mime) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[2048]; while (bytesRead != -1) { bytesRead = is.read(buffer, 0, buffer.length); if (bytesRead > 0) { baos.write(buffer, 0, bytesRead); } } ImageReader ir = null; BufferedImage i = null; try { if (mime.indexOf(";") != -1) { mime = mime.substring(0, mime.indexOf(";")); } String mimeType = getMimeType(mime); /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de * HttpClient vernieuwing in kaartenbalie ? */ if (mimeType == null) { mimeType = "image/png"; } if (mimeType == null) { log.error("Response from server not understood (mime = " + mime + "): " + baos.toString()); throw new Exception( "Response from server not understood (mime = " + mime + "): " + baos.toString()); } ir = getReader(mimeType); if (ir == null) { log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); throw new Exception("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); } //TODO Make smarter.. Possibly faster... But keep reporting! ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray())); ir.setInput(stream, true); i = ir.read(0); //if image is a png, has no alpha and has a tRNS then make that color transparent. if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) { PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0); if (metadata.tRNS_present) { int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue); BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < i.getWidth(); x++) { for (int y = 0; y < i.getHeight(); y++) { int rgb = i.getRGB(x, y); rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb; tmp.setRGB(x, y, rgb); } } i = tmp; } } } finally { if (ir != null) { ir.dispose(); } } return i; }
From source file:oct.analysis.application.comp.EZWorker.java
@Override protected EZEdgeCoord doInBackground() throws Exception { int foveaCenterXPosition = analysisManager.getFoveaCenterXPosition(); /*/* www. j a v a2s . c o m*/ first get a sharpened version of the OCT and use that to obtain the segmentation of the Bruch's membrane. Use a Loess interpolation algorithm to smooth out imperfetions in the segmentation line. */ UnivariateInterpolator interpolator = new LoessInterpolator(0.1, 0); ArrayList<Point> rawBrmPoints = new ArrayList<>(analysisManager .getSegmentation(new SharpenOperation(15, 0.5F)).getSegment(Segmentation.BrM_SEGMENT)); double[][] brmSeg = Util.getXYArraysFromPoints(rawBrmPoints); UnivariateFunction brmInterp = interpolator.interpolate(brmSeg[0], brmSeg[1]); BufferedImage sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F); setProgress(10); /* Starting from the identified location of the fovea search northward in the image until the most northern pixels northward (in a 3x3 matrix of pixels arround the the search point (X,Y) ) are black (ie. the search matrix is has found that the search point isn't totally surrounded by white pixels). Then a recursive search algorithm determines if the black area signifies the seperation between bands or simply represents a closed (a black blob entirely surrounded by white pixels) black band. It will continue searching northward in the image until it can find an open region of all blak pixels. Once this is found it will find the contour of the edge between the black and white pixels along the width of the image. */ int searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition)) + 1; do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || !isContrastPoint(foveaCenterXPosition, searchY, sharpOCT)); LinkedList<Point> contour = new LinkedList<>(); Point startPoint = new Point(foveaCenterXPosition, searchY); //find contour by searching for white pixel boundary to te right of the fovea contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT, 0)); //search until open black area found (ie. if the search algorithm arrives back at //the starting pixel keep moving north to next black area to search) while (contour.get(0).equals(startPoint)) { contour = new LinkedList<>(); do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0); do { searchY--; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); startPoint = new Point(foveaCenterXPosition, searchY); contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT, 0)); } setProgress(20); //open balck space found, complete contour to left of fovea contour.add( findContourLeft(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT)); analysisManager.getImgPanel().setDrawPoint(new Point(foveaCenterXPosition, searchY)); setProgress(30); /* since the contour can snake around due to aberations and low image density we need to create a single line (represented by points) from left to right to represent the countour. This is easily done by building a line of points consisting of the point with the largest Y value (furthest from the top of the image) at each X value. This eliminates overhangs from the contour line. */ Map<Double, List<Point>> grouped = contour.stream().collect(Collectors.groupingBy(Point::getX)); List<Point> refinedEZContour = grouped.values().stream().map((List<Point> points) -> { int maxY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt(); return new Point(points.get(0).x, maxY); }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList()); setProgress(35); /* Starting from the identified location of the fovea search southward in the image until the most southern pixels (in a 3x3 matrix of pixels arround the the search point (X,Y) ) are black (ie. the search matrix has found that the search point isn't totally surrounded by white pixels). Then a recursive search algorithm determines if the black area signifies the bottom of the Bruch's membrane or simply represents a closed (a black blob entirely surrounded by white pixels) black band. It will continue searching southward in the image until it can find an open region of all black pixels. Once this is found it will find the contour of the edge between the black and white pixels, along the width of the image, of the bottom of the Bruch's membrane. */ // sharpOCT = getSharpenedOctImage(5D, 1.0F); searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition)); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); contour = new LinkedList<>(); startPoint = new Point(foveaCenterXPosition, searchY); /* Find contour by searching for white pixel boundary to te right of the fovea. Sometimes the crap below the Bruchs membrane causes too much interferance for the algorithm to work properly so we must tweak some of the parameters of the sharpening performed on the image until the algorithm succedes or we can no longer tweak parameters. In the case of the later event we can use the raw segmented Bruchs membrane as a substitute to keep the method from failing. */ contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); double filtValue = 8.5D; boolean tweakFailed = false; while (contour.contains(null)) { contour = new LinkedList<>(); filtValue -= 0.5D; System.out.println("Reducing sigma to " + filtValue); if (filtValue <= 0D) { tweakFailed = true; break; } sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F); contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); } if (tweakFailed) { contour = new LinkedList<>(rawBrmPoints); } else { //search until open black area found (ie. if the search algorithm arrives back at //the starting pixel keep moving south to next black area to search) while (contour.get(0).equals(startPoint)) { contour = new LinkedList<>(); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0); do { searchY++; } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0 || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT)); startPoint = new Point(foveaCenterXPosition, searchY); contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT, 0)); } setProgress(45); //open balck space found, complete contour to left of fovea contour.add(findContourLeft(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour, sharpOCT)); } setProgress(55); /* since the contour can snake around due to aberations and low image density we need to create a single line (represented by points) from left to right to represent the countour. This is easily done by building a line of points consisting of the point with the smallest Y value (closest to the top of the image) at each X value. This eliminates overhangs from the contour line. */ grouped = contour.stream().collect(Collectors.groupingBy(Point::getX)); List<Point> refinedBruchsMembraneContour = grouped.values().stream().map((List<Point> points) -> { int minY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt(); return new Point(points.get(0).x, minY); }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList()); setProgress(70); /* use a Loess interpolator again to smooth the new contours of the EZ and Bruch's Membrane */ double[][] refinedContourPoints = Util.getXYArraysFromPoints(refinedEZContour); UnivariateFunction interpEZContour = interpolator.interpolate(refinedContourPoints[0], refinedContourPoints[1]); refinedContourPoints = Util.getXYArraysFromPoints(refinedBruchsMembraneContour); UnivariateFunction interpBruchsContour = interpolator.interpolate(refinedContourPoints[0], refinedContourPoints[1]); /* find the average difference in the distance in the Y between the 10 pixels at each end of the Bruch's Membrane contour and the contour created along the top of the EZ. */ //since the lines are sorted on X position it is easy to align the lines //based on the tails of each line int minX = refinedEZContour.get(0).x; int maxX; //the interpolator can shorten the range of the X values from the original supplied //so we need to test where the end of the range occurs since it isn't directly accessible for (maxX = refinedEZContour.get(refinedEZContour.size() - 1).x; maxX > minX; maxX--) { try { double tmp = interpEZContour.value(maxX) - interpBruchsContour.value(maxX); //if this break is reached we have found the max value the interpolators will allow break; } catch (OutOfRangeException oe) { //do nothing but let loop continue } } double avgDif = Stream .concat(IntStream.range(minX + 30, minX + 50).boxed(), IntStream.range(maxX - 49, maxX - 28).boxed()) .mapToDouble(x -> interpBruchsContour.value(x) - interpEZContour.value(x)).average().getAsDouble(); int height = sharpOCT.getHeight();//make to use in lambda expression List<LinePoint> ezLine = IntStream.rangeClosed(minX, maxX) .mapToObj(x -> new LinePoint(x, height - interpEZContour.value(x) - avgDif)) .collect(Collectors.toList()); List<LinePoint> bmLine = IntStream.rangeClosed(minX, maxX) .mapToObj(x -> new LinePoint(x, height - interpBruchsContour.value(x))) .collect(Collectors.toList()); List<LinePoint> bmUnfiltLine = refinedBruchsMembraneContour.stream() .map((Point p) -> new LinePoint(p.x, height - p.getY())).collect(Collectors.toList()); Util.graphPoints(ezLine, bmLine, bmUnfiltLine); analysisManager.getImgPanel().setDrawnLines( IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpEZContour.value(x))) .collect(Collectors.toList()), IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpBruchsContour.value(x))) .collect(Collectors.toList())); /* Find the difference between the two contours (Bruch's membrane and the EZ + Bruch's membrane) and use this to determine where the edge of the EZ is */ List<LinePoint> diffLine = findDiffWithAdjustment(interpBruchsContour, 0D, interpEZContour, avgDif, minX, maxX); setProgress(90); // List<LinePoint> peaks = Util.findPeaksAndVallies(diffLine); // Util.graphPoints(diffLine, peaks); /* Find the first zero crossings of the difference line on both sides of the fovea. If a zero crossing can't be found then search for the first crossing of a value of 1, then 2, then 3, etc. until an X coordinate of a crossing is found on each side of the fovea. */ OptionalInt ezLeftEdge; double crossingThreshold = 0.25D; do { double filtThresh = crossingThreshold; System.out.println("Crossing threshold = " + crossingThreshold); ezLeftEdge = diffLine.stream().filter(lp -> lp.getY() <= filtThresh && lp.getX() < foveaCenterXPosition) .mapToInt(LinePoint::getX).max(); crossingThreshold += 0.25D; } while (!ezLeftEdge.isPresent()); OptionalInt ezRightEdge; crossingThreshold = 0.25D; do { double filtThresh = crossingThreshold; System.out.println("Crossing threshold = " + crossingThreshold); ezRightEdge = diffLine.stream() .filter(lp -> lp.getY() <= filtThresh && lp.getX() > foveaCenterXPosition) .mapToInt(LinePoint::getX).min(); crossingThreshold += 0.25D; } while (!ezRightEdge.isPresent()); //return findings return new EZEdgeCoord(ezLeftEdge.getAsInt(), ezRightEdge.getAsInt()); }
From source file:PNGDecoder.java
/** main encoding method (stays blocked till encoding is finished). * @param image BufferedImage to encode/*from ww w. j a va2 s .c om*/ * @throws IOException IOException */ public void encode(BufferedImage image) throws IOException { int width = image.getWidth(null); int height = image.getHeight(null); final byte id[] = { -119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13 }; write(id); crc.reset(); write("IHDR".getBytes()); write(width); write(height); byte head[] = null; switch (mode) { case BW_MODE: head = new byte[] { 1, 0, 0, 0, 0 }; break; case GREYSCALE_MODE: head = new byte[] { 8, 0, 0, 0, 0 }; break; case COLOR_MODE: head = new byte[] { 8, 2, 0, 0, 0 }; break; } write(head); write((int) crc.getValue()); ByteArrayOutputStream compressed = new ByteArrayOutputStream(65536); BufferedOutputStream bos = new BufferedOutputStream(new DeflaterOutputStream(compressed, new Deflater(9))); int pixel; int color; int colorset; switch (mode) { case BW_MODE: int rest = width % 8; int bytes = width / 8; for (int y = 0; y < height; y++) { bos.write(0); for (int x = 0; x < bytes; x++) { colorset = 0; for (int sh = 0; sh < 8; sh++) { pixel = image.getRGB(x * 8 + sh, y); color = ((pixel >> 16) & 0xff); color += ((pixel >> 8) & 0xff); color += (pixel & 0xff); colorset <<= 1; if (color >= 3 * 128) colorset |= 1; } bos.write((byte) colorset); } if (rest > 0) { colorset = 0; for (int sh = 0; sh < width % 8; sh++) { pixel = image.getRGB(bytes * 8 + sh, y); color = ((pixel >> 16) & 0xff); color += ((pixel >> 8) & 0xff); color += (pixel & 0xff); colorset <<= 1; if (color >= 3 * 128) colorset |= 1; } colorset <<= 8 - rest; bos.write((byte) colorset); } } break; case GREYSCALE_MODE: for (int y = 0; y < height; y++) { bos.write(0); for (int x = 0; x < width; x++) { pixel = image.getRGB(x, y); color = ((pixel >> 16) & 0xff); color += ((pixel >> 8) & 0xff); color += (pixel & 0xff); bos.write((byte) (color / 3)); } } break; case COLOR_MODE: for (int y = 0; y < height; y++) { bos.write(0); for (int x = 0; x < width; x++) { pixel = image.getRGB(x, y); bos.write((byte) ((pixel >> 16) & 0xff)); bos.write((byte) ((pixel >> 8) & 0xff)); bos.write((byte) (pixel & 0xff)); } } break; } bos.close(); write(compressed.size()); crc.reset(); write("IDAT".getBytes()); write(compressed.toByteArray()); write((int) crc.getValue()); write(0); crc.reset(); write("IEND".getBytes()); write((int) crc.getValue()); out.close(); }
From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java
public static BufferedImage rotateImage(BufferedImage img, double angle, int type, Color fillBgColor) { if (img == null) { return null; }//www . ja v a2s. co m if (angle > 360.0 || angle < -360) { angle = angle % 360.0; } if (angle < 0) { angle = 360 + angle; } if (angle == 0.0 || angle == 360.0) { return img; } //System.out.println("angle="+angle); int w = img.getWidth(); int h = img.getHeight(); /* AffineTransform tr = new AffineTransform(); tr.rotate(theta,w/2,h/2); BufferedImageOp op = new AffineTransformOp(tr, type); BufferedImage out = op.filter(img,null); */ /* AffineTransform tr = new AffineTransform(); tr.rotate(theta, w/2.0, h/2.0); AffineTransform translationTransform = findTranslation(tr, img); tr.preConcatenate(translationTransform); BufferedImageOp op = new AffineTransformOp(tr, type); BufferedImage out = op.filter(img,null); */ BufferedImage out = null; if (angle == 90.0 || angle == 180.0 || angle == 270.0) { switch ((int) angle) { case 90: out = new BufferedImage(h, w, img.getType()); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { out.setRGB(h - y - 1, x, img.getRGB(x, y)); } } break; case 180: out = new BufferedImage(w, h, img.getType()); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { out.setRGB(w - x - 1, h - y - 1, img.getRGB(x, y)); } } break; case 270: out = new BufferedImage(h, w, img.getType()); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { out.setRGB(y, w - x - 1, img.getRGB(x, y)); } } break; } } else { double theta = angle * Math.PI / 180.0; int neww = w, newh = h; double dx = 0.0, dy = 0.0; double s = Math.sin(theta); double c = Math.cos(theta); if (angle > 0.0 && angle < 90.0) { neww = (int) Math.round(((double) w) * c + ((double) h) * s); newh = (int) Math.round(((double) w) * s + ((double) h) * c); dx = ((double) h) * s; dy = 0.0; } else if (angle > 90.0 && angle < 180.0) { neww = (int) Math.round(-((double) w) * c + ((double) h) * s); newh = (int) Math.round(((double) w) * s - ((double) h) * c); dx = -((double) w) * c + ((double) h) * s; dy = -((double) h) * c; } else if (angle > 180.0 && angle < 270.0) { neww = (int) Math.round(-((double) w) * c - ((double) h) * s); newh = (int) Math.round(-((double) w) * s - ((double) h) * c); dx = -((double) w) * c; dy = -((double) w) * s - ((double) h) * c; } else if (angle > 270.0 && angle < 360.0) { neww = (int) Math.round(((double) w) * c - ((double) h) * s); newh = (int) Math.round(-((double) w) * s + ((double) h) * c); dx = 0.0; dy = -((double) w) * s; } AffineTransform tr = new AffineTransform(); tr.translate(dx, dy); tr.rotate(theta); BufferedImageOp op = new AffineTransformOp(tr, type); out = new BufferedImage(neww, newh, img.getType()); Graphics2D g2d = (Graphics2D) out.getGraphics(); Rectangle clear = new Rectangle(0, 0, out.getWidth(), out.getHeight()); g2d.setPaint(fillBgColor); g2d.fill(clear); op.filter(img, out); } return out; }
From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java
public static BufferedImage sphericalMapping(BufferedImage img, double f) { if (img == null) { return null; }/*from w w w .ja v a 2s. co m*/ int w = img.getWidth(); int h = img.getHeight(); BufferedImage out = new BufferedImage(w, h, img.getType()); //System.out.println("w:"+w+", h:"+h); int x0 = (int) Math.floor(w / 2) + 1; int y0 = (int) Math.floor(h / 2) + 1; double tmax = Math.atan2((double) (w - x0), f); double tmin = Math.atan2(-((double) x0), f); double tstep = (tmax - tmin) / ((double) w); double fimax = Math.atan2((double) (h - y0), Math.sqrt(f * f)); double fimin = Math.atan2(-(double) y0, Math.sqrt(f * f)); double fistep = (fimax - fimin) / ((double) h); //System.out.println("fimax:"+fimax+", fimin:"+fimin); double theta, tantheta, costheta, tanfi, phi; int x, y; for (int t = 0; t < w; t++) { theta = tmin + (double) t * tstep; tantheta = Math.tan(theta); x = (int) Math.round(f * tantheta) + x0; for (int fi = 0; fi < h; fi++) { //nearest neighbour--------------------------------------- phi = fimin + (double) fi * fistep; tanfi = Math.tan(phi); //x = (int)Math.round(f*tantheta) + x0; y = (int) Math.round(Math.sqrt((x - x0) * (x - x0) + f * f) * tanfi) + y0; if (x >= 0 && y >= 0 && x < w && y < h) { //piksel nowy x,y = piksel stary xd,yd out.setRGB(t, fi, img.getRGB(x, y)); } //--------------------------------------------------------- } } return out; }
From source file:uk.bl.dpt.qa.gui.DissimilarGUIThread.java
/** * overlay heatmap on image//from ww w. j a v a 2 s . co m */ private void internalOverlayHeatmap() { gRightImageSave = imageRight.getImage(); if (!gHeatmapGenerated) { internalBeforeGUIThread(); //threaded load so GUI doesn't hang Task<Integer> task = new Task<Integer>() { @Override protected Integer call() throws Exception { BufferedImage image = SwingFXUtils.fromFXImage(imageRight.getImage(), null); if (gHeatmap == null) { //re-generate heatmap (must be on a re-load) try { gHeatmap = Imaging.getBufferedImage(gResults.get(gCurrentRecord).getHeatmapTemp()); } catch (IOException | ImageReadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int rgb = image.getRGB(x, y); Color heatmapColor = new Color(gHeatmap.getRGB((x / DissimilarV2.SSIMWINDOWSIZE), (y / DissimilarV2.SSIMWINDOWSIZE))); int heatmapPixel = heatmapColor.getGreen();//&maxPixelValue; if (heatmapColor.getGreen() != heatmapColor.getBlue() && heatmapColor.getBlue() != heatmapColor.getRed()) { gLogger.error("Heatmap error (should not happen)"); } double factor = 1 - (((double) heatmapPixel / 255)); Color col = new Color(rgb); int red = (int) (factor * col.getRed()); int green = (int) (factor * col.getGreen()); int blue = (int) (factor * col.getBlue()); if (red < 0) red = 0; if (green < 0) green = 0; if (blue < 0) blue = 0; col = new Color(red, green, blue); image.setRGB(x, y, col.getRGB()); } } gHeatmapImage = SwingFXUtils.toFXImage(image, null); gHeatmapGenerated = true; Platform.runLater(new Runnable() { //@Override public void run() { imageRight.setImage(gHeatmapImage); } }); internalAfterGUIThread(); return 1; } }; progressIndicator.progressProperty().bind(task.progressProperty()); Thread loader = new Thread(task); loader.setDaemon(true); loader.start(); } else { imageRight.setImage(gHeatmapImage); } }
From source file:nl.b3p.viewer.image.ImageTool.java
/** Reads an image from an http input stream. * * @param method Apache HttpClient GetMethod object * @param mime String representing the mime type of the image. * * @return BufferedImage/* w w w. j a v a 2 s . c o m*/ * * @throws Exception */ // <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method."> public static BufferedImage readImage(HttpMethod method, String mime) throws Exception { ImageReader ir = null; BufferedImage i = null; try { if (mime.indexOf(";") != -1) { mime = mime.substring(0, mime.indexOf(";")); } String mimeType = getMimeType(mime); /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de * HttpClient vernieuwing in kaartenbalie ? */ if (mimeType == null) { mimeType = "image/png"; } if (mimeType == null) { log.error("Response from server not understood (mime = " + mime + "): " + method.getResponseBodyAsString()); throw new Exception("Response from server not understood (mime = " + mime + "): " + method.getResponseBodyAsString()); } ir = getReader(mimeType); if (ir == null) { log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); throw new Exception("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); } //TODO Make smarter.. Possibly faster... But keep reporting! InputStream is = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[2048]; while (bytesRead != -1) { bytesRead = is.read(buffer, 0, buffer.length); if (bytesRead > 0) { baos.write(buffer, 0, bytesRead); } } ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray())); ir.setInput(stream, true); i = ir.read(0); //if image is a png, has no alpha and has a tRNS then make that color transparent. if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) { PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0); if (metadata.tRNS_present) { int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue); BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < i.getWidth(); x++) { for (int y = 0; y < i.getHeight(); y++) { int rgb = i.getRGB(x, y); rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb; tmp.setRGB(x, y, rgb); } } i = tmp; } } } finally { if (ir != null) { ir.dispose(); } } return i; }
From source file:pl.edu.icm.visnow.lib.utils.ImageUtilities.java
public static BufferedImage compensateLensDistortion2(BufferedImage img, double k) { if (img == null) { return null; }//from w w w . j a v a2 s .c o m int w = img.getWidth(); int h = img.getHeight(); //BufferedImage out = new BufferedImage(w, h, img.getType()); int x0 = (int) Math.floor(w / 2) + 1; int y0 = (int) Math.floor(h / 2) + 1; double ru, theta, ww, rd; int xd, yd; double rdmax = Math.sqrt((w - x0) * (w - x0) + (h - y0) * (h - y0)); double rumax = rdmax * (1 + k * rdmax * rdmax); //System.out.println("rdmax="+rdmax); //System.out.println("rumax="+rumax); double thetamax = Math.atan2(h - y0, w - x0); int xmax = (int) Math.round(rumax * Math.cos(thetamax)) * 2; int ymax = (int) Math.round(rumax * Math.sin(thetamax)) * 2; //System.out.println("xmax="+xmax); //System.out.println("ymax="+ymax); BufferedImage out = new BufferedImage(xmax, ymax, img.getType()); int newx0 = (int) Math.floor(xmax / 2) + 1; int newy0 = (int) Math.floor(ymax / 2) + 1; int dx = (int) ((xmax - w) / 2) - 1; int dy = (int) ((ymax - h) / 2) - 1; for (int x = 0; x < xmax; x++) { for (int y = 0; y < ymax; y++) { ru = Math.sqrt((x - newx0) * (x - newx0) + (y - newy0) * (y - newy0)); theta = Math.atan2(y - newy0, x - newx0); ww = Math.pow(ru / (2 * k) + Math.sqrt((ru * ru) / (4 * k * k) + 1 / (27 * k * k * k)), 1.0 / 3.0); rd = ww - 1 / (3 * k * ww); //nearest neighbour--------------------------------------- xd = (int) Math.round(rd * Math.cos(theta)) + x0; yd = (int) Math.round(rd * Math.sin(theta)) + y0; if (xd >= 0 && yd >= 0 && xd < w && yd < h) { //piksel nowy x,y = piksel stary xd,yd out.setRGB(x, y, img.getRGB(xd, yd)); } //--------------------------------------------------------- } } return out; }
From source file:blusunrize.immersiveengineering.client.render.IEShaderLayerCompositeTexture.java
@Override public void loadTexture(IResourceManager resourceManager) { this.deleteGlTexture(); IResource iresource = null;//from w ww . j av a2 s.c o m BufferedImage bufferedimage; BufferedImage scaledImage; label255: { try { iresource = resourceManager.getResource(this.canvasTexture); BufferedImage canvasImage = TextureUtil.readBufferedImage(iresource.getInputStream()); int imageType = canvasImage.getType(); if (imageType == 0) imageType = 6; int canvasWidth = canvasImage.getWidth(); int canvasHeight = canvasImage.getHeight(); bufferedimage = new BufferedImage(canvasWidth, canvasHeight, imageType); int layer = 0; while (true) { if (layer >= 17 || layer >= this.layers.length) break label255; IResource iresource1 = null; try { String texPath = this.layers[layer].getTexture().getPath(); if (!texPath.startsWith("textures/")) texPath = "textures/" + texPath; if (!texPath.endsWith(".png")) texPath += ".png"; String texture = this.layers[layer].getTexture().getNamespace() + ":" + texPath; int colour = this.layers[layer].getColour(); iresource1 = resourceManager.getResource(new ResourceLocation(texture)); BufferedImage texureImage = TextureUtil.readBufferedImage(iresource1.getInputStream()); scaledImage = new BufferedImage(canvasWidth, canvasHeight, imageType); float[] mod = { (colour >> 16 & 255) / 255f, (colour >> 8 & 255) / 255f, (colour & 255) / 255f, (colour >> 24 & 255) / 255f }; IntFunction<Integer> uInterpolate = uIn -> uIn; IntFunction<Integer> vInterpolate = vIn -> vIn; int bufImg2Size = Math.min(texureImage.getWidth(), texureImage.getHeight()); int uMin = 0; int vMin = 0; int uMax = canvasWidth; int vMax = canvasHeight; final double[] texBounds = this.layers[layer].getTextureBounds(); if (texBounds != null) { final double uOffset = texBounds[0] * canvasWidth; final double vOffset = texBounds[1] * canvasHeight; final double uScale = bufImg2Size / ((texBounds[2] - texBounds[0]) * canvasWidth); final double vScale = bufImg2Size / ((texBounds[3] - texBounds[1]) * canvasHeight); uInterpolate = uIn -> (int) Math.round((uIn - uOffset) * uScale); vInterpolate = vIn -> (int) Math.round((vIn - vOffset) * vScale); uMin = (int) uOffset; vMin = (int) vOffset; uMax = (int) (texBounds[2] * canvasWidth); vMax = (int) (texBounds[3] * canvasHeight); } try { for (int v = vMin; v < vMax; ++v) for (int u = uMin; u < uMax; ++u) { int interU = uInterpolate.apply(u) % bufImg2Size; int interV = vInterpolate.apply(v) % bufImg2Size; int iRGB = texureImage.getRGB(interU, interV); float[] rgb = { (iRGB >> 16 & 255) / 255f, (iRGB >> 8 & 255) / 255f, (iRGB & 255) / 255f, (iRGB >> 24 & 255) / 255f }; if ((iRGB & -16777216) != 0) { int iNoise = canvasImage.getRGB(u, v); float[] noise = { (iNoise >> 16 & 255) / 255f, (iNoise >> 8 & 255) / 255f, (iNoise & 255) / 255f, (iNoise >> 24 & 255) / 255f }; for (int m = 0; m < 4; m++) rgb[m] = rgb[m] * mod[m] * noise[m]; int[] irgb = { (int) (rgb[0] * 255), (int) (rgb[1] * 255), (int) (rgb[2] * 255), (int) (rgb[3] * 255) }; int i2 = (irgb[0] << 16) + (irgb[1] << 8) + (irgb[2]) + (irgb[3] << 24); scaledImage.setRGB(u, v, i2); } } } catch (Exception e) { e.printStackTrace(); } bufferedimage.getGraphics().drawImage(scaledImage, 0, 0, null); } finally { IOUtils.closeQuietly(iresource1); } ++layer; } } catch (IOException ioexception) { IELogger.error("Couldn't load layered image", ioexception); } finally { IOUtils.closeQuietly(iresource); } return; } TextureUtil.uploadTextureImage(this.getGlTextureId(), bufferedimage); }