Reputation: 372
I'm trying to convert a 2d NumPy array of complex numbers into another 2d array RGB values for an image, by mapping a function over the array.
This is the function:
import numpy as np
import colorsys
def ComplexToRGB(complex):
angle = ((np.angle(complex,deg=True)+360)%360)/360
magnitude = np.absolute(complex)
rawColor = colorsys.hls_to_rgb(angle,0.5,1-np.log2(magnitude)%1)
return rawColor
I map this function over an array by passing the array as input:
print(ComplexToRGB(foo))
where foo
is foo=np.linspace(-1-1j,1+1j,11)
.
When I pass a single complex number as an input, I don't get an error, but when I try to use an array as an input, I get the rather mysterious error
Exception has occurred: ValueError
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
File "C:\Users\trevo\Documents\GitHub\NumPy-Complex-Function-Grapher\colorTest.py", line 7, in ComplexToRGB
rawColor = colorsys.hls_to_rgb(angle,0.5,1-np.log2(magnitude)%1)
File "C:\Users\trevo\Documents\GitHub\NumPy-Complex-Function-Grapher\colorTest.py", line 12, in <module>
print(ComplexToRGB(foo))
I understand that you can't use Boolean conditionals when you map over an array, but I don't have any logic in my function, just math, so I'm not user where the error is coming from. Thanks for your help!
Upvotes: 0
Views: 121
Reputation: 231355
With a single complex number:
In [3]: ComplexToRGB(1+3j)
Out[3]: (0.6041685072417726, 0.6695179762781593, 0.33048202372184066)
same thing with a single element array:
In [4]: ComplexToRGB(np.array(1+3j))
Out[4]: (0.6041685072417726, 0.6695179762781593, 0.33048202372184066)
In [5]: ComplexToRGB(np.array([1+3j]))
Out[5]: (array([0.60416851]), array([0.66951798]), array([0.33048202]))
but with a 2 element array:
In [6]: ComplexToRGB(np.array([1+3j]*2))
Traceback (most recent call last):
File "<ipython-input-6-a1b8e92d5dcc>", line 1, in <module>
ComplexToRGB(np.array([1+3j]*2))
File "<ipython-input-1-05948df7c0bd>", line 6, in ComplexToRGB
rawColor = colorsys.hls_to_rgb(angle,0.5,1-np.log2(magnitude)%1)
File "/usr/lib/python3.8/colorsys.py", line 99, in hls_to_rgb
if s == 0.0:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
You may not have any explicit logic in your code, but the Python colorsys
code does do a if
test. colorsys
is a base Python module, and is not written with numpy
arrays in mind.
Read the full traceback, and if necessary, read the docs of the relevant function(s).
Upvotes: 1