Reputation: 5
I have such a problem. I want to make "average" image from the few diffirent. my idea was to load them to BufferImage sequentially, sum values in each bit, and than just divide by number of photos. The problem is that i can't divide byte[][] by number. What am i doing wrong, or what is the proper way to do this?
File[] others = getOtherImageFiles(file);
byte[][] pixels = new byte[300][];
List<byte[][]> pixelsList = new ArrayList<byte[][]>();
for (int i = 0; i < others.length; i++) {
try {
img = ImageIO.read(others[i]);
} catch (IOException e) {
}
for (int x = 0; x < img.getWidth(); x++) {
pixels[x] = new byte[img.getHeight()];
for (int y = 0; y < img.getHeight(); y++) {
pixels[x][y] = (byte) (img.getRGB(x, y));
}
}
pixelsList.add(pixels);
}
byte[][] pixelsSum = new byte[300][];
for (int i = 0; i < pixelsList.size(); i++) {
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
pixelsSum[x][y] += pixelsList.get(i)[x][y];
}
}
}
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
pixelsSum[x][y]/10;
}
}
}
i want to use them as a face comparer and the point is to create a scheme of faces.
Upvotes: 0
Views: 1302
Reputation: 520
You're close. You did the division by 10, but you never wrote the result back into the pixelsSum
array, so the result is lost. You need to do:
pixelsSum[x][y] = pixelsSum[x][y] / 10;
or in shorthand:
pixelsSum[x][y] /= 10;
Another problem you will run into is that each byte
in Java (or any other language) can only hold values between 0 and 255. So if you have a bytes x = 255, y = 1
, x + y
will turn out to be 0. When you add up 10 images, it will almost certainly go over the 255 limit. I suggest changing pixelsSum from byte[][]
to int[][]
, and then turn it back to bytes after you do the division.
Upvotes: 1
Reputation: 1927
Instead of this set of loops:
for (int i = 0; i < pixelsList.size(); i++) {
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
pixelsSum[x][y] += pixelsList.get(i)[x][y];
}
}
}
you should put the pixelsList
reference in the middle:
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
for (int i = 0; i < pixelsList.size(); i++) {
pixelsSum[x][y] += pixelsList.get(i)[x][y];
}
pixelsSum[x][y] /= pixelsList.size();
}
}
This should calculate the average immediately rather than looping through the pixelsSum
array again. Note also the use of the /=
operator which performs both division and assignment compared with the /
operator which is limited to division in the context of numbers.
Upvotes: 0