Obtendo dados de pixel de uma imagem usando java
Pergunta
Eu estou tentando obter os valores de pixel RGB de uma imagem de 64 x 48
bit. Recebo alguns valores mas nem de longe os valores 3072 (= 64 x 48)
que eu estou esperando. Eu também obter:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(ByteInterleavedRaster.java:301)
at java.awt.image.BufferedImage.getRGB(BufferedImage.java:871)
at imagetesting.Main.getPixelData(Main.java:45)
at imagetesting.Main.main(Main.java:27)
Não consigo encontrar o fora dos limites de erro ...
Aqui está o código:
package imagetesting;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.image.BufferedImage;
public class Main {
public static final String IMG = "matty.jpg";
public static void main(String[] args) {
BufferedImage img;
try {
img = ImageIO.read(new File(IMG));
int[][] pixelData = new int[img.getHeight() * img.getWidth()][3];
int[] rgb;
int counter = 0;
for(int i = 0; i < img.getHeight(); i++){
for(int j = 0; j < img.getWidth(); j++){
rgb = getPixelData(img, i, j);
for(int k = 0; k < rgb.length; k++){
pixelData[counter][k] = rgb[k];
}
counter++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static int[] getPixelData(BufferedImage img, int x, int y) {
int argb = img.getRGB(x, y);
int rgb[] = new int[] {
(argb >> 16) & 0xff, //red
(argb >> 8) & 0xff, //green
(argb ) & 0xff //blue
};
System.out.println("rgb: " + rgb[0] + " " + rgb[1] + " " + rgb[2]);
return rgb;
}
}
Solução
Este:
for(int i = 0; i < img.getHeight(); i++){
for(int j = 0; j < img.getWidth(); j++){
rgb = getPixelData(img, i, j);
Não corresponder-se com esta:
private static int[] getPixelData(BufferedImage img, int x, int y) {
Você tem i
contando as linhas e j
as colunas, ou seja i
contém y valores e j
contém x valores. Isso é para trás.
Outras dicas
Isso funciona muito:
BufferedImage img = ImageIO.read(file);
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
Eu estava procurando por essa mesma capacidade. não quis enumerar a imagem inteira, então eu fiz alguma pesquisa e PixelGrabber usado.
Image img = Toolkit.getDefaultToolkit().createImage(filename);
PixelGrabber pg = new PixelGrabber(img, 0, 0, -1, -1, false);
pg.grabPixels(); // Throws InterruptedException
width = pg.getWidth();
height = pg.getHeight();
int[] pixels = (int[])pg.getPixels();
Você pode usar o int[]
diretamente aqui, os pixels estão em um formato ditado pelo ColorModel de pg.getColorModel()
, ou você pode mudar aquele falso para verdadeiro e forçá-lo a ser RGB8-in-ints.
Eu já descobriu que as classes Raster
e imagem podem fazer isso também, e houve algumas classes úteis adicionados no javax.imageio.*
.
BufferedImage img = ImageIO.read(new File(filename)); // Throws IOException
int[] pixels = img.getRGB(0,0, img.getWidth(), img.getHeight, null, 0, img.getWidth());
// also available through the BufferedImage's Raster, in multiple formats.
Raster r = img.getData();
int[] pixels = r.getPixels(0,0,r.getWidth(), r.getHeight(), (int[])null);
Existem vários métodos getPixels(...)
em Raster
também.
int argb = img.getRGB(x, y);
Seu código
int argb = img.getRGB(y, x);
minhas alterações agora ele funciona
Você tem que mudar:
for(int i = 0; i < img.getHeight(); i++){
for(int j = 0; j < img.getWidth(); j++){
rgb = getPixelData(img, i, j);
Em
for(int i = 0; i < img.getWidth(); i++){
for(int j = 0; j < img.getHeight(); j++){
rgb = getPixelData(img, i, j);
Uma vez que o segundo parâmetro de getPixelData
é o x
-valor eo thirth é o y
de valor. Você trocou os parâmetros.
Por que não usar apenas usar:
public int[] getRGB(int startX,
int startY,
int w,
int h,
int[] rgbArray,
int offset,
int scansize)
É construído-in, cara.