Java: implementation of Gaussian Blur - java

I need to implement Gaussian Blur in Java for 3x3, 5x5 and 7x7 matrix. Can you correct me if I'm wrong:
I've a matrix(M) 3x3 (middle value is M(0, 0)):
1 2 1
2 4 2
1 2 1
I take one pixel(P) from image and for each nearest pixel:
s = M(-1, -1) * P(-1, -1) + M(-1, 0) * P(-1, 0) + ... + M(1, 1) * P(1, 1)
An then division it total value of matrix:
P'(i, j) = s / M(-1, -1) + M(-1, 0) + ... + M(1, 1)
That's all that my program do. I leave extreme pixels not changed.
My program:
for(int i = 1; i < height - 1; i++){
for(int j = 1; j < width - 1; j++){
int sum = 0, l = 0;
for(int m = -1; m <= 1; m++){
for(int n = -1; n <= 1; n++){
try{
System.out.print(l + " ");
sum += mask3[l++] * Byte.toUnsignedInt((byte) source[(i + m) * height + j + n]);
} catch(ArrayIndexOutOfBoundsException e){
int ii = (i + m) * height, jj = j + n;
System.out.println("Pixels[" + ii + "][" + jj + "] " + i + ", " + j);
System.exit(0);
}
}
System.out.println();
}
System.out.println();
output[i * width + j] = sum / maskSum[0];
}
}
I get source from a BufferedImage like this:
int[] source = image.getRGB(0, 0, width, height, null, 0, width);
So for this image:
Result is this:
Can you describe me, what is wrong with my program?

First of all, your formula for calculating the index in the source array is wrong. The image data is stored in the array one pixel row after the other. Therefore the index given x and y is calculated like this:
index = x + y * width
Furthermore the color channels are stored in different bits of the int cannot simply do the calculations with the whole int, since this allows channels to influence other channels.
The following solution should work (even though it just leaves the pixels at the bounds transparent):
public static BufferedImage blur(BufferedImage image, int[] filter, int filterWidth) {
if (filter.length % filterWidth != 0) {
throw new IllegalArgumentException("filter contains a incomplete row");
}
final int width = image.getWidth();
final int height = image.getHeight();
final int sum = IntStream.of(filter).sum();
int[] input = image.getRGB(0, 0, width, height, null, 0, width);
int[] output = new int[input.length];
final int pixelIndexOffset = width - filterWidth;
final int centerOffsetX = filterWidth / 2;
final int centerOffsetY = filter.length / filterWidth / 2;
// apply filter
for (int h = height - filter.length / filterWidth + 1, w = width - filterWidth + 1, y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int r = 0;
int g = 0;
int b = 0;
for (int filterIndex = 0, pixelIndex = y * width + x;
filterIndex < filter.length;
pixelIndex += pixelIndexOffset) {
for (int fx = 0; fx < filterWidth; fx++, pixelIndex++, filterIndex++) {
int col = input[pixelIndex];
int factor = filter[filterIndex];
// sum up color channels seperately
r += ((col >>> 16) & 0xFF) * factor;
g += ((col >>> 8) & 0xFF) * factor;
b += (col & 0xFF) * factor;
}
}
r /= sum;
g /= sum;
b /= sum;
// combine channels with full opacity
output[x + centerOffsetX + (y + centerOffsetY) * width] = (r << 16) | (g << 8) | b | 0xFF000000;
}
}
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
result.setRGB(0, 0, width, height, output, 0, width);
return result;
}
int[] filter = {1, 2, 1, 2, 4, 2, 1, 2, 1};
int filterWidth = 3;
BufferedImage blurred = blur(img, filter, filterWidth);

Related

scrambled block trying to decompress BC1 texture compression

I've been trying to implement a BC1 (DXT1) decompression algorithm in Java. Everything seems to work pretty precise but I've ran into problem with some blocks around transparent ones. I've been trying to resolve it for a few hours without success.
In short, after decompressing all blocks everything looks good except for the blocks whose are around transparent ones. During the development I've been checking results with results from DirectXTex (texconv) which is written in C++.
This is my result compared to DirectXTex one:
Here is the code I'm using:
BufferedImage decompress(byte[] buffer, int width, int height)
and implementation:
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int[] scanline = new int[4 * width]; //stores 4 horizontal lines (width/4 blocks)
RGBA[] blockPalette = new RGBA[4]; //stores RGBA values of current block
int bufferOffset = 0;
for (int row = 0; row < height / 4; row++) {
for (int col = 0; col < width / 4; col++) {
short rgb0 = Short.reverseBytes(Bytes.getShort(buffer, bufferOffset));
short rgb1 = Short.reverseBytes(Bytes.getShort(buffer, bufferOffset + 2));
int bitmap = Integer.reverseBytes(Bytes.getInt(buffer, bufferOffset + 4));
bufferOffset += 8;
blockPalette[0] = R5G6B5.decode(rgb0);
blockPalette[1] = R5G6B5.decode(rgb1);
if(rgb0 <= rgb1) {
int c2r = (blockPalette[0].getRed() + blockPalette[1].getRed()) / 2;
int c2g = (blockPalette[0].getGreen() + blockPalette[1].getGreen()) / 2;
int c2b = (blockPalette[0].getBlue() + blockPalette[1].getBlue()) / 2;
blockPalette[2] = new RGBA(c2r, c2g, c2b, 255);
blockPalette[3] = new RGBA(0, 0, 0, 0);
} else {
int c2r = (2 * blockPalette[0].getRed() + blockPalette[1].getRed()) / 3;
int c2g = (2 * blockPalette[0].getGreen() + blockPalette[1].getGreen()) / 3;
int c2b = (2 * blockPalette[0].getBlue() + blockPalette[1].getBlue()) / 3;
int c3r = (blockPalette[0].getRed() + 2 * blockPalette[1].getRed()) / 3;
int c3g = (blockPalette[0].getGreen() + 2 * blockPalette[1].getGreen()) / 3;
int c3b = (blockPalette[0].getBlue() + 2 * blockPalette[1].getBlue()) / 3;
blockPalette[2] = new RGBA(c2r, c2g, c2b, 255);
blockPalette[3] = new RGBA(c3r, c3g, c3b, 255);
}
for (int i = 0; i < 16; i++, bitmap >>= 2) {
int pi = (i / 4) * width + (col * 4 + i % 4);
int index = bitmap & 3;
scanline[pi] = A8R8G8B8.encode(blockPalette[index]);
}
}
//copy scanline to buffered image
result.setRGB(0, row * 4, width, 4, scanline, 0, width);
}
return result;
Does anyone have idea where is the problem? I've been doing exactly the same steps as specification says: Block Compression (Direct3D 10)
Is it that blockPalette[2].set(c2r, c2g, c2b); should be blockPalette[2].set(c2r, c2g, c2b, 255);? (in two locations)
For those who are interested, I've found that the problem was in comparing short values.
I've just changed:
if(rgb0 <= rgb1) {
to either
if(Short.compareUnsigned(rgb0, rgb1) <= 0) {
or
if((rgb0 & 0xffff) <= (rgb1 & 0xffff)) {
and this ensures that color values are compared as unsigned shorts (positive integers).

Translating C library to Java: Getting mangled garbage data in top-left of resulting bitmap

The LWJGL3 library contains bindings to STB TrueType and other libraries made by Sean Barrett.
In order to modify the packing API provided by this library to render SDF glyphs into the backing texture instead of normal bitmaps, I am reproducing the texture-rendering code from the library in java.
I managed to get it to almost work but I am hitting a stumbling stone where I am getting mangled garbage data for the very top-left corner of the texture. I am somewhat confident that the error must be located somewhere in the code for my version of the stbtt__h_prefilter(...), as this is where the assertion fails.
Edit: I forgot to take into consideration the current buffer position when doing read/write operations on the buffer. Now I still have some garbage data in the bitmap, but it's more evenly distributed.
In fact looking at the updated second picture it seems that somehow the very left-most part of every glyph is shifted half the glyph height down. I cannot find out where or why it happens, especially considering that the bitmap processing works on each glyph individually after it is rendered into the font, so to my understanding the next line of glyphs should just overwrite this..?
Bitmap generated by the original library:
Bitmap generated by my version (see the offset half-lines cutting into some letters):
Addendum: Bitmap generated by my version without the prefilter_... methods:
Below you find my versions of the methods from the library. The originals can be found here.
The references to STB... functions refer to the generated bindings form lwjgl3.
private static boolean packFontRangesRenderIntoRectsSDF(
STBTTPackContext context, STBTTFontinfo fontinfo,
STBTTPackRange.Buffer ranges, STBRPRect.Buffer rects) {
int i, j, k;
boolean returnValue = true;
int curr_hOversample = context.h_oversample();
int curr_vOversample = context.v_oversample();
k = 0;
for(i = 0 ; i < ranges.remaining() ; i++) {
float fh = ranges.get(i).font_size();
float scale = fh > 0.0f ? stbtt_ScaleForPixelHeight(fontinfo, fh) : stbtt_ScaleForMappingEmToPixels(fontinfo, -fh);
float recip_h, recip_v, sub_x, sub_y;
curr_hOversample = STBTTPackRange.nh_oversample(ranges.get(i).address()) & 0xFF;
curr_vOversample = STBTTPackRange.nv_oversample(ranges.get(i).address()) & 0xFF;
recip_h = 1.0f / (float)curr_hOversample;
recip_v = 1.0f / (float)curr_vOversample;
sub_x = __oversample_shift(curr_hOversample);
sub_y = __oversample_shift(curr_vOversample);
for(j = 0 ; j < ranges.get(i).num_chars() ; j++) {
STBRPRect r = rects.get(k);
if(r.was_packed()) {
STBTTPackedchar bc = ranges.get(i).chardata_for_range().get(j);
IntBuffer advance = ByteBuffer.allocateDirect(Integer.BYTES)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
IntBuffer lsb = ByteBuffer.allocateDirect(Integer.BYTES)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
IntBuffer x0 = ByteBuffer.allocateDirect(Integer.BYTES)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
IntBuffer x1 = ByteBuffer.allocateDirect(Integer.BYTES)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
IntBuffer y0 = ByteBuffer.allocateDirect(Integer.BYTES)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
IntBuffer y1 = ByteBuffer.allocateDirect(Integer.BYTES)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
int codepoint = ranges.get(i).array_of_unicode_codepoints() == null ? ranges.get(i).first_unicode_codepoint_in_range() + j : ranges.get(i).array_of_unicode_codepoints().get(j);
int glyph = stbtt_FindGlyphIndex(fontinfo, codepoint);
int pad = context.padding();
r.x((short) (r.x() + pad));
r.y((short) (r.y() + pad));
r.w((short) (r.w() - pad));
r.h((short) (r.h() - pad));
stbtt_GetGlyphHMetrics(fontinfo, glyph, advance, lsb);
stbtt_GetGlyphBitmapBox(fontinfo, glyph,
scale * curr_hOversample,
scale * curr_vOversample,
x0, y0, x1, y1);
//TODO replace below with SDF func
ByteBuffer buff = context.pixels(context.height() * context.width());
buff.position(r.x() + r.y() * context.stride_in_bytes());
stbtt_MakeGlyphBitmapSubpixel(fontinfo, buff,
r.w() - curr_hOversample + 1,
r.h() - curr_vOversample + 1,
context.stride_in_bytes(),
scale * curr_hOversample,
scale * curr_vOversample,
0, 0,
glyph);
if(curr_hOversample > 1) {
//FIXME __h_prefilter(..) function
buff.position(r.x() + r.y() * context.stride_in_bytes());
__h_prefilter(buff,
r.w(), r.h(), context.stride_in_bytes(),
curr_hOversample);
}
if(curr_vOversample > 1) {
//FIXME __v_prefilter(..) function
buff.position(r.x() + r.y() * context.stride_in_bytes());
__v_prefilter(buff,
r.w(), r.h(), context.stride_in_bytes(),
curr_vOversample);
}
bc.x0(r.x());
bc.y0(r.y());
bc.x1((short) (r.x() + r.w()));
bc.y1((short) (r.y() + r.h()));
bc.xadvance(scale * advance.get(0));
bc.xoff((float) (x0.get(0) * recip_h + sub_x));
bc.yoff((float) (y0.get(0) * recip_v + sub_y));
bc.xoff2((x0.get(0) + r.w()) * recip_h + sub_x);
bc.yoff2((y0.get(0) + r.h()) * recip_v + sub_y);
} else {
returnValue = false;
}
++k;
}
}
return returnValue;
}
//copy of stbtt__oversample_shift(..) as it's inaccessible
private static float __oversample_shift(int oversample) {
if(oversample == 0) {
return 0.0f;
}
return (float)-(oversample - 1) / (2.0f * (float)oversample);
}
private static final int MAX_OVERSAMPLE = 8;
private static final int __OVER_MASK = MAX_OVERSAMPLE - 1;
private static void __h_prefilter(ByteBuffer pixels, int w, int h, int stride_in_bytes, int kernel_width) {
final int pixels_offset = pixels.position();
int pixelstride = 0;
byte[] buffer = new byte[MAX_OVERSAMPLE];
int safe_w = w - kernel_width;
int j;
Arrays.fill(buffer, 0, MAX_OVERSAMPLE, (byte)0);
for(j = 0 ; j < h ; j++) {
int i;
int total;
Arrays.fill(buffer, 0, kernel_width, (byte)0);
total = 0;
for(i = 0 ; i <= safe_w ; i++) {
total += Byte.toUnsignedInt(pixels.get(pixels_offset + (pixelstride + i))) - Byte.toUnsignedInt(buffer[i & __OVER_MASK]);
buffer[(i + kernel_width) & __OVER_MASK] = pixels.get(pixels_offset + (pixelstride + i));
pixels.put(pixels_offset + (pixelstride + i), (byte) Integer.divideUnsigned(total, kernel_width));
}
for(; i < w ; ++i) {
// if(Byte.toUnsignedInt(pixels.get(pixels_offset + (pixelstride + i))) != 0) {
// throw new RuntimeException("Expected '0' but was '" + Byte.toUnsignedInt(pixels.get(pixels_offset + (pixelstride + i))) + "'");
// }
total -= Byte.toUnsignedInt(buffer[i & __OVER_MASK]);
pixels.put(pixels_offset + (pixelstride + i), (byte) Integer.divideUnsigned(total, kernel_width));
}
pixelstride += stride_in_bytes;
}
}
private static void __v_prefilter(ByteBuffer pixels, int w, int h, int stride_in_bytes, int kernel_width) {
final int pixels_offset = pixels.position();
int pixelstride = 0;
byte[] buffer = new byte[MAX_OVERSAMPLE];
int safe_h = h - kernel_width;
int j;
Arrays.fill(buffer, 0, MAX_OVERSAMPLE, (byte)0);
for(j = 0 ; j < w ; j++) {
int i;
int total;
Arrays.fill(buffer, 0, kernel_width, (byte)0);
total = 0;
for(i = 0 ; i <= safe_h ; i++) {
total += Byte.toUnsignedInt(pixels.get(pixels_offset + ((pixelstride + i) * stride_in_bytes))) - Byte.toUnsignedInt(buffer[i & __OVER_MASK]);
buffer[(i + kernel_width) & __OVER_MASK] = pixels.get(pixels_offset + ((pixelstride + i) * stride_in_bytes));
pixels.put(pixels_offset + ((pixelstride + i) * stride_in_bytes), (byte) Integer.divideUnsigned(total, kernel_width));
}
for(; i < h ; ++i) {
// if(Byte.toUnsignedInt(pixels.get(pixels_offset + ((pixelstride + i) * stride_in_bytes))) != 0) {
// throw new RuntimeException("Expected '0' but was '" + Byte.toUnsignedInt(pixels.get(pixels_offset + ((pixelstride + i) * stride_in_bytes))) + "'");
// }
total -= Byte.toUnsignedInt(buffer[i & __OVER_MASK]);
pixels.put(pixels_offset + ((pixelstride + i) * stride_in_bytes), (byte) Integer.divideUnsigned(total, kernel_width));
}
pixelstride += 1;
}
}
It seems to work out fine when I remove the offset from the __v_prefilter(..) method.
Thus changing final int pixels_offset = pixels.position(); to final int pixels_offset = 0; (or removing it altogether from the code).
I say it seems because I have not done any bitwise comparisons of the produced maps between my, now working, and the original code. There are just no, to me at least, discernible mangled bits in the texture anymore.

How to fix java.lang.ArrayIndexOutOfBoundsException image resizing error?

I have little experience with java programming, but I know my way around it a little. I want to pick up a project that was left behind by someone else. I was doing well fixing other errors here and there, but this one stumped me. Here it is:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at Replacer.main(Replacer.java:19)
To my surprise, the program still opened. However, when I tried to open a picture, this happened, and displayed a picture of 0 x 0 pixels:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:
2147483647
at ImageEditor.resize(ImageEditor.java:384)
at ImageEditor.resize(ImageEditor.java:308)
at ImageFrame.setImage(ImageFrame.java:438)
at ImageFrame.actionPerformed(ImageFrame.java:765)
at java.awt.Button.processActionEvent(Unknown Source)
at java.awt.Button.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionP
rivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionP
rivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionP
rivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Replacer:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.PrintStream;
import javax.imageio.ImageIO;
public class Replacer
{
public static void main(String[] args)
{
BufferedImage i = null;
BufferedImage i2 = null;
Color[][] blockColors = new Color[16][16];
ImageFrame b = new ImageFrame(i);
try
{
i2 = ImageIO.read(new File("terrain.png"));
int blockSize = i2.getWidth(b) / 16;
System.out.println("Analyzing terrain.png");
int[] buffer = ImageEditor.returnBuffer(i2, b);
int width = i2.getWidth(b);
for (int j = 0; j < 16; j++) {
for (int k = 0; k < 16; k++) {
if ((j <= 2) || (k <= 8))
{
int[] i3 = ImageEditor.crop(buffer, width, width, b, j * blockSize, k * blockSize, blockSize, blockSize);
blockColors[j][k] = ImageEditor.getAverageColor(i3, b);
}
}
}
Color[] c2 = new Color[100];
c2[0] = blockColors[1][8];
c2[1] = blockColors[2][10];
c2[2] = blockColors[1][11];
c2[3] = blockColors[1][9];
c2[4] = blockColors[1][7];
c2[5] = blockColors[0][4];
c2[6] = blockColors[2][13];
c2[7] = blockColors[1][13];
c2[8] = blockColors[1][12];
c2[9] = blockColors[2][7];
c2[10] = blockColors[2][11];
c2[11] = blockColors[2][8];
c2[12] = blockColors[2][9];
c2[13] = blockColors[2][12];
c2[14] = blockColors[1][14];
c2[15] = blockColors[1][10];
c2[16] = blockColors[1][0];
c2[17] = blockColors[2][0];
c2[18] = blockColors[2][1];
c2[19] = blockColors[3][1];
c2[20] = blockColors[8][4];
c2[21] = blockColors[5][2];
c2[22] = blockColors[4][2];
c2[23] = blockColors[6][7];
c2[24] = blockColors[4][0];
c2[25] = blockColors[0][1];
c2[26] = blockColors[0][11];
c2[27] = blockColors[7][0];
c2[28] = blockColors[6][1];
c2[29] = blockColors[7][1];
c2[30] = blockColors[8][1];
c2[31] = blockColors[0][9];
c2[32] = blockColors[10][4];
c2[33] = blockColors[9][6];
c2[34] = blockColors[7][6];
c2[35] = blockColors[8][6];
c2[36] = blockColors[2][4];
c2[37] = blockColors[6][3];
c2[38] = blockColors[1][1];
c2[39] = blockColors[5][1];
c2[40] = blockColors[4][1];
c2[41] = blockColors[4][7];
c2[42] = blockColors[5][7];
c2[43] = blockColors[0][3];
c2[44] = blockColors[3][4];
c2[45] = blockColors[8][8];
c2[46] = blockColors[8][9];
c2[47] = blockColors[8][10];
c2[48] = blockColors[8][11];
c2[49] = blockColors[8][12];
for (int j = 0; j < c2.length / 2; j++)
{
double shadowRed = 0.892D * c2[j].getRed() + 0.5D;
double shadowGreen = 0.892D * c2[j].getGreen() + 0.5D;
double shadowBlue = 0.892D * c2[j].getBlue() + 0.5D;
c2[(50 + j)] = new Color((int)shadowRed, (int)shadowGreen, (int)shadowBlue);
}
for (int j = 0; j < c2.length; j++) {
System.out.println("colors[" + j + "] = new Color(" + c2[j].getRed() + "," + c2[j].getGreen() + "," + c2[j].getBlue() + ");");
}
b.setColors(c2);
System.out.println("Done");
}
catch (Exception e)
{
e.printStackTrace();
}
b.repaint();
}
}
ImageEditor:
import java.awt.Color;
import java.awt.Component;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import java.io.PrintStream;
public class ImageEditor
{
public static int[] returnBuffer(Image i, Component c)
{
MediaTracker tracker = new MediaTracker(c);
tracker.addImage(i, 0);
try
{
tracker.waitForAll();
}
catch (Exception e)
{
System.out.println("Image loading interrupted");
}
int width = i.getWidth(c);
int height = i.getHeight(c);
int[] buffer = new int[width * height];
PixelGrabber grabber = new PixelGrabber(i, 0, 0, width, height, buffer, 0, width);
try
{
grabber.grabPixels();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return buffer;
}
public static Image simplifyColors(int width, int height, int[] buffer, Component c, Color[] colors)
{
double[] w = new double[colors.length];
for (int k = 0; k < w.length; k++) {
w[k] = 1.0D;
}
return simplifyColors(width, height, buffer, c, colors, w);
}
public static Image simplifyColors(int width, int height, int[] buffer, Component c, Color[] colors, double[] weights)
{
int[] simple = new int[buffer.length];
for (int j = 0; j < buffer.length; j++)
{
int minDiff = 10000000;
Color current = new Color(buffer[j], true);
Color col = Color.black;
for (int k = 0; k < colors.length; k++)
{
Color test = colors[k];
double w = weights[k];
if (test != null)
{
int diff = (int)((Math.pow(test.getRed() - current.getRed(), 2.0D) + Math.pow(test.getGreen() - current.getGreen(), 2.0D) + Math.pow(test.getBlue() - current.getBlue(), 2.0D)) / w);
if (diff < minDiff)
{
col = test;
minDiff = diff;
}
}
}
if (current.getAlpha() >= 128) {
simple[j] = col.getRGB();
} else {
simple[j] = new Color(255, 255, 255, 0).getRGB();
}
}
return c.createImage(new MemoryImageSource(width, height, simple, 0, width));
}
public static Image simplifyColors2(Image i, int[] buffer, Component c, Color[] colors)
{
double[] w = new double[colors.length];
for (int k = 0; k < w.length; k++) {
w[k] = 1.0D;
}
return simplifyColors2(i, buffer, c, colors, w);
}
public static Image simplifyColors2(Image i, int[] buffer, Component c, Color[] colors, double[] weights)
{
int height = i.getHeight(c);
int width = i.getWidth(c);
int[] simple = new int[buffer.length];
float[] hsb1 = new float[3];
float[] hsb2 = new float[3];
for (int j = 0; j < buffer.length; j++)
{
int minDiff = 10000000;
Color current = new Color(buffer[j], true);
hsb1 = Color.RGBtoHSB(current.getRed(), current.getGreen(), current.getBlue(), null);
Color col = Color.black;
for (int k = 0; k < colors.length; k++)
{
Color test = colors[k];
if (test != null)
{
hsb2 = Color.RGBtoHSB(test.getRed(), test.getGreen(), test.getBlue(), null);
int diff = (int)(Math.pow(hsb1[0] - hsb2[0], 2.0D) + Math.pow(hsb1[1] - hsb2[1], 2.0D) + Math.pow(hsb1[2] - hsb2[2], 2.0D));
if (diff < minDiff)
{
col = test;
minDiff = diff;
}
}
}
if (current.getAlpha() >= 128) {
simple[j] = col.getRGB();
} else {
simple[j] = new Color(255, 255, 255, 0).getRGB();
}
}
return c.createImage(new MemoryImageSource(width, height, simple, 0, width));
}
public static Image simplifyColors3(int width, int height, int[] buffer2, Component c, Color[] colors, double[] weights)
{
int[] buffer = (int[])buffer2.clone();
int[] simple = new int[buffer.length];
for (int j = 0; j < buffer.length; j++)
{
int minDiff = 10000000;
Color current = new Color(buffer[j], true);
Color col = Color.black;
for (int k = 0; k < colors.length; k++)
{
if (current.getAlpha() == 0)
{
col = new Color(255, 255, 255, 0);
break;
}
Color test = colors[k];
double w = weights[k];
if (test != null)
{
int diff = (int)((Math.pow(test.getRed() - current.getRed(), 2.0D) + Math.pow(test.getGreen() - current.getGreen(), 2.0D) + Math.pow(test.getBlue() - current.getBlue(), 2.0D)) / w);
if (diff < minDiff)
{
col = test;
minDiff = diff;
}
}
}
int quantErrorR = current.getRed() - col.getRed();
int quantErrorG = current.getGreen() - col.getGreen();
int quantErrorB = current.getBlue() - col.getBlue();
if ((j + 1) % width != 0)
{
Color x = new Color(buffer[(j + 1)], true);
Color y = new Color(Math.max(0, Math.min(x.getRed() + col.getAlpha() / 255 * quantErrorR * 7 / 16, 255)), Math.max(0, Math.min(x.getGreen() + col.getAlpha() / 255 * quantErrorG * 7 / 16, 255)), Math.max(0, Math.min(x.getBlue() + col.getAlpha() / 255 * quantErrorB * 7 / 16, 255)), x.getAlpha());
buffer[(j + 1)] = y.getRGB();
}
if (((j - 1) % width != 0) && (j - 1 + width < buffer.length))
{
Color x = new Color(buffer[(j - 1 + width)], true);
Color y = new Color(Math.max(0, Math.min(x.getRed() + col.getAlpha() / 255 * quantErrorR * 3 / 16, 255)), Math.max(0, Math.min(x.getGreen() + col.getAlpha() / 255 * quantErrorG * 3 / 16, 255)), Math.max(0, Math.min(x.getBlue() + col.getAlpha() / 255 * quantErrorB * 3 / 16, 255)), x.getAlpha());
buffer[(j - 1 + width)] = y.getRGB();
}
if (j + width < buffer.length)
{
Color x = new Color(buffer[(j + width)], true);
Color y = new Color(Math.max(0, Math.min(x.getRed() + col.getAlpha() / 255 * quantErrorR * 5 / 16, 255)), Math.max(0, Math.min(x.getGreen() + col.getAlpha() / 255 * quantErrorG * 5 / 16, 255)), Math.max(0, Math.min(x.getBlue() + col.getAlpha() / 255 * quantErrorB * 5 / 16, 255)), x.getAlpha());
buffer[(j + width)] = y.getRGB();
}
if (((j + 1) % width != 0) && (j + 1 + width < buffer.length))
{
Color x = new Color(buffer[(j + 1 + width)], true);
Color y = new Color(Math.max(0, Math.min(x.getRed() + col.getAlpha() / 255 * quantErrorR * 1 / 16, 255)), Math.max(0, Math.min(x.getGreen() + col.getAlpha() / 255 * quantErrorG * 1 / 16, 255)), Math.max(0, Math.min(x.getBlue() + col.getAlpha() / 255 * quantErrorB * 1 / 16, 255)), x.getAlpha());
buffer[(j + 1 + width)] = y.getRGB();
}
if (current.getAlpha() >= 128) {
simple[j] = col.getRGB();
} else {
simple[j] = new Color(255, 255, 255, 0).getRGB();
}
}
return c.createImage(new MemoryImageSource(width, height, simple, 0, width));
}
public static Image shadowColors(int width, int height, int[] buffer, Component c, Color[] colors, double[] weights)
{
int[] simple = new int[buffer.length];
double k2 = 0.0D;
for (int j = 0; j < buffer.length; j++)
{
int minDiff = 10000000;
Color current = new Color(buffer[j], true);
Color col = Color.black;
for (int k = 0; k < colors.length; k++)
{
Color test = colors[k];
double w = weights[k];
if (test != null)
{
int diff = (int)((Math.pow(test.getRed() - current.getRed(), 2.0D) + Math.pow(test.getGreen() - current.getGreen(), 2.0D) + Math.pow(test.getBlue() - current.getBlue(), 2.0D)) / w);
if (diff < minDiff)
{
col = test;
k2 = k;
minDiff = diff;
}
}
}
if (current.getAlpha() >= 128)
{
if (k2 < colors.length / 2) {
simple[j] = Color.WHITE.getRGB();
} else {
simple[j] = Color.BLACK.getRGB();
}
}
else {
simple[j] = new Color(255, 255, 255, 0).getRGB();
}
}
return c.createImage(new MemoryImageSource(width, height, simple, 0, width));
}
public static Image shadowColors3(int width, int height, int[] buffer2, Component c, Color[] colors, double[] weights)
{
int[] buffer = (int[])buffer2.clone();
int[] simple = new int[buffer.length];
double k2 = 0.0D;
for (int j = 0; j < buffer.length; j++)
{
int minDiff = 10000000;
Color current = new Color(buffer[j], true);
Color col = Color.black;
for (int k = 0; k < colors.length; k++)
{
if (current.getAlpha() == 0)
{
col = new Color(255, 255, 255, 0);
break;
}
Color test = colors[k];
double w = weights[k];
if (test != null)
{
int diff = (int)((Math.pow(test.getRed() - current.getRed(), 2.0D) + Math.pow(test.getGreen() - current.getGreen(), 2.0D) + Math.pow(test.getBlue() - current.getBlue(), 2.0D)) / w);
if (diff < minDiff)
{
col = test;
minDiff = diff;
k2 = k;
}
}
}
int quantErrorR = current.getRed() - col.getRed();
int quantErrorG = current.getGreen() - col.getGreen();
int quantErrorB = current.getBlue() - col.getBlue();
if ((j + 1) % width != 0)
{
Color x = new Color(buffer[(j + 1)], true);
Color y = new Color(Math.max(0, Math.min(x.getRed() + col.getAlpha() / 255 * quantErrorR * 7 / 16, 255)), Math.max(0, Math.min(x.getGreen() + col.getAlpha() / 255 * quantErrorG * 7 / 16, 255)), Math.max(0, Math.min(x.getBlue() + col.getAlpha() / 255 * quantErrorB * 7 / 16, 255)), x.getAlpha());
buffer[(j + 1)] = y.getRGB();
}
if (((j - 1) % width != 0) && (j - 1 + width < buffer.length))
{
Color x = new Color(buffer[(j - 1 + width)], true);
Color y = new Color(Math.max(0, Math.min(x.getRed() + col.getAlpha() / 255 * quantErrorR * 3 / 16, 255)), Math.max(0, Math.min(x.getGreen() + col.getAlpha() / 255 * quantErrorG * 3 / 16, 255)), Math.max(0, Math.min(x.getBlue() + col.getAlpha() / 255 * quantErrorB * 3 / 16, 255)), x.getAlpha());
buffer[(j - 1 + width)] = y.getRGB();
}
if (j + width < buffer.length)
{
Color x = new Color(buffer[(j + width)], true);
Color y = new Color(Math.max(0, Math.min(x.getRed() + col.getAlpha() / 255 * quantErrorR * 5 / 16, 255)), Math.max(0, Math.min(x.getGreen() + col.getAlpha() / 255 * quantErrorG * 5 / 16, 255)), Math.max(0, Math.min(x.getBlue() + col.getAlpha() / 255 * quantErrorB * 5 / 16, 255)), x.getAlpha());
buffer[(j + width)] = y.getRGB();
}
if (((j + 1) % width != 0) && (j + 1 + width < buffer.length))
{
Color x = new Color(buffer[(j + 1 + width)], true);
Color y = new Color(Math.max(0, Math.min(x.getRed() + col.getAlpha() / 255 * quantErrorR * 1 / 16, 255)), Math.max(0, Math.min(x.getGreen() + col.getAlpha() / 255 * quantErrorG * 1 / 16, 255)), Math.max(0, Math.min(x.getBlue() + col.getAlpha() / 255 * quantErrorB * 1 / 16, 255)), x.getAlpha());
buffer[(j + 1 + width)] = y.getRGB();
}
if (current.getAlpha() >= 128)
{
if (k2 < colors.length / 2) {
simple[j] = Color.WHITE.getRGB();
} else {
simple[j] = Color.BLACK.getRGB();
}
}
else {
simple[j] = new Color(255, 255, 255, 0).getRGB();
}
}
return c.createImage(new MemoryImageSource(width, height, simple, 0, width));
}
public static Image resize(Image i, int[] buffer, Component c, int newDim)
{
int h = i.getHeight(c);
int w = i.getWidth(c);
if (w < h) {
return resize(i, buffer, c, newDim, (int)(newDim * 1.0D * w / h));
}
return resize(i, buffer, c, (int)(newDim * 1.0D * h / w), newDim);
}
public static int getResizedHeight(Image i, Component c, int newDim)
{
int h = i.getHeight(c);
int w = i.getWidth(c);
if (w < h) {
return newDim;
}
return (int)(newDim * 1.0D * h / w);
}
public static int getResizedWidth(Image i, Component c, int newDim)
{
int h = i.getHeight(c);
int w = i.getWidth(c);
if (w < h) {
return (int)(newDim * 1.0D * w / h);
}
return newDim;
}
public static int[] resizebuff(Image i, int[] buffer, Component c, int newDim)
{
int h = i.getHeight(c);
int w = i.getWidth(c);
if (w < h) {
return resizebuff(i, buffer, c, newDim, (int)(newDim * 1.0D * w / h));
}
return resizebuff(i, buffer, c, (int)(newDim * 1.0D * h / w), newDim);
}
public static Image resize2(Image i, int[] buffer, Component c, int newDim)
{
int h = i.getHeight(c);
int w = i.getWidth(c);
if (w < h) {
return resize2(i, buffer, c, newDim, (int)(newDim * 1.0D * w / h));
}
return resize2(i, buffer, c, (int)(newDim * 1.0D * h / w), newDim);
}
public static int[] resize2buff(Image i, int[] buffer, Component c, int newDim)
{
int h = i.getHeight(c);
int w = i.getWidth(c);
if (w < h) {
return resize2buff(i, buffer, c, newDim, (int)(newDim * 1.0D * w / h));
}
return resize2buff(i, buffer, c, (int)(newDim * 1.0D * h / w), newDim);
}
public static Image resize(Image i, int[] buffer, Component c, int newHeight, int newWidth)
{
if (newHeight < 2) {
newHeight = 2;
}
if (newWidth < 2) {
newWidth = 2;
}
int height = i.getHeight(c);
int width = i.getWidth(c);
if ((height == newHeight) && (width == newWidth)) {
return i;
}
int[] resized = new int[newHeight * newWidth];
double hRatio = newHeight / height;
double wRatio = newWidth / width;
for (int y = 0; y < newHeight; y++) {
for (int x = 0; x < newWidth; x++)
{
int oldX = (int)(x / wRatio);
int oldY = (int)(y / hRatio);
resized[(y * newWidth + x)] = buffer[(oldY * width + oldX)];
}
}
return c.createImage(new MemoryImageSource(newWidth, newHeight, resized, 0, newWidth));
}
public static int[] resizebuff(Image i, int[] buffer, Component c, int newHeight, int newWidth)
{
if (newHeight < 2) {
newHeight = 2;
}
if (newWidth < 2) {
newWidth = 2;
}
int height = i.getHeight(c);
int width = i.getWidth(c);
if ((height == newHeight) && (width == newWidth)) {
return buffer;
}
int[] resized = new int[newHeight * newWidth];
double hRatio = newHeight / height;
double wRatio = newWidth / width;
for (int y = 0; y < newHeight; y++) {
for (int x = 0; x < newWidth; x++)
{
int oldX = (int)(x / wRatio);
int oldY = (int)(y / hRatio);
resized[(y * newWidth + x)] = buffer[(oldY * width + oldX)];
}
}
return resized;
}
public static Image resize2(Image i, int[] buffer, Component c, int newHeight, int newWidth)
{
if (newHeight < 2) {
newHeight = 2;
}
if (newWidth < 2) {
newWidth = 2;
}
int height = i.getHeight(c);
int width = i.getWidth(c);
if ((height == newHeight) && (width == newWidth)) {
return i;
}
int[] resized = new int[newHeight * newWidth];
double hRatio = newHeight / height;
double wRatio = newWidth / width;
if ((hRatio > 1.0D) || (wRatio > 1.0D)) {
return resize(i, buffer, c, newHeight, newWidth);
}
for (int y = 0; y < newHeight; y++) {
for (int x = 0; x < newWidth; x++)
{
int k = 0;
double oldC = 0.0D;
double oldRed = 0.0D;
double oldGreen = 0.0D;
double oldBlue = 0.0D;
double oldAlpha = 0.0D;
for (int q = (int)(x / wRatio); q < (int)((x + 1) / wRatio); q++) {
for (int j = (int)(y / hRatio); j < (int)((y + 1) / hRatio); j++)
{
Color oldColor = new Color(buffer[(j * width + q)], true);
oldRed = (oldRed * k + oldColor.getRed()) / (k + 1);
oldGreen = (oldGreen * k + oldColor.getGreen()) / (k + 1);
oldBlue = (oldBlue * k + oldColor.getBlue()) / (k + 1);
oldAlpha = (oldAlpha * k + oldColor.getAlpha()) / (k + 1);
k++;
}
}
resized[(y * newWidth + x)] = new Color((int)oldRed, (int)oldGreen, (int)oldBlue, (int)oldAlpha).getRGB();
}
}
return c.createImage(new MemoryImageSource(newWidth, newHeight, resized, 0, newWidth));
}
public static int[] resize2buff(Image i, int[] buffer, Component c, int newHeight, int newWidth)
{
if (newHeight < 2) {
newHeight = 2;
}
if (newWidth < 2) {
newWidth = 2;
}
int height = i.getHeight(c);
int width = i.getWidth(c);
if ((height == newHeight) && (width == newWidth)) {
return buffer;
}
int[] resized = new int[newHeight * newWidth];
double hRatio = newHeight / height;
double wRatio = newWidth / width;
if ((hRatio > 1.0D) || (wRatio > 1.0D)) {
return resizebuff(i, buffer, c, newHeight, newWidth);
}
for (int y = 0; y < newHeight; y++) {
for (int x = 0; x < newWidth; x++)
{
int k = 0;
double oldC = 0.0D;
double oldRed = 0.0D;
double oldGreen = 0.0D;
double oldBlue = 0.0D;
double oldAlpha = 0.0D;
for (int q = (int)(x / wRatio); q < (int)((x + 1) / wRatio); q++) {
for (int j = (int)(y / hRatio); j < (int)((y + 1) / hRatio); j++)
{
Color oldColor = new Color(buffer[(j * width + q)], true);
oldRed = (oldRed * k + oldColor.getRed()) / (k + 1);
oldGreen = (oldGreen * k + oldColor.getGreen()) / (k + 1);
oldBlue = (oldBlue * k + oldColor.getBlue()) / (k + 1);
oldAlpha = (oldAlpha * k + oldColor.getAlpha()) / (k + 1);
k++;
}
}
resized[(y * newWidth + x)] = new Color((int)oldRed, (int)oldGreen, (int)oldBlue, (int)oldAlpha).getRGB();
}
}
return resized;
}
public static int[] countColors(int[] buffer, Component c, Color[] colors)
{
int[] count = new int[colors.length];
for (int k = 0; k < count.length; k++) {
count[k] = 0;
}
Color col = Color.BLACK;
for (int j = 0; j < buffer.length; j++)
{
col = new Color(buffer[j]);
for (int k = 0; k < colors.length; k++) {
if ((colors[k] != null) && (colors[k].getRGB() == col.getRGB())) {
count[k] += 1;
}
}
}
return count;
}
(Had to cut it off b/c of character limit)
EDIT: Turns out the first error doesn't matter. The program tries to run textures from a separate file. If it isn't found, it skips it.
Any help is appreciated.
Addressing your second issue with the stack trace:
This line is your issue:
resized[(y * newWidth + x)] = buffer[(oldY * width + oldX)];
Specifically this part resized[(y * newWidth + x)] because [y * newWidth + x] can be far bigger than what resized allows.
Let's assume the image is 100x50 (WxH), this means that int[] resized = new int[newHeight * newWidth]; will create a new array that is 5000 long.
However the for loops will create something much higher:
for (int y = 0; y < newHeight; y++) in this instance y will go as high as newHeight or 100
vfor (int x = 0; x < newWidth; x++)in this instanceywill go as high asnewWidth` or 50
So:
resized[(y * newWidth + x)] = something; will be an issue because 100 * 100 + 50 can be as large as 10050, that is far bigger than 5000.
The solution is to make a larger resized array, or to rethink your for loops.

Inconsistent results from taking average of two RGB values

Why are those pixel rgb values sometimes equal and sometimes not equal? I am learning image processing. It would be great if someone help me out here.
public class ColorTest1 {
Color p1;
Color p2;
ColorTest1() throws IOException, InterruptedException {
BufferedImage bi = ImageIO.read(new File("d:\\x.jpg"));
for (int y = 0; y < bi.getHeight(); y++) {
for (int x = 0; x < bi.getWidth() - 1; x++) {
p1 = new Color(bi.getRGB(x, y));
p2 = new Color(bi.getRGB(x + 1, y));
int a = (p1.getAlpha() + p2.getAlpha()) / 2;
int r = (p1.getRed() + p2.getRed()) / 2;
int g = (p1.getGreen() + p2.getGreen()) / 2;
int b = (p1.getBlue() + p2.getBlue()) / 2;
int x1 = p1.getRGB();
int x2 = p2.getRGB();
int sum1 = (x1 + x2) / 2;
int sum2 = a * 16777216 + r * 65536 + g * 256 + b;
System.out.println(sum1 == sum2);
}
}
}
public static void main(String... areg) throws IOException, InterruptedException {
new ColorTest1();
}
}
This is the image:
Take two pixels. One is black. The other is nearly black but with a slight bit of red in it, just 1/255. Ignore alpha. r will be (0 + 1) / 2 = 0. g and b will be 0 too. x1 will be 0. x2 will be 65536, right? So sum1 will be 65536 / 2 = 32768. sum2 obviously will be 0.
Whenever the sum of either red or green of the two colours is odd, the int division will set the high bit of the next colour in RGB, leading to an unexpected result.

How to render colours properly in Java Graphics

I was using this code placed here to generate bar-charts for my datasets. However, the colours were all the same (red in the code), so I decided to generate a colour ramp for this. I wrote the following code:
Color[] getColorRamp(int numColours)
{
Color[] colours = new Color[numColours];
int red_1 = 255;
int green_1 = 0;
int blue_1 = 0;
int red_2 = 0;
int green_2 = 0;
int blue_2 = 255;
int count = 0;
for (float t=0.0f;t<1.0f;t+=1.0/(float)numColours) {
colours[count] = new Color((int)(t*red_2 + (1-t)*red_1),
(int)(t*green_2 + (1-t)*green_1),
(int)(t*blue_2 + (1-t)*blue_1),34);
//System.out.print((int)(t*red_2 + (1-t)*red_1) +",");
//System.out.print((int)(t*green_2 + (1-t)*green_1) +",");
//System.out.println((int)(t*blue_2 + (1-t)*blue_1));
}
return colours;
}
It is here, where the problem starts. Only the first colour (pretty light blue) get rendered properly. Other colours are rendered as black! You can see that I have put System.out.println to verify the colours generated (commented in the code posted here). I saw that colours were generated as perfect RGB combinations.
The modified barchart function is posted here:
void drawBarChart(Graphics g, double[] values, String[] names, String title)
{
if (values == null || values.length == 0)
return;
double minValue = 0;
double maxValue = 0;
for (int i = 0; i < values.length; i++) {
if (minValue > values[i])
minValue = values[i];
if (maxValue < values[i])
maxValue = values[i];
}
//Graphics2D g = (Graphics2D)gg;
Dimension d = getSize();
int clientWidth = d.width;
int clientHeight = d.height;
int barWidth = clientWidth / values.length;
Font titleFont = new Font("SansSerif", Font.BOLD, 20);
FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);
int titleWidth = titleFontMetrics.stringWidth(title);
int y = titleFontMetrics.getAscent();
int x = (clientWidth - titleWidth) / 2;
g.setFont(titleFont);
g.drawString(title, x, y);
int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();
if (maxValue == minValue)
return;
double scale = (clientHeight - top - bottom) / (maxValue - minValue);
y = clientHeight - labelFontMetrics.getDescent();
g.setFont(labelFont);
Color[] colours = getColorRamp(values.length);
for (int i = 0; i < values.length; i++) {
int valueX = i * barWidth + 1;
int valueY = top;
int height = (int) (values[i] * scale);
if (values[i] >= 0)
valueY += (int) ((maxValue - values[i]) * scale);
else {
valueY += (int) (maxValue * scale);
height = -height;
}
g.setColor(colours[i]);
g.fillRect(valueX, valueY, barWidth - 2, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY, barWidth - 2, height);
int labelWidth = labelFontMetrics.stringWidth(names[i]);
x = i * barWidth + (barWidth - labelWidth) / 2;
g.drawString(names[i], x, y);
}
//paintComponent(g);
}
I wish to know, what mistake I am making!
You're probably going to hit yourself on the head now. The reason it fails is that you forget to increase the variable count after setting the first colour, so you're constantly overwriting the first element of the Color array, and leaving all the other values in the array as their initial default (null).
Fixed code:
for (float t=0.0f;t<1.0f;t+=1.0/(float)numColours) {
colours[count++] = new Color((int)(t*red_2 + (1-t)*red_1),
(int)(t*green_2 + (1-t)*green_1),
(int)(t*blue_2 + (1-t)*blue_1),34);
}
(Notice the colours[count++])

Categories