Welcome to Fractal Forums

Fractal Math, Chaos Theory & Research => (new) Theories & Research => Topic started by: Tglad on March 07, 2017, 04:21:08 AM




Title: What colour is a Koch curve?
Post by: Tglad on March 07, 2017, 04:21:08 AM
I have been doing a bit more investigation of fractal colour due to its shape, and looking at the 2D case.
Three basic fractal curves are:
(https://3.bp.blogspot.com/-jCARBVP3WiQ/WJACD2mceGI/AAAAAAAABB8/AB48mEsIsLsOCkMCppLrw51MPjKXdmawwCLcB/s1600/Untitled%2BDiagram.png)
with a fourth being a version with random bend angles.

The idea of the colouration is that there is some minimum resolvable spot size inside which reflected coloured light doesn't combine linearly, instead it interferes. For any given light frequency, instead of amplitudes adding, it is the complex value amplitude*e^(i * frequency * distance travelled) that sums together and you take its modulus. I look at the case where the curve is opaque, and only consider direct reflection (one bounce), so approximates low reflectivity with high light intensity to compensate.

Here is a Koch curve
(https://2.bp.blogspot.com/-fbA1bx29tRY/WI3eflG2UdI/AAAAAAAAA_E/R73f4qO4pVMYXvsAJEh-PifL81xk1nCzQCLcB/s200/shape1reflect.bmp)
for five increasing bend angles (rows) lit front on, with increasing spot size from one pixel downwards:
(https://3.bp.blogspot.com/-IvkWTwaSSmI/WLvu5wbl9rI/AAAAAAAABIM/hh6B2_Zyb4AqKltrwWZCa4ov0Kfc3YBYgCLcB/s200/rcConWidth.bmp)

As you can see, the spot size doesn't make a great deal of difference to the colour, however the scale of the curve does. So we pick a mid-range spot size and increase the size of the curve (downwards):
(https://2.bp.blogspot.com/-ZUl-2eL4aJs/WLvuxoqS1yI/AAAAAAAABIE/ywkYveZ2_hsZrN2Z1_uajx47cvcy317twCLcB/s1600/rc.bmp)

Most of this colour is because this is a single pinhole (white) light source, for ambient white light you integrate over all light directions:
(https://3.bp.blogspot.com/-Kz6twkBTKYY/WL07oklyw0I/AAAAAAAABIo/fEpSaC2_MKUQaK_MZJaZ2ILD1qYTe4WsQCLcB/s1600/rcAmbient.bmp)
Notice it is most colourful on the fourth down (~1.4D), and gets less so as the dimension approaches 2.

For the Levy curve
(https://3.bp.blogspot.com/-NnB-CdIWWh0/WI3Tv8O8NXI/AAAAAAAAA-Q/GtW4Bg254NIQ1aVu16nYJasCnYrUBoqGgCEw/s200/levydiffuseb.bmp)
it is a bit less colourful:
(https://4.bp.blogspot.com/-gE3C_jkcf04/WL074uTNQkI/AAAAAAAABIs/zOakPISjfIkNiwkSaTXFLVAXHRmJJ0ZCACLcB/s1600/levyAmbient.bmp)

and the randomised curve has least colour:
(https://4.bp.blogspot.com/-oOt3QlHlvZU/WL08TzTTbCI/AAAAAAAABI8/0rbZm-dakoYx5qvg7Mj7ryEcgnYugXG6wCLcB/s1600/randomAmbient.bmp)

however the Dragon curve
(https://2.bp.blogspot.com/-Hrt_JRts3iE/WI8Okwif9dI/AAAAAAAABAo/fw933Ke9qLADeGA2Hr3Aq_hSZLEdG9q-wCLcB/s200/dragondiffuse.bmp)
seems like the most colourful of the lot:
(https://1.bp.blogspot.com/-3Y6iXpirxZU/WL08PImGluI/AAAAAAAABI4/PpvlwNirH6c-i91Zo-YMcz3OkW83mFv4gCLcB/s1600/dragonAmbient.bmp)

So, if I'm doing the light physics about right then I think we can say that:
1. colour is stronger when reflectivity is lower, and incident intensity should be high to compensate and due to fractal's roughness
2. colour is stronger (and shade darker) away from integer dimensions
3. colour is stronger on thinner light sources (e.g. a pinhole) and less strong on wider (e.g. ambient) light
4. colour is less strong when the curve is more random
5. hue cycles as the curve scale increases, so your fractal's colour depends on how big it is
It also seems to be the case that concave parts are more red-shifted and convex parts relatively blue-shifted (or more neutral).

These should all transfer to 3D fractal surfaces too I imagine.
If anyone here is good with light physics, let me know if you think I'm doing something wrong!  :)


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 10, 2017, 12:05:17 AM
And here's a rotating Koch snowflake, of increasing scale, with ambient light and a single directional light from the right:
(https://3.bp.blogspot.com/-Nwu4BDWZveA/WME1pBDiJxI/AAAAAAAABJU/5voqSJnwPNgSSEDaHv4t-432Uz_DsA3xwCLcB/s1600/koch.gif.gif)

the vertical rainbow effect seems to vary a bit as it rotates.


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 12, 2017, 11:55:04 AM
If you remove the point light, so the only light is an ambient sky then a rotating Koch snowflake looks like this:
(https://2.bp.blogspot.com/-_Xs4xo_kSec/WMUlGV8fnwI/AAAAAAAABKE/iORO2R0ZkjQbXY6lFM2clDNpqm4YP7btwCLcB/s320/www.GIFCreator.me_RrRYi3.gif)

This is interesting as you can see that its colour changes with view angle, even for ambient light. I think this is correct as I have tried three methods and they all produce the same result (http://tglad.blogspot.com.au/2017/01/the-colour-of-2d-fractals.html).

So a Koch curve prism flips between brown and blue/purple every 30 degrees as you rotate it.


Title: Re: What colour is a Koch curve?
Post by: youhn on March 12, 2017, 09:15:19 PM
Not sure if I understand all details, but this is really nice.

The surface of heated metal also get color, but permanent in any direction. The color depends on the temperature. Is there any (fractal) connection?

(https://anitachowdry.files.wordpress.com/2013/05/steel-spectrum-2-copy.jpg)
Source: https://anitachowdry.wordpress.com/2013/11/15/heat-induced-colours-on-metals/


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 12, 2017, 11:31:00 PM
I'm pretty sure metals that get these kinds of colors actually have their top layers react with air or surrounding molecules (sometimes high heat is necessary for reactions) and that thin film of different material is what causes this coloration. The effect is especially famously strong in Bismuth (https://en.wikipedia.org/wiki/Bismuth#Physical_characteristics) as you can see here: (https://upload.wikimedia.org/wikipedia/commons/thumb/1/1f/Wismut_Kristall_und_1cm3_Wuerfel.jpg/1024px-Wismut_Kristall_und_1cm3_Wuerfel.jpg)
In principle it's still a similar effect, but it's not quite the same.
You probably know of the interference patterns you get from a double slit experiment.
But do you also know what happens if you try to use white light?
(https://www.itp.uni-hannover.de/~zawischa/ITP/bildchen/spalt07.png)
This, roughly. (I think that image is computer generated though: It's quite a bit too perfectly evenly bright for a photo)
If I understood what Tglad is doing right, then he's basically taking the many tiny bumps and gaps that are inherent in a given fractal (in this example: the Koch snowflake) as a sort of slit, except he doesn't really consider refraction but rather reflection, and only a single bounce deep.
What you can see in the animations is basically a tapered Koch Snowflake "gear" with a scale of 1 (I think it's 1 centimeter? - relative to the wavelength of light, not relative to screen space) at the top and, it looks like about 2 (cm?) at the bottom, rotating around in two different lighting conditions (and for some reason the rotational direction also changes).
Because the smaller features are on the order of the size of the wavelengths of visible light, the reflections are no longer white but actually have different brightness for different wavelengths, overally giving the gear color.


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 13, 2017, 12:08:29 PM
That's exactly right, here's a diagram that might clarify:
(https://3.bp.blogspot.com/-sXbNZiJRDqU/WMZ5R-wtvYI/AAAAAAAABKg/VcQQm6EGy4I06p_PVSgYSmCBtXCmzdFewCLcB/s1600/interference.png)

You assume each packet of incident light is a monochromatic wave of a small width (about 2 pixels), and the bumpy surface means the reflected waves have differing phase, when you add those together (thinking of the wave as circular motion in a 2d or complex plane), the magnitude of the result is the intensity for that wavelength. Do this once for the red, green and blue wavelengths, for all incidence directions and you get the fractal's colour. Assuming it is opaque, and low reflectivity (so one bounce is a good approximation).

I made each pixel about 4 wavelengths wide, so about 2 microns wide, so the "gear" image is about 0.6mm wide, however the colours remain the same for enlargements by any powers of three due to symmetry, and in-between scales just have a vertical shift of the colours.

I think the technique is valid, it is based on this awesome page:
http://www.itp.uni-hannover.de/~zawischa/ITP/diffraction.html (http://www.itp.uni-hannover.de/~zawischa/ITP/diffraction.html)
The interfering beam width maybe justified since:
Quote
Light coming from one point will shine on an approximately circular area on the retina (or film/sensor), and correspondingly all rays arriving at one point of the retina will originate from a small, circular area


Title: Re: What colour is a Koch curve?
Post by: claude on March 13, 2017, 12:48:20 PM
Do this once for the red, green and blue wavelengths, for all incidence directions and you get the fractal's colour.

Better would be to use CIE XYZ colour space to accumulate monochromatic light over a spectrum with more granularity than just 3 sample points - otherwise you might miss some important peaks/troughs.


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 13, 2017, 01:27:51 PM
Do you think you could expand it to include more bounces and/or more possibly color-giving effects? There might actually be some iterative or recursive procedure to find arbitrary light paths through the Koch snowflake to arbitrary depth due to its high symmetry. Equivalently, if you try the random version, you probably could even emulate infinite depth via some monte-carlo random walk of the light source near the boundary.

And how do you sample the white light? Do you just pick a handful of channels and convert them over to RGB? I think you could "properly" sample a blackbody white light source to get a full spectral view. Sampling from the correct distribution would be really easy. The hard part simply would be to correctly transform the result to RGB. But since you did some fancy more-than-three-color math already, I can only assume you have something ready that should scale to arbitrarily many input channels.


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 13, 2017, 01:31:03 PM
For color management, you could try supporting OpenColorIO (http://opencolorio.org/) and using Filmic Blender which is a special OCIO file that really expands on the dynamic range you can use in your images. This might mean a lot finer details for dark and bright spots. - Filmic Blender apparently is based on the industry standard used by Hollywood to really get the most out of your image details.


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 15, 2017, 11:33:34 AM
Good point Claude, I was just looking at the red, green and blue wavelengths.
Converting a higher res spectrum into RGB is a bit tricky, I have just tried using the answer 6 here: http://stackoverflow.com/questions/1472514/convert-light-frequency-to-rgb (http://stackoverflow.com/questions/1472514/convert-light-frequency-to-rgb) and I get this:
(https://2.bp.blogspot.com/-SvsiYb895Rw/WMkWrryfMcI/AAAAAAAABK4/_OWSABJEku8o7_kf5MeBx8o_zFEMazLwACLcB/s1600/ambientfullspectrum.gif)
the main difference to the previous gif is that the aqua part is less noticeable. The brown part is perhaps less strong but that's because the average rgb (if I integrate over all the visible frequencies) is a little bit purple:
(https://4.bp.blogspot.com/-PKZgkAcAe7g/WMkXLgV_loI/AAAAAAAABLA/S5rZNjKGnl0ryoIEOgCe3bO_Ryd7gmTuACLcB/s320/koch0_tint.bmp)
I was unsure whether white light should be equal intensity for equally spaced frequencies, or equally spaced wavelengths, but the latter gives a really orange colour so I used the former. Is this where the blackbody white light source that kram talked about comes in?
[Edit: in hindsight, I am somehow using these light sensitivity curves incorrectly, instead I have used a simple intermediate colours (yellow, cyan) to get 7 samples instead of 3, this is about enough as the spectrum isn't that spikey].

"Do you think you could expand it to include more bounces"
possibly, but it gets quite expensive, its already a multiple integral over spot size, fractal length, frequency, incident angle and time.

".. and/or more possibly color-giving effects?"
The other effect would be from refraction and total internal reflection... it would need a chosen refraction index... I haven't looked at this, but it has been suggested that this can give stonger colouration. The strongest colours come from point coherent light sources of just a few frequencies (e.g. red, green and blue), like so (with just a little ambient light):
(https://4.bp.blogspot.com/-gtwLFi5iYdE/WMPchkATiZI/AAAAAAAABJs/3WcyJe62w5wj7fxuzY6XnNkGn_RNu_ijACLcB/s320/www.GIFCreator.me_udQtoR.gif)

"you could try supporting OpenColorIO"
Yes the high dynamic range sounds like a better way to store these colour experiments, rather than the 0 to 255 gifs.


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 15, 2017, 03:05:06 PM
Ah so the other coloration would just be chromatic aberration, the lens defect? Seems unnecessary. It'd not be fractal-specific.
What you already cover, then, is what you get from grid diffraction, right? (As in the image of the spectrum I showed below)

Color space conversions apparently are far from trivial. To properly convert between wavelengths and RGB you need to know what color space you are working in and stuff like that. It can be really fiddly. However, I think a linear space (which sRGB isn't) probably would make stuff simpler.

Black body radiation is basically a particular energy spectrum that's being emitted at particular temperatures. The sun has a surface of 5777K, so that's the color it glows in, however the sky, at least during day time, takes away some of the high energy radiation that's instead coming seemingly uniformly from everywhere, so the sun looks a bit warmer (which oddly enough means it looks like it has a lower temperature) but the sky adds a ton of cool ambient light. I think a common white point is typically set at like 6500K.

Planck's Law states:
(https://wikimedia.org/api/rest_v1/media/math/render/svg/b4d70697e4d2fe9f187a96fc030bc7baaa52b841)
Where I is the power (the energy per time unit) that's being emitted.
The constant in front amounts to 1.4745*10-50kg s (kilograms seconds, a weird unit of course), but you can basically forget about that. It's just a scaling factor. We're only interested in the
The actual interesting part then is \frac{\nu^3}{e^{\frac{h \nu}{k T}} -1}

The range that interests us is \nu = 400 \text{-} 789 \text{THz}.
So to get the right sample distribution, you'd follow the very simple Markov Chain Monte Carlo sampling algorithm. I hope the following example in Python is readable enough as well as error-free (it's been a while that I actually implemented something like this):

Code:
from math import exp, floor, ceil
import random
import numpy as np
from matplotlib import pyplot as plt


C = .70351417223810256  # prefactor such that peak is 1
K = 4.79924  # prefactor if units are in PHz and 10^4 K
# desired range for v is .4 to .789
# desired range for T is 7.98e-2 to 2.
# typical range would be .5 to .7, commonly .65


def Planck(v, T):  # the distribution of spectral frequencies for a given temperature
    KTv = K * v / T
    return C * KTv * KTv * KTv * v * v / (exp(KTv) - 1)


def MC(T):  # generates samples from the distribution using Markov Chain Monte Carlo method
    v0 = random.uniform(.4, .789)
    I0 = Planck(v0, T)
    while True:
        v = random.uniform(.4, .789)
        I = Planck(v, T)
        a = I/I0
        if a >= 1:
            v0 = v
            I0 = I
        else:
            p = random.random()
            if a <= p:
                v0 = v
                I0 = I
        yield v0


# a bunch of utility functions to get to proper units


def to_eV(v):
    return v * 4.135668


def to_nm(v):
    return 299.8/v


def from_K(T):
    return T * 1.e-4


def from_THz(v):
    return v * 1.e-3

# example histogram for some temperature

temp = 6500  # in Kelvin

data = [to_nm(v) for v, _ in zip(MC(from_K(temp)), range(100000))]  # in nanometers, from 100k samples.

binbot = ceil(min(data))
bintop = floor(max(data))
bincount = int(bintop-binbot)
bins = np.linspace(binbot,
                   bintop,
                   bincount)

plt.xlim([min(data), max(data)])

plt.hist(data, bins=bins, alpha=0.5)
plt.title('spectral distribution of ' + repr(temp) + 'K light source')
plt.xlabel('nm')
plt.ylabel('count')

plt.show()

If you find a way to properly mix and covert spectral values into RGB, then this would be the method to sample from a given blackbody radiation lightsource.
I'm well aware that this is the easier part. The conversion ought to be more convoluted.


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 15, 2017, 08:56:17 PM
Hmm, I was trying to generate the conversion from spectrum to RGB and at this point I'm pretty much convinced that the below code for sampling from the spectrum is incorrect. I somehow get the right peak wavelength but it's emphasized much too strongly. Effectively I have super saturated light. Presumably I'm doing something wrong with the MC sampling. If somebody can spot the error I'd much appreciate it.
Assuming that indeed is where my error lies, converting to RGB will be easier than I thought. All I need to do, apparently, is first convert to XYZ color space via some matrix transformation given by CIE, then add up all my values in that space, then normalize as wanted and convert to an appropriate color space, for instance sRGB, which is just another simple matrix transformation.


Title: Re: What colour is a Koch curve?
Post by: claude on March 15, 2017, 09:04:46 PM
The hardest part is wavelength to XYZ, which you can do by looking up into a table of tristimulus response curves.

EDITED to add, I once collected some facts from wikipedia into a small reference document: https://mathr.co.uk/misc/2015-04-04_colour.pdf maybe is useful


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 16, 2017, 12:16:08 AM
I'm basically doing that but I get a super saturated cyan (if I use XYZ to sRGB as I found on some website) or super saturated purple (if I give wolfram alpha the resulting XYZ values and ask it to give me the color).
I think I may have flipped a < in the MC function. It makes more sense to have it go the other way from how I put it in the function. If I change that, I get a bluish grey which is a lot better (I'm not entirely sure which values are supposed to be exactly white. Probably .33 for all three?) but then the spectrum does NOT peak where it is supposed to, whereas with the opposite convention it peaks right where I want it to but it's evidently too narrow.
Something really weird is going on here. I must misremember something about how the MC algorithm works. Or else, the spectrum-to-XYZ and/or XYZ-to-RGB data I got are bogus.


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 16, 2017, 12:46:53 AM
"Ah so the other coloration would just be chromatic aberration, the lens defect? Seems unnecessary. It'd not be fractal-specific."
which other coloration do you mean? I talked about coloration due to total internal reflection when the curve is translucent, the main effect is when reflected light and refracted light interfere, it causes some of the brighter plumage on parrots for instance.
"What you already cover, then, is what you get from grid diffraction, right?"
well it is the same principle I suppose, but the diagram I gave with the blue waves is clearer than anything I could write.

What I am less clear on is the origin of the beam width (where light interferes rather than intensities adding linearly), one justification is that all lenses can only focus to a small spot size (not a point), so equivalently, any point on your retina (a cone for instance) gets light from a small spot on the fractal. Does this justify interference? or is it to do with the spatial coherence of the incident light source?
Either way, the spot size doesn't affect the colour unless it is tiny, its just more blurry if big.

"first convert to XYZ color space via some matrix transformation given by CIE, then add up all my values in that space, then normalize as wanted and convert to an appropriate color space, for instance sRGB, which is just another simple matrix transformation."
Yes, this is what the code in answer 6 of the link I mentioned does (http://stackoverflow.com/questions/1472514/convert-light-frequency-to-rgb (http://stackoverflow.com/questions/1472514/convert-light-frequency-to-rgb)). It uses an analytic approximation of the light sensitivity curves to get to XYZ then converts to RGB.

I don't think I'll try a black body white light as, well its all getting pretty complicated! and I think at this point the results won't look too different, probably a bit more green in them. The interesting result for me is that the curve changes colour with view angle (flipping every 30 degrees) even under ambient light. Perhaps some crystals are like this? if so then the connection is just that both are regular shapes... the randomised Koch curve had no colour on average. Or perhaps I'm just doing it wrong  :)

Thanks for the link Claude, I must read this and gain some more understanding. I'll also chuck the code on github.


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 16, 2017, 07:06:06 PM
I found my error! Two errors, in fact. What I get now does indeed look like it should. Conversion from spectrum to color seems to work too, pretty much. The only thing I'm still not entirely sure about is how to properly normalize the color I get. If I simply divide by the number of samples taken I get some slightly colored grey rather than white. From what I gathered I could also normalize it such that the Y value ends up at 1 which, if I understood right, means the color I get will be at the maximum brightness of the color system (though I might still get some hue since it isn't "perfect white")

Perhaps this is usable as is to you either way. It's fairly straight forward code. If you need me to explain anything, just ask away. I'd love to see full-spectrum Koch gears.

Code:
from math import exp, floor, ceil
import random
import numpy as np
from matplotlib import pyplot as plt
import csv


# a bunch of utility functions to get to proper units


def to_eV(v):
    return v * 4.135668


def to_nm(v):
    return 299.8/v

def from_nm(v):
    return 299.8/v

def from_K(T):
    return T * 1.e-4


def from_THz(v):
    return v * 1.e-3

C = 77.766  # prefactor such that peak is 1
K = 4.79924  # prefactor if units are in PHz and 10^4 K
# desired range for v is .4 to .789
# desired range for T is 7.98e-2 to 2.
# typical range would be .5 to .7, commonly .65


def Planck(v, T):  # the distribution of spectral frequencies for a given temperature
    vT = v / T
    return C * vT * vT * vT / (exp(K * vT) - 1)

topPHz = from_nm(390)
botPHz = from_nm(830)


def MC(T):  # generates samples from the distribution using Markov Chain Monte Carlo method
    v0 = random.uniform(botPHz, topPHz)
    I0 = Planck(v0, T)
    while True:
        v = random.uniform(botPHz, topPHz)
        I = Planck(v, T)
        a = I/I0
        if a >= 1:
            v0 = v
            I0 = I
        else:
            p = random.random()
            if p < a:
                v0 = v
                I0 = I
        yield v0

# example histogram for some temperature

samples = 1000000
temp = 5777  # in Kelvin

data = [to_nm(v) for v, _ in zip(MC(from_K(temp)), range(samples))]  # in nanometers, from 100k samples.

specxyz = []
with open('lin2012xyz10e_fine_7sf.csv', newline='') as inputfile:
    for row in csv.reader(inputfile):
        specxyz.append(row)

col = (0, 0, 0)

r, g, b = 0., 0., 0.
for d in data:
    x = d*10 - 3900
    i = floor(x)
    y = x - i
    vals = zip(specxyz[i], specxyz[i + 1])
    ivals = []
    for v in vals:
        ivals.append(float(v[0])*(1-y) + float(v[1])*y)
    r += ivals[1]
    g += ivals[2]
    b += ivals[3]

t = r + g + b
r /= g

b /= g
g = 1

def xyztorgb(x, y, z):
    r = 3.2404542 * x - 1.5371385 * y - 0.4985314 * z
    g = -0.969266 * x + 1.8760108 * y + 1.8760108 * z
    b = 0.0556434 * x - 0.2040259 * y + 1.0572252 * z
    return r, g, b

print('XYZ')
print(r)
print(g)
print(b)
print()
r, g, b = xyztorgb(r, g, b)

r = int(min(1, max(0, r)) * 255)
g = int(min(1, max(0, g)) * 255)
b = int(min(1, max(0, b)) * 255)

print('RGB')
print(r)
print(g)
print(b)
print()

binbot = ceil(min(data))
bintop = floor(max(data))
bincount = int(bintop-binbot)
bins = np.linspace(binbot,
                   bintop,
                   bincount)

plt.xlim([min(data), max(data)])

plt.hist(data, bins=bins, alpha=0.5)
plt.title('spectral distribution of ' + repr(temp) + 'K light source')
plt.xlabel('nm')
plt.ylabel('count')

plt.show()

It will output a plot of the sampled spectrum's histogram as well as the corresponding XYZ and RGB values (using a XYZ-to-RGB matrix I found somewhere)

The file "lin2012xyz10e_fine_7sf.csv" is just a csv I got from here: http://cvrl.ioo.ucl.ac.uk/
In particular, and this might be a slight error, not quite sure, I used
"10-deg XYZ CMFs transformed from the CIE (2006) 2-deg LMS cone fundamentals"
in
"New CIE XYZ (from LMS) functions (proposed)"

I picked (and in this code it's hardcoded) the 0.1nm option as a csv file.

What might be problematic about that is the "proposed": It's a new standard that's apparently not yet in common use. Presumably it's more accurate than the old version, however it might actually need a slightly different matrix to convert from XYZ to sRGB. Not sure.

And I chose the variant where I normalize my XYZ such that Y = 1 which might not actually be what you'd want to do.

My output for a 5777K lightsource ended up being
Code:
XYZ
0.9739410242962122
1
0.9990353465096308

RGB
255
255
231

(http://i.imgur.com/dxb3W8r.png)

Which agrees really well with an actual visible portion of a black body spectrum of this temperature.

EDIT:

So the way this works would be, you'd use spectral data to calculate the color of your gear (use lots of samples. The more samples, the closer to actual white your light source will be). You don't actually need to store the whole spectrum: Just convert each final ray as it hits the camera into XYZ colors using the lookup table from the page I linked above. In the XYZ color space, add everything up. If I understood right, it's conveniently linear, so adding up in spectral space and then converting to XYZ is the same as converting to XYZ and then adding up in that space.
Then, once your render is finished, first find your maximum Y value and normalize the entire image by that. That will mean that no point is actually brighter than this. If you are concerned with saturation-clipping, it might help to actually make the brightest point darker, so normalize it such that the maximum Y is only like .8 or something. Then, convert it all over to your desired color space, for instance, for screens, the sRGB color space. That then is the final image.

Oh and the way I set it up in the python script above, I actually interpolate wavelengths linearly to get an approximate color for wavelengths that aren't exactly .1nm. Presumably, at that resolution, you could also just round them. Would probably work just as well.


Title: Re: What colour is a Koch curve?
Post by: lycium on March 16, 2017, 08:54:35 PM
Hi Mark, cool to see you doing some spectral ray tracing, deja vu? :D

I don't see why you're using importance sampling for the wavelengths, and via a massively overpowered method like MCMC; there isn't even that much variance, and the visible spectrum is rather "small" 1D domain. I'd recommend simply using eg. 8 wavelengths at once, uniformly spaced with a random offset in range [0, 1/8).

I'd be interested to look at and mess around with the code for Koch curve rendering when it gets released; I'm good at ray tracing / path tracing, but don't understand how the surface reflection model works, probably due to my very limited knowledge of quantum mechanical effects in light reflection.


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 16, 2017, 11:54:20 PM
I'm not sure how accurate it'd need to be - how much of a visual difference it'd make. Maybe 8 samples are enough. - Heck, maybe the full spectral result wouldn't even look so different from the already shown 3 sample take. But I think it should be tried at least once, just to see if the difference is worth it.
That the spectrum is fairly uniform kind of is the point though: It's supposed to be white light after all.

I'd also like to see the code. I have a rough idea how it works. If I got what you said right, Tglad, you're currently actually using the HSV colorspace to get a proxy conversion from "wavelengths" (actually hues) to RGB?


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 17, 2017, 12:33:41 PM
here is the code: https://github.com/TGlad/FractalColour2D (https://github.com/TGlad/FractalColour2D), using 10 frequency samples by default. It will make 60 .bmp files in a folder called kochs. I just use http://gifcreator.me/ (http://gifcreator.me/) to convert it to a gif.


Title: Re: What colour is a Koch curve?
Post by: lycium on March 17, 2017, 02:07:16 PM
Just in time for the weekend :) Thanks for sharing, Tglad!

Edit: zomg the code is so complex  :o


Title: Re: What colour is a Koch curve?
Post by: claude on March 17, 2017, 05:30:09 PM
EDITED to say, this code is buggy (should consider 2x the distance to the surface in the interference calculations), will post corrected version soon

I had a go using distance estimation ray marching, see attached image and C99 source code.  Took 35mins to render the image on my quad core desktop...

The image shows the Koch curve horizontally, and each scanline is at a different scale (with a factor of 3 between the top row and the bottom row, interpolated exponentially).

Light is parallel to ray direction, heading vertically down towards the curve in its traditional orientation.


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 17, 2017, 11:02:35 PM
so this one has multiple reflections and thus is much brighter? Or how does that work? It looks pretty.
At that render time I don't suppose doing a rotating version will be feasible?


Title: Re: What colour is a Koch curve?
Post by: claude on March 18, 2017, 02:07:42 PM
so this one has multiple reflections and thus is much brighter? Or how does that work? It looks pretty.
At that render time I don't suppose doing a rotating version will be feasible?

No just one hit point per ray, I think it was 32 rays per pixel, accumulated over a 10-pixel region.  It might be more saturated because the rays are equally spaced instead of randomly sampled?  Not sure.

Some things could be tuned to reduce render time, like number of wavelengths, number of rays per pixel, number of ray steps, distance estimator recursion depth.  Some things are totally unoptimized - it traces the rays for each wavelength, when it could cache the distances and just redo the phasor additions...


Title: Re: What colour is a Koch curve?
Post by: claude on March 19, 2017, 09:06:44 PM
Here's some fixed code that renders one scale, rotating through 60 degrees.  1024 rays per pixel equally spaced over 4 pixels with a raised cosine magnitude window.

It took so long to render the first 30deg (45mins) that I did the second half by rotating the first half in GIMP instead, should have thought about the symmetry before launching the code.


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 20, 2017, 02:59:03 AM
It's really good to see an independent confirmation of the overall effect that the colour flips every 30 degrees, I think that those intermediate colours (the oranges) would blend out if you did it under ambient light, rather than your single front-facing light. The brighter image is just a stronger incident light compared to mine (roughly 4th one down):
(https://2.bp.blogspot.com/-ZUl-2eL4aJs/WLvuxoqS1yI/AAAAAAAABIE/ywkYveZ2_hsZrN2Z1_uajx47cvcy317twCLcB/s200/rc.bmp)
You also seem to be scaling the wavelength of light (vertically) rather than the actual size of the fractal... so there's a slight difference between ours in the scaling of the spot size. I'm also only using 3 spectrum samples (r,g,b) in that image.

A nice thing about using the DE approach is that it is simple and could migrate to 3D fractals, but an advantage of my more complicated code is that it is super-quick for 2D curves, takes about 20s per image (which uses 20 incident light angles, and 10 spectrum samples), and I haven't tried openMP yet.

Kram, I haven't tried multiple bounces, but it seems to me that if the reflectivity was 1 then all colour would be lost, so higher reflectivity probably just reduces colouration... but that's just an educated guess.


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 22, 2017, 11:01:57 AM
I have tidied up the description: https://sites.google.com/site/tomloweprojects/scale-symmetry/what-colour-are-fractals (https://sites.google.com/site/tomloweprojects/scale-symmetry/what-colour-are-fractals)
and included a gif for the levy curve and dragon curve:
(https://1.bp.blogspot.com/-OoWWmCn1G8s/WNEHXAiJxyI/AAAAAAAABMM/jDR4FNG0Mf82bdSJJKF-x7ugeCKEzFihgCLcB/s1600/levy.gif)
(https://4.bp.blogspot.com/-Zkr3mSULVzQ/WND5EPVQU0I/AAAAAAAABLw/2hOshezYkJwqMJNk7pwDvPu0JhwwkR7igCLcB/s1600/dragon.gif.gif)

The colour sensitivity functions I was using weren't working so I reverted to a much simpler 7 frequency samples. I doubt more samples makes much difference as it isn't spikey in frequency.

Each of these similar curves gives a different colour behaviour.


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 22, 2017, 11:49:11 AM
the lower one is the dragon curve? Looking great!


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 26, 2017, 06:39:51 AM
Yes, that's right. Shows much more colour.


Title: Re: What colour is a Koch curve?
Post by: claude on March 29, 2017, 11:31:42 PM
Here's one rotating:

(https://mathr.co.uk/misc/2017-03-29_koch_curve_colour.gif)

32 rays per pixel, positions randomized slightly.

I found that the magic number (6e-5 in the attached) to match wavelength to structure size is crucial, too small and colours are very saturated but noisy/grainy, too large and it blends to white (relatively large spot size).  I guess measuring everything in terms of wavelengths would be one way to deal with this properly.

EDITED to add: 10mins render time total for 60 frames at 128x128, previous images were so slow due to needing many more rays to reduce noise with small scaling (magic number), and rendered at larger resolutions


Title: Re: What colour is a Koch curve?
Post by: kram1032 on March 29, 2017, 11:43:44 PM
neat! what kind of scaling are you using here? It looks like you're reducing the size by a factor of 3 as you go down, but it isn't linear rescaling. Is it exponential?


Title: Re: What colour is a Koch curve?
Post by: Tglad on March 30, 2017, 03:17:00 AM
Great Claude, it looks nice.
The spot size itself seems to be based on two things:
1. the resolving power of our eyes, according to http://www.wikilectures.eu/index.php/Resolution_of_human_eye (http://www.wikilectures.eu/index.php/Resolution_of_human_eye) we can resolve about 100 microns at screen distance.
2. the spatial coherence of the incident light (how similar is the light wave laterally), according to https://www.photonics.ethz.ch/fileadmin/user_upload/pdf/Papers/divitt15a.pdf (https://www.photonics.ethz.ch/fileadmin/user_upload/pdf/Papers/divitt15a.pdf) the coherence is about 7 to 80 times the wavelength of sunlight for overcast and clear sky respectively. So 3.5 to 40 microns.
Since the second one is smaller, the light coherence seems to the one that matters, and affects the interference width. Either way the spot size doesn't make much difference to the colour unless it is really foggy (e.g. coherence width less than 7 times wavelength of light), then becomes less colourful.

Here are some more:

(https://sites.google.com/site/tomloweprojects/_/rsrc/1490782488173/scale-symmetry/what-colour-are-fractals/Minkowski.jpg?height=132&width=200)(https://4.bp.blogspot.com/-tZgIMq-MJe0/WNuJm2hWaGI/AAAAAAAABMo/s9utcBlu9DALpaTtXeWo0aQ-utMPmHMlwCLcB/s1600/minkowskisausage.gif)

(https://sites.google.com/site/tomloweprojects/_/rsrc/1490830220134/scale-symmetry/what-colour-are-fractals/square1.png?height=139&width=200)(https://1.bp.blogspot.com/-f_6TqjJuVpM/WNxCr0oyxUI/AAAAAAAABN8/VD9I0-C2PKAbJ0inb9SMwupZ1XVKXXC7ACLcB/s1600/minkowskimushroom.gif)

(https://sites.google.com/site/tomloweprojects/_/rsrc/1490782953827/scale-symmetry/what-colour-are-fractals/vicsek.png?height=156&width=200)(https://1.bp.blogspot.com/-h86HEzM-F8Y/WNuOSAuRuqI/AAAAAAAABNE/Sy56cU1szZQayNdAJyGekX6J5bZBOSr5wCLcB/s1600/vicsek.gif)


Title: Re: What colour is a Koch curve?
Post by: claude on March 30, 2017, 03:30:30 AM
neat! what kind of scaling are you using here? It looks like you're reducing the size by a factor of 3 as you go down, but it isn't linear rescaling. Is it exponential?

Yes exponential, so if you stack two copies of the image on top it should make smooth curves through both.