use of java.awt.image.BufferedImage in project libgdx by libgdx.
the class TexturePacker method writeImages.
private void writeImages(File outputDir, String scaledPackFileName, Array<Page> pages) {
File packFileNoExt = new File(outputDir, scaledPackFileName);
File packDir = packFileNoExt.getParentFile();
String imageName = packFileNoExt.getName();
int fileIndex = 0;
for (Page page : pages) {
int width = page.width, height = page.height;
int paddingX = settings.paddingX;
int paddingY = settings.paddingY;
if (settings.duplicatePadding) {
paddingX /= 2;
paddingY /= 2;
}
width -= settings.paddingX;
height -= settings.paddingY;
if (settings.edgePadding) {
page.x = paddingX;
page.y = paddingY;
width += paddingX * 2;
height += paddingY * 2;
}
if (settings.pot) {
width = MathUtils.nextPowerOfTwo(width);
height = MathUtils.nextPowerOfTwo(height);
}
width = Math.max(settings.minWidth, width);
height = Math.max(settings.minHeight, height);
page.imageWidth = width;
page.imageHeight = height;
File outputFile;
while (true) {
outputFile = new File(packDir, imageName + (fileIndex++ == 0 ? "" : fileIndex) + "." + settings.outputFormat);
if (!outputFile.exists())
break;
}
new FileHandle(outputFile).parent().mkdirs();
page.imageName = outputFile.getName();
BufferedImage canvas = new BufferedImage(width, height, getBufferedImageType(settings.format));
Graphics2D g = (Graphics2D) canvas.getGraphics();
if (!settings.silent)
System.out.println("Writing " + canvas.getWidth() + "x" + canvas.getHeight() + ": " + outputFile);
for (Rect rect : page.outputRects) {
BufferedImage image = rect.getImage(imageProcessor);
int iw = image.getWidth();
int ih = image.getHeight();
int rectX = page.x + rect.x, rectY = page.y + page.height - rect.y - rect.height;
if (settings.duplicatePadding) {
int amountX = settings.paddingX / 2;
int amountY = settings.paddingY / 2;
if (rect.rotated) {
// Copy corner pixels to fill corners of the padding.
for (int i = 1; i <= amountX; i++) {
for (int j = 1; j <= amountY; j++) {
plot(canvas, rectX - j, rectY + iw - 1 + i, image.getRGB(0, 0));
plot(canvas, rectX + ih - 1 + j, rectY + iw - 1 + i, image.getRGB(0, ih - 1));
plot(canvas, rectX - j, rectY - i, image.getRGB(iw - 1, 0));
plot(canvas, rectX + ih - 1 + j, rectY - i, image.getRGB(iw - 1, ih - 1));
}
}
// Copy edge pixels into padding.
for (int i = 1; i <= amountY; i++) {
for (int j = 0; j < iw; j++) {
plot(canvas, rectX - i, rectY + iw - 1 - j, image.getRGB(j, 0));
plot(canvas, rectX + ih - 1 + i, rectY + iw - 1 - j, image.getRGB(j, ih - 1));
}
}
for (int i = 1; i <= amountX; i++) {
for (int j = 0; j < ih; j++) {
plot(canvas, rectX + j, rectY - i, image.getRGB(iw - 1, j));
plot(canvas, rectX + j, rectY + iw - 1 + i, image.getRGB(0, j));
}
}
} else {
// Copy corner pixels to fill corners of the padding.
for (int i = 1; i <= amountX; i++) {
for (int j = 1; j <= amountY; j++) {
plot(canvas, rectX - i, rectY - j, image.getRGB(0, 0));
plot(canvas, rectX - i, rectY + ih - 1 + j, image.getRGB(0, ih - 1));
plot(canvas, rectX + iw - 1 + i, rectY - j, image.getRGB(iw - 1, 0));
plot(canvas, rectX + iw - 1 + i, rectY + ih - 1 + j, image.getRGB(iw - 1, ih - 1));
}
}
// Copy edge pixels into padding.
for (int i = 1; i <= amountY; i++) {
copy(image, 0, 0, iw, 1, canvas, rectX, rectY - i, rect.rotated);
copy(image, 0, ih - 1, iw, 1, canvas, rectX, rectY + ih - 1 + i, rect.rotated);
}
for (int i = 1; i <= amountX; i++) {
copy(image, 0, 0, 1, ih, canvas, rectX - i, rectY, rect.rotated);
copy(image, iw - 1, 0, 1, ih, canvas, rectX + iw - 1 + i, rectY, rect.rotated);
}
}
}
copy(image, 0, 0, iw, ih, canvas, rectX, rectY, rect.rotated);
if (settings.debug) {
g.setColor(Color.magenta);
g.drawRect(rectX, rectY, rect.width - settings.paddingX - 1, rect.height - settings.paddingY - 1);
}
}
if (settings.bleed && !settings.premultiplyAlpha && !(settings.outputFormat.equalsIgnoreCase("jpg") || settings.outputFormat.equalsIgnoreCase("jpeg"))) {
canvas = new ColorBleedEffect().processImage(canvas, settings.bleedIterations);
g = (Graphics2D) canvas.getGraphics();
}
if (settings.debug) {
g.setColor(Color.magenta);
g.drawRect(0, 0, width - 1, height - 1);
}
ImageOutputStream ios = null;
try {
if (settings.outputFormat.equalsIgnoreCase("jpg") || settings.outputFormat.equalsIgnoreCase("jpeg")) {
BufferedImage newImage = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
newImage.getGraphics().drawImage(canvas, 0, 0, null);
canvas = newImage;
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = writers.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(settings.jpegQuality);
ios = ImageIO.createImageOutputStream(outputFile);
writer.setOutput(ios);
writer.write(null, new IIOImage(canvas, null, null), param);
} else {
if (settings.premultiplyAlpha)
canvas.getColorModel().coerceData(canvas.getRaster(), true);
ImageIO.write(canvas, "png", outputFile);
}
} catch (IOException ex) {
throw new RuntimeException("Error writing file: " + outputFile, ex);
} finally {
if (ios != null) {
try {
ios.close();
} catch (Exception ignored) {
}
}
}
}
}
use of java.awt.image.BufferedImage in project libgdx by libgdx.
the class ColorBleedEffect method processImage.
public BufferedImage processImage(BufferedImage image, int maxIterations) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage processedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int[] rgb = image.getRGB(0, 0, width, height, null, 0, width);
Mask mask = new Mask(rgb);
int iterations = 0;
int lastPending = -1;
while (mask.pendingSize > 0 && mask.pendingSize != lastPending && iterations < maxIterations) {
lastPending = mask.pendingSize;
executeIteration(rgb, mask, width, height);
iterations++;
}
processedImage.setRGB(0, 0, width, height, rgb, 0, width);
return processedImage;
}
use of java.awt.image.BufferedImage in project libgdx by libgdx.
the class ImageProcessor method addImage.
/** The image won't be kept in-memory during packing if {@link Settings#limitMemory} is true. */
public void addImage(File file) {
BufferedImage image;
try {
image = ImageIO.read(file);
} catch (IOException ex) {
throw new RuntimeException("Error reading image: " + file, ex);
}
if (image == null)
throw new RuntimeException("Unable to read image: " + file);
String name = file.getAbsolutePath().replace('\\', '/');
// Strip root dir off front of image path.
if (rootPath != null) {
if (!name.startsWith(rootPath))
throw new RuntimeException("Path '" + name + "' does not start with root: " + rootPath);
name = name.substring(rootPath.length());
}
// Strip extension.
int dotIndex = name.lastIndexOf('.');
if (dotIndex != -1)
name = name.substring(0, dotIndex);
Rect rect = addImage(image, name);
if (rect != null && settings.limitMemory)
rect.unloadImage(file);
}
use of java.awt.image.BufferedImage in project h2o-2 by h2oai.
the class MnistCanvas method paint.
@Override
public void paint(Graphics g) {
Layer[] ls = _trainer.layers();
Vec[] vecs = ((VecsInput) ls[0]).vecs;
// Vec resp = ((VecSoftmax) ls[ls.length - 1]).vec;
int edge = 56, pad = 10;
int rand = _rand.nextInt((int) vecs[0].length());
// Side
{
BufferedImage in = new BufferedImage(EDGE, EDGE, BufferedImage.TYPE_INT_RGB);
WritableRaster r = in.getRaster();
// Input
int[] pix = new int[PIXELS];
for (int i = 0; i < pix.length; i++) pix[i] = (int) (vecs[i].at8(rand));
r.setDataElements(0, 0, EDGE, EDGE, pix);
g.drawImage(in, pad, pad, null);
// Labels
// g.drawString("" + resp.at8(rand), 10, 50);
// g.drawString("RBM " + _level, 10, 70);
}
// Outputs
int offset = pad;
// float[] visible = new float[MnistNeuralNetTest.PIXELS];
// System.arraycopy(_images, rand * MnistNeuralNetTest.PIXELS, visible, 0, MnistNeuralNetTest.PIXELS);
// for( int i = 0; i <= _level; i++ ) {
// for( int pass = 0; pass < 10; pass++ ) {
// if( i == _level ) {
// int[] output = new int[visible.length];
// for( int v = 0; v < visible.length; v++ )
// output[v] = (int) Math.min(visible[v] * 255, 255);
// BufferedImage out = new BufferedImage(MnistNeuralNetTest.EDGE, MnistNeuralNetTest.EDGE,
// BufferedImage.TYPE_INT_RGB);
// WritableRaster r = out.getRaster();
// r.setDataElements(0, 0, MnistNeuralNetTest.EDGE, MnistNeuralNetTest.EDGE, output);
// BufferedImage image = new BufferedImage(edge, edge, BufferedImage.TYPE_INT_RGB);
// Graphics2D ig = image.createGraphics();
// ig.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
// ig.clearRect(0, 0, edge, edge);
// ig.drawImage(out, 0, 0, edge, edge, null);
// ig.dispose();
// g.drawImage(image, pad * 2 + MnistNeuralNetTest.EDGE, offset, null);
// offset += pad + edge;
// }
// if( _ls[i]._v != null ) {
// float[] hidden = new float[_ls[i]._b.length];
// _ls[i].forward(visible, hidden);
// visible = _ls[i].generate(hidden);
// }
// }
// float[] t = new float[_ls[i]._b.length];
// _ls[i].forward(visible, t);
// visible = t;
// }
// Weights
int buf = EDGE + pad + pad;
Layer layer = ls[_level];
double mean = 0;
int n = layer._w.length;
for (int i = 0; i < n; i++) mean += layer._w[i];
mean /= layer._w.length;
double sigma = 0;
for (int i = 0; i < layer._w.length; i++) {
double d = layer._w[i] - mean;
sigma += d * d;
}
sigma = Math.sqrt(sigma / (layer._w.length - 1));
for (int o = 0; o < layer._b.length; o++) {
if (o % 10 == 0) {
offset = pad;
buf += pad + edge;
}
int[] start = new int[layer._previous._a.length];
for (int i = 0; i < layer._previous._a.length; i++) {
double w = layer._w[o * layer._previous._a.length + i];
w = ((w - mean) / sigma) * 200;
if (w >= 0)
//GREEN
start[i] = ((int) Math.min(+w, 255)) << 8;
else
//RED
start[i] = ((int) Math.min(-w, 255)) << 16;
}
BufferedImage out = new BufferedImage(EDGE, EDGE, BufferedImage.TYPE_INT_RGB);
WritableRaster r = out.getRaster();
r.setDataElements(0, 0, EDGE, EDGE, start);
BufferedImage resized = new BufferedImage(edge, edge, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resized.createGraphics();
try {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.clearRect(0, 0, edge, edge);
g2.drawImage(out, 0, 0, edge, edge, null);
} finally {
g2.dispose();
}
g.drawImage(resized, buf, offset, null);
offset += pad + edge;
}
}
use of java.awt.image.BufferedImage in project h2o-3 by h2oai.
the class EasyPredictModelWrapper method fillRawData.
private double[] fillRawData(RowData data, double[] rawData) throws PredictException {
// TODO: refactor
boolean isImage = m instanceof DeepwaterMojoModel && ((DeepwaterMojoModel) m)._problem_type.equals("image");
boolean isText = m instanceof DeepwaterMojoModel && ((DeepwaterMojoModel) m)._problem_type.equals("text");
for (String dataColumnName : data.keySet()) {
Integer index = modelColumnNameToIndexMap.get(dataColumnName);
// Skip the "response" column which should not be included in `rawData`
if (index == null || index >= rawData.length) {
continue;
}
BufferedImage img = null;
String[] domainValues = m.getDomainValues(index);
if (domainValues == null) {
// Column is either numeric or a string (for images or text)
double value = Double.NaN;
Object o = data.get(dataColumnName);
if (o instanceof String) {
String s = ((String) o).trim();
// Url to an image given
if (isImage) {
boolean isURL = s.matches("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
try {
img = isURL ? ImageIO.read(new URL(s)) : ImageIO.read(new File(s));
} catch (IOException e) {
throw new PredictException("Couldn't read image from " + s);
}
} else if (isText) {
// TODO: use model-specific vectorization of text
throw new PredictException("MOJO scoring for text classification is not yet implemented.");
} else {
// numeric
try {
value = Double.parseDouble(s);
} catch (NumberFormatException nfe) {
if (!convertInvalidNumbersToNa)
throw new PredictNumberFormatException("Unable to parse value: " + s + ", from column: " + dataColumnName + ", as Double; " + nfe.getMessage());
}
}
} else if (o instanceof Double) {
value = (Double) o;
} else if (o instanceof byte[] && isImage) {
// Read the image from raw bytes
InputStream is = new ByteArrayInputStream((byte[]) o);
try {
img = ImageIO.read(is);
} catch (IOException e) {
throw new PredictException("Couldn't interpret raw bytes as an image.");
}
} else {
throw new PredictUnknownTypeException("Unexpected object type " + o.getClass().getName() + " for numeric column " + dataColumnName);
}
if (isImage && img != null) {
DeepwaterMojoModel dwm = (DeepwaterMojoModel) m;
int W = dwm._width;
int H = dwm._height;
int C = dwm._channels;
float[] _destData = new float[W * H * C];
try {
GenModel.img2pixels(img, W, H, C, _destData, 0, dwm._meanImageData);
} catch (IOException e) {
e.printStackTrace();
throw new PredictException("Couldn't vectorize image.");
}
rawData = new double[_destData.length];
for (int i = 0; i < rawData.length; ++i) rawData[i] = _destData[i];
return rawData;
}
rawData[index] = value;
} else {
// Column has categorical value.
Object o = data.get(dataColumnName);
double value;
if (o instanceof String) {
String levelName = (String) o;
HashMap<String, Integer> columnDomainMap = domainMap.get(index);
Integer levelIndex = columnDomainMap.get(levelName);
if (levelIndex == null) {
levelIndex = columnDomainMap.get(dataColumnName + "." + levelName);
}
if (levelIndex == null) {
if (convertUnknownCategoricalLevelsToNa) {
value = Double.NaN;
unknownCategoricalLevelsSeenPerColumn.get(dataColumnName).incrementAndGet();
} else {
throw new PredictUnknownCategoricalLevelException("Unknown categorical level (" + dataColumnName + "," + levelName + ")", dataColumnName, levelName);
}
} else {
value = levelIndex;
}
} else if (o instanceof Double && Double.isNaN((double) o)) {
//Missing factor is the only Double value allowed
value = (double) o;
} else {
throw new PredictUnknownTypeException("Unexpected object type " + o.getClass().getName() + " for categorical column " + dataColumnName);
}
rawData[index] = value;
}
}
return rawData;
}
Aggregations