Physicist February 2016

method to circumvent if-else checking

I am just wondering if I want to implement a program that converts wavelength to (r,g,b) using the algorithm in this paper (p5-6): http://www.scientificbulletin.upb.ro/rev_docs_arhiva/full49129.pdf, instead of checking the value of wavelength using if-else like

if wavelength>380 and wavelength<410:
    # do something
elif wavelength<440:
    # do something
elif wavelength<490:
    # do something, and so on

Are there some genius method to avoid using if-else statement so that I can speed up the code? More specifically, suppose I store the wavelengths in a list or a numpy array, is it possible to have some sort of 'vectorized' method to generate the (r,g,b) values?

Answers


MSeifert February 2016

Yes, there are. If you have your wavelengths in a numpy array you can use boolean masks instead of the if ... elif ... clauses.

For your second question about the vectorized operation ... I think you want something like this:

wavelengths = np.array([1,2,3])
conversion = np.array([-0.41,0,0.6]).reshape(3,1) # R, G, B Parts
wavelengths * conversion
# Reshape is needed to get a 3x3 result
array([[-0.41, -0.82, -1.23],
       [ 0.  ,  0.  ,  0.  ],
       [ 0.6 ,  1.2 ,  1.8 ]])

The given formulas are a bit more complicated than this example but StackOverflow isn't about writing you the code. I think with the example you should be able to implement these formulas.

Post Status

Asked in February 2016
Viewed 3,561 times
Voted 7
Answered 1 times

Search




Leave an answer