20 May 2012

Visible light spectrum to RGB

Some of my recent work has required me to become better versed in color spectrum properties and some of the multitudes of ways we've created to try and classify it. Dr. Dan Bruton has a really excellent and understandable page at http://www.midnightkite.com/color.html, including some FORTRAN code to convert wavelength values to RGB.

It's been very handy for plotting some of the data I've been collecting lately, especially with scatter3, when I still have wavelength as a variable to account for in the output.

I tweaked the code for MATLAB and am posting this version here with his permission. Hope it's useful for someone...

%%Wavelength to RBG code was modified from Dan Bruton's FORTRAN code at
%%http://www.physics.sfasu.edu/astro/color/spectra.html
%%Only RGB was kept, Gamma and intensity SSS were for unavailable data
%%Further details and explanation at:
%%http://www.midnightkite.com/color.html


%set wavelength to the name of your vector of values to convert
RGB = zeros(length(wavelength), 3); 
for i = 1:length(wavelength)
    %set wavelength to the name of your vector of values to convert
    w = wavelength(i);
    if w >= 380 && w < 440
        RGB(i,:) = [(w-440)/(440-380) 0.0 1.0];
    elseif w >= 440 && w < 490
        RGB(i,:) = [0.0 (w-440)/(490-440) 1.0];
    elseif w >= 490 && w < 510
        RGB(i,:) = [0.0 1.0 -(w-510)/(510-490)];
    elseif w >= 510 && w < 580
        RGB(i,:) = [(w-510)/(580-510) 1.0 0.0];
    elseif w >= 580 && w < 645
        RGB(i,:) = [1.0 -(w-645)/(645-580) 0.0];
    elseif w >= 645 && w <= 780
        RGB(i,:) = [1.0 0.0 0.0];
    else
        RGB(i,:) = [0 0 0];
    end
end

No comments:

Post a Comment