Figure 6. Turtle.

Generating fractal-like images

In this post I'll describe an algorithm that builds images similar to this one:

Generated image example
Figure 1. Generated image example.

We will use Mandelbrot set generation algorithm as a basis. You can find example of Matlab code for this kind of fractal on this page (thanks to Alberto Strumia). It will be used as a basis.

Mandelbrot set is generated in iterative manner.

  1. C = X + 1i*Y; % X and Y form a grid of 2D coordinates
  2. Z = zeros(size(C));
  3. for it = 1:10
  4. Z = Z.^2 + C;
  5. end

Information from matrix Z is then used to display a resulting fractal.

In order to shift from standard images of fractals, let's introduce some randomness to the generation process. We will use two sources of randomness in modified algorithm:

  1. noise added to grid;
  2. noisy value of exponent in generation loop.

So, we arrive to the following code:

  1. L = -2;
  2. C=X+1i*Y;
  3. Z = zeros(size(C));
  4. T = (1+0.01*randn(size(C)).*exp(0.01*1i*2*pi*randn(size(C))));
  5. C = C.*T;
  6. for it = 1:10
  7. Z=Z.^(L+it+10*randn)+C;
  8. Z(isnan(Z)) = C(isnan(Z));
  9. end

Lines 4-5 multiply grid by "small" random complex number effectively adding minor deformations to the grid. As a result, images look noisy. Commenting out these lines leads to interesting pictures too: all the curves become more clear.
In line 7 you can see that exponent for Z has changed: for each iteration exponent grows and also gets altered by a random number. Variable L denotes approximate starting value for exponent (-2 in this example). Trick in line 8 prevents us from undesired NaNs in case if we got too far in experiments with value of the exponent.

We are almost done. The last step is visualization.

  1. W = exp(-abs(Z));
  2. W(W<1e-10) = 0.1*max(W(:))*angle(Z(W<1e-10))/pi;
  3. pcolor(W);
  4. shading flat;
  5. axis('square','equal','off');

The code is straight-forward. It transforms Z so that it lies in real domain between 0 and 1. Line 2 handles cases where absolute value for Z is close to zero: low values are replaced with information gathered from argument of corresponding elements in Z. Then a pretty colormap is selected and at last data is plotted.

You can find full source code for Matlab/Octave with some additional make-up in the github repo (m-file).

Some examples of generated images:

Figure 2. Bug.
Figure 2. Bug.

Figure 3. Mill.
Figure 3. Mill.

Figure 4. Star.
Figure 4. Star.

Figure 5. Sun
Figure 5. Sun.

Figure 6. Turtle.
Figure 6. Turtle.

That's all for now. 🙂

One thought on “Generating fractal-like images”

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.