Obteniendo datos de píxeles de una imagen usando java
Pregunta
Estoy intentando obtener los valores rgb de píxeles de una imagen de bit 64 x 48
. Obtengo algunos valores pero en ningún lugar cerca de los valores de 3072 (= 64 x 48)
que estoy esperando. También obtengo:
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)
No puedo encontrar el error de fuera de límites ...
Aquí está el 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;
}
}
Solución
Esto:
for(int i = 0; i < img.getHeight(); i++){
for(int j = 0; j < img.getWidth(); j++){
rgb = getPixelData(img, i, j);
No coincide con esto:
private static int[] getPixelData(BufferedImage img, int x, int y) {
Tiene i
contando las filas y j
las columnas, es decir, i
contiene valores y y
Otros consejos
Esto también funciona:
BufferedImage img = ImageIO.read(file);
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
Estaba buscando esta misma habilidad. No quería enumerar toda la imagen, así que busqué un poco y utilicé PixelGrabber.
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();
Puede usar int []
directamente aquí, los píxeles están en un formato dictado por ColorModel desde pg.getColorModel ()
, o puede cambiar eso a falso verdadero y forzarlo a ser RGB8-in-ints.
Desde entonces he descubierto que las clases Raster
y Image también pueden hacer esto, y se han agregado algunas clases útiles en 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);
También hay varios métodos getPixels (...)
en Raster
.
int argb = img.getRGB (x, y);
Su código
int argb = img.getRGB (y, x);
mis cambios ahora funciona
Tienes que cambiar:
for(int i = 0; i < img.getHeight(); i++){
for(int j = 0; j < img.getWidth(); j++){
rgb = getPixelData(img, i, j);
En
for(int i = 0; i < img.getWidth(); i++){
for(int j = 0; j < img.getHeight(); j++){
rgb = getPixelData(img, i, j);
Porque el segundo parámetro de getPixelData
es el valor x
y la tercera es el valor y
. Cambiaste los parámetros.
¿Por qué no usó solo use:
public int[] getRGB(int startX,
int startY,
int w,
int h,
int[] rgbArray,
int offset,
int scansize)
Está incorporado, hombre.