Page 1 of 1

Wavelength to RGB color

Posted: Mon Jun 08, 2015 6:35 pm
by BasicallyPure
This will convert a visible light wavelength to an approximate RGB color value.
For convenience you can use Ctrl+C to copy the image to the clipboard.

Code: Select all

; Wavelength_to_RGB.pb

; Translated and adapted to PureBasic by BasicallyPure 6/7/2015
;
; RGB VALUES For VISIBLE WAVELENGTHS   by Dan Bruton (astro@tamu.edu)
;
; This program can be found at 
; http://www.physics.sfasu.edu/astro/color.html
; or more specifically here
; http://www.physics.sfasu.edu/astro/color/spectra.html
; And was last updated on February 20, 1996.
;
; This program will create an image of a visible light spectrum.
; The spectrum is generated using approximate RGB values For visible
; wavelengths between 380 nm And 780 nm.
; The red, green And blue values (RGB) are assumed To vary
; linearly With wavelength (For GAMMA=1).
; NetPBM Software: ftp://ftp.cs.ubc.ca/ftp/archive/netpbm/

EnableExplicit

ExamineDesktops()
Define.i W = DesktopWidth(0)/2 ; image width
Define.i H = W/10  ; image height
Define.i flags, X, Ymax = H-1
Define.f wavelength

Declare WAVELENGTH_TO_RGB(WL.f)

CreateImage(0, W, H)

StartDrawing(ImageOutput(0))
   While X < W
      wavelength = 380 + ((X+1) * 400.0 / W) ; scale wavelength between 380 and 780 nm.
      LineXY(X, 0, X, Ymax, WAVELENGTH_to_RGB(wavelength)) ; make the conversion & plot
      X + 1
   Wend
StopDrawing()

flags = #PB_Window_ScreenCentered|#PB_Window_SystemMenu|#PB_Window_MinimizeGadget
OpenWindow(0,0,0,W,H,"visible spectrum | Dan Bruton algorithm",flags)

AddKeyboardShortcut(0,#PB_Shortcut_Control | #PB_Shortcut_C, 0)

ImageGadget(0,0,0,1,1,ImageID(0))

Repeat
   Select WaitWindowEvent()
      Case #PB_Event_CloseWindow : Break
      Case #PB_Event_Menu        : SetClipboardImage(0)
         MessageRequester("","copied to clipboard")
   EndSelect
ForEver

End

Procedure WAVELENGTH_TO_RGB(WL.f)
   ; returns RGB value for visible wavelengths between
   ; 380 nm and 780 nm.  WL = wavelength
   Static GAMMA.f = 0.80
   Static MAX.i   = 255 ; intensity
   Protected.f R, G, B, SSS
   
   If (WL >= 380) And (WL <= 440)
      R = (440 - WL) / 60 : G = 0 : B = 1
   ElseIf (WL >= 440) And (WL <= 490)
      R = 0 : G = (WL - 440) / 50 : B = 1
   ElseIf (WL >= 490) And (WL <= 510)
      R = 0 : G = 1 : B = (510 - WL) / 20
   ElseIf (WL >= 510) And (WL <= 580)
      R = (WL - 510) / 70 : G = 1 : B = 0
   ElseIf (WL >= 580) And (WL <= 645)
      R = 1 : G = (645 - WL) / 65 : B = 0
   ElseIf (WL >= 645) And (WL <= 780)
      R = 1 : G = 0 : B = 0
   EndIf
   
   ; let the intensity fall off near the vision limits
   If WL > 700
      SSS = (780 - WL) / 80
   ElseIf WL < 420
      SSS = (WL - 380) / 40
   Else
      SSS = 1
   EndIf
   
   ; GAMMA adjust
   R = MAX*Pow(SSS*R,GAMMA)
   G = MAX*Pow(SSS*G,GAMMA)
   B = MAX*Pow(SSS*B,GAMMA)
                            
   ProcedureReturn RGB(R,G,B)
EndProcedure