Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need Faster way to get RGB value for each Pixel of a Buffered Image

What is the fastest way to get the RGB value of each pixel of a BufferedImage?

Right now I am getting the RGB values using two for loops as shown in the code below, but it took too long to get those values as the nested loop runs a total of 479999 times for my image. If I use a 16-bit image this number would be even higher!

I need a faster way to get the pixel values.

Here is the code I am currently trying to work with:

BufferedImage bi=ImageIO.read(new File("C:\\images\\Sunset.jpg"));

int countloop=0;  

for (int x = 0; x <bi.getWidth(); x++) {
    for (int y = 0; y < bi.getHeight(); y++) {
        Color c = new Color(bi.getRGB(x, y));
        System.out.println("red=="+c.getRed()+" green=="+c.getGreen()+"    blue=="+c.getBlue()+"  countloop="+countloop++);                                                                                                                                                  
    }
}
like image 983
Jony Avatar asked Apr 10 '12 12:04

Jony


People also ask

How do you find the pixel value of an image RGB?

Retrieving the pixel contents (ARGB values) of an image −Get the pixel value at every point using the getRGB() method. Instantiate the Color object by passing the pixel value as a parameter. Get the Red, Green, Blue values using the getRed(), getGreen() and getBlue() methods respectively.

How many values per point pixel does RGB have?

A digital color image pixel is just numbers representing a RGB data value (Red, Green, Blue). Each pixel's color sample has three numerical RGB components (Red, Green, Blue) to represent the color of that tiny pixel area. These three RGB components are three 8-bit numbers for each pixel.

What color is a pixel if the RGB value is 255 255 255?

An RGB value of (255, 0, 0) would imply a red pixel, an RGB value of (0, 255, 0) would be green, and an RGB value of (0, 0, 255) would be blue. An RGB of (255, 255, 255) is white, (0, 0, 0) is black. Varying the RGB value of the three color elements causes the eye to perceive a wide range of colors.


1 Answers

I don't know if this might help and I haven't tested it yet but you can get the rgb values this way:

BufferedImage bi=ImageIO.read(new File("C:\\images\\Sunset.jpg"));
int[] pixel;

for (int y = 0; y < bi.getHeight(); y++) {
    for (int x = 0; x < bi.getWidth(); x++) {
        pixel = bi.getRaster().getPixel(x, y, new int[3]);
        System.out.println(pixel[0] + " - " + pixel[1] + " - " + pixel[2] + " - " + (bi.getWidth() * y + x));
    }
}

As you can see you don't have to initialize a new Color inside the loop. I also inverted the width/height loops as suggested by onemasse to retrieve the counter from data I already have.

like image 60
mastaH Avatar answered Sep 19 '22 13:09

mastaH