1

I was asked to make the figure of the image bellow, using a grid (100,100) with the np.meshgrid and np.angle() and my only problem is that when i want to make the final boolean grid, python says: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

from PIL import Image
import numpy as np

XX = np.arange(0,101)
YY = np.arange(0,101) 
x, y = np.meshgrid(XX, YY)

x = x-50
y = y-50

z = x+ y*-1j

print z    

a = np.angle(z,deg=True)

grid = (a>=0 and a<20) or (a>=40 and a<60) or (a>=80 and a<100) or (a>=120 and a<140) or++ (a<=-20 and a>-40) or (a<=-60 and a>-80) or (a<=-100 and a>-120) or (a<=-140 and a>-160)


grid = grid.astype('uint8') * 255
new_img = Image.fromarray(grid ,'L') 
new_img.save("grid .bmp")
poke
  • 369,085
  • 72
  • 557
  • 602
Brain_Stop
  • 15
  • 3
  • Please see related: http://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous?rq=1 – EdChum Mar 27 '15 at 20:49

2 Answers2

4

A couple of issues:

1) When giving us an error message, you should indicate which code line it refers to.

2) This is one of the most frequent error messages in SO questions (related to Python and numpy).

My guess is that the error occurs in:

grid = (a>=0 and a<20) or (a>=40 and a<60) or (a>=80 and a<100) or (a>=120 and a<140) or++ (a<=-20 and a>-40) or (a<=-60 and a>-80) or (a<=-100 and a>-120) or (a<=-140 and a>-160)

and is caused by two things

1) the use of and/or instead of &/|

2) the priority of >= kind of operators relative to the &/|. Put () around the former.


In [168]: a=np.arange(10)

In [169]: (a>=0 and a<20) or (a>=40 and a<60) or (a>=80 and a<100)
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

In [171]: ((a>=0) & (a<20)) | ((a>=40) & (a<60)) | ((a>=80) & (a<100))
Out[171]: array([ True,  True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)

So the correct expression is

((a>=0) & (a<20)) | ((a>=40) & (a<60)) | ((a>=80) & (a<100)) ...
hpaulj
  • 221,503
  • 14
  • 230
  • 353
1

Try & and | or * and +, respectively for and and or.

"and" and "or" compares the whole truthiness of the whole object, but you want the analogue of element-wise and. There is are also numpy functions logical_and and logical_or to be more explicit.

mdurant
  • 27,272
  • 5
  • 45
  • 74