We are about to switch to a new forum software. Until then we have removed the registration on this forum.
This is a very simple pixelation algorithm using the pixel array. When I run the program without the outer for loop (yL) the program successfully handles a single row, though it seems slow. When I add this loop back in, the program hangs, will not finish, and I have to shut it down using Task Manager. I am sure there is something simple and fundamental here, perhaps how I am using the pixel array and the loadPixels(), updatePixels() methods?
any help is very appreciated, B
PImage myImg;
color white1 = #FFFFFF;
color skyBlue = #6092F1;
color rgbRed = #FF0000;
color rgbBlue = #0000FF;
int pixSize = 50;
float threshold = 180.0;
void setup() {
size (1280, 720);
myImg = loadImage("img-200.tif");
image (myImg,0,0);
pixelate (myImg, rgbRed, rgbBlue, pixSize);
}
void pixelate (PImage pic, color color1, color color2, int pSize) {
int c1Count = 0;
int c2Count = 0;
int pos = 0;
pic.loadPixels();
// two outer loops handle rows and columns of cells - each cell size is determined by pixSize
for (int yL = 0; yL < pic.height; yL += pSize) {
for (int xL = 0; xL < pic.width; xL += pSize) {
pos = ((yL * pic.width) + xL);
// two inner loops handle each pixel in each cell
for (int yS = 0; yS < pSize; yS++) {
for (int xS = 0; xS < pSize; xS++) {
color p = pic.pixels[pos + (yS * pic.width) + xS];
// just using red component to determine pixel's brighness
if (((red(p)) > threshold)) {
c1Count++;
} else {
c2Count++;
}
}
}
// rectangles used instead of changing each pixel's color
if (c1Count > c2Count) {
noStroke ();
fill (color1);
rect(xL, yL, pSize, pSize);
} else {
noStroke();
fill (color2);
rect(xL, yL, pSize, pSize);
}
c1Count = 0;
c2Count = 0;
}
}
pic.updatePixels();
}
Answers
try with a small image, I think it's just slow... because 4 for-loops.........
With some pre-calculation you could reduce the algorithm to just two (possibly three) loops, although the maths would need some thought if the image width and/or height was not a multiple of the pixelate size.
Also you could access the pixel ARGB color data directly rather than using the red(), green() ... methods, this would improve the speed greatly.