Speed up histogram color code
in
Programming Questions
•
1 year ago
I've been messing around with Shiffman's Mandelbrot code for a while now. I have it counting fractional iteration counts (instead of integer iterations counts) to get smooth colors. Another thing I tried adding was histogram coloring which works but is vey, very slow for fractional iterations. It is fast for integer iterations because I can build a histogram with:
int[] hist = new int[maxIterations];
for (every pixel) {
...run Mandelbrot code...
...n = numIterations...
hist[n]++;
}
Unfortunately I can't do this for fractional iterations because I can't index an array with a float. If you are not familiar with histogram coloring the basic idea is to count the number of pixels that have a lower iteration count by comparison to the pixel that needs to be colored. That number is divided by the number of pixels to get a value between 0.0 and 1.0. Multiply that value by 255 and you get a value for that pixel. For example:
int less = number of pixels with an iteration value less than the pixel in question
int total = number of pixels that the screen contains (width*height)
float histColor = float(less)/total*255
Here is the code. It works, but the coloring is too slow:
- float xmin = -2.5;
- float ymin = -2.0;
- float wh = 4;
- int maxIterations = 200;
- void setup() {
- size(200, 200, P2D);
- }
- void draw() {
- loadPixels();
- float xmax = xmin+wh;
- float ymax = ymin+wh;
- float dx = (xmax-xmin)/width;
- float dy = (ymax-ymin)/height;
- float[] fn = new float[width*height];
- float x = xmin;
- for (int i = 0; i < width; i++) {
- float y = ymin;
- for (int j = 0; j < height; j++) {
- float zr = x;
- float zi = y;
- int n = 0;
- while (n < maxIterations) {
- float zrr = zr*zr;
- float zii = zi*zi;
- float twori = 2*zr*zi;
- zr = zrr-zii+x;
- zi = twori+y;
- if (zrr+zii > 16.0) break;
- n++;
- }
- if (n == maxIterations) fn[i+j*width] = 0;
- else fn[i+j*width] = float(n)+log(log(maxIterations))-log(log(sqrt(sq(zr)+sq(zi))))/log(2);
- y += dy;
- }
- x += dx;
- }
- println("Fractional Iterations Found");
- for (int i = 0; i < width*height; i++) {
- if (fn[i] == 0) pixels[i] = 0;
- else {
- int numLess = 0;
- for (int j = 0; j < width*height; j++) if (fn[j] < fn[i]) numLess++;
- pixels[i] = color(float(numLess)/(width*height)*255);
- }
- }
- println("Mandelbrot Rendered");
- updatePixels();
- noLoop();
- }
1