We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Efficient way to 'loop' through pixels
Page Index Toggle Pages: 1
Efficient way to 'loop' through pixels (Read 728 times)
Efficient way to 'loop' through pixels
Apr 15th, 2008, 11:12pm
 
Hello!

I'm trying to keep track of the /popular/ colors in an image by looping through each pixel, checking its HEX value, comparing with what I have found so far and adding it to an array (or incrementing a counter for each color). My problem is that the method I'm using is extremely slow:

PImage c;
c = loadImage("/images/02.jpg");

for (int i = 0; i < c.width*c.height; i += 1)
{
int here = c.pixels[i];
color col = color(red(here), green(here), blue(here));
println(hex(col, 6));
}

Would using get() be faster? or something completely different? Also, is there another way I could use to store the count for each color? (something like Python's dictionaries would be perfect)

Thanks!
Re: Efficient way to 'loop' through pixels
Reply #1 - Apr 15th, 2008, 11:56pm
 
You can cut out the "color col=..." line, color is actually a synonym for int.

so your code can be:
Code:
 PImage c;
c = loadImage("/images/02.jpg");

for (int i = 0; i < c.width*c.height; i += 1)
{
println(hex(c.pixels[i];, 6));
}
Re: Efficient way to 'loop' through pixels
Reply #2 - Apr 16th, 2008, 4:43am
 
Quote:
You can cut out the "color col=..." line, color is actually a synonym for int.

so your code can be:
Code:
 PImage c;
c = loadImage("/images/02.jpg");

for (int i = 0; i < c.width*c.height; i += 1)
{
println(hex(c.pixels[i];, 6));
}


Thank you for that! I also decided to check one every five pixels. It won't change the results that much and it is (technically) 5 times faster Smiley
Re: Efficient way to 'loop' through pixels
Reply #3 - Apr 16th, 2008, 2:47pm
 
println() is also very slow--you don't want to use that inside a loop that runs many times.

the best thing to do is compare the actual color value when you want to store it, not its hex value, since the conversion to/from hex (and comparing a hex String) will take a lot of time. just use an array of ints and compare against those.
Page Index Toggle Pages: 1