1

I need to understand the usage of operators in the following python code snippet. I'm not familiar with the usage of * in the np.zeros() statement. It looks like the pointer dereferencing operator in c, but I'm guessing not.

Also, what is the usage of == in the assignment statement? This looks like an equality test, but True and False are not valid indexes into a numpy array.

new_segs = np.zeros((*raw_segs.shape, 3), dtype=np.uint8)
i = 0
for val in [x['handle'] for x in detections]:
    colors = [(255,0,255), (55,0,55), (34,33,87)]
    new_segs[raw_segs == val] = colors[i % len(colors)]

Sorry for the crappy question. Have tried looking for answers but I get unsatisfactory answers with searches on operator usage.

martineau
  • 119,623
  • 25
  • 170
  • 301
tinyMind
  • 155
  • 3
  • 14
  • 1
    `*` is not an operator here: https://stackoverflow.com/questions/2921847/what-does-the-star-operator-mean – Xantium Mar 09 '18 at 00:00

3 Answers3

4

The star * unpacking was explained. The == in numpy is a boolean mask. You are passing an array that should be the same size of the other numpy array but this tells it which elements of the array to include or not.

Totoro
  • 867
  • 9
  • 10
2

The star * is the unpacking operator; it expands raw_segs.shape to a tuple of values.

You're incorrect about indices: True and False are valid, being interpreted as 1 and 0, respectively. Try it and see:

>>> new_segs = np.array((3.3, 4.4))
>>> new_segs[0]
3.2999999999999998
>>> new_segs[True]
4.4000000000000004
>>> 
Right leg
  • 16,080
  • 7
  • 48
  • 81
Prune
  • 76,765
  • 14
  • 60
  • 81
1

* unpacks the shape tuple, allowing it be joined with the 3 to make a bigger shape tuple:

In [26]: x = np.zeros((2,3))
In [28]: y = np.zeros((*x.shape, 3))
In [29]: y.shape
Out[29]: (2, 3, 3)

another way to do that:

In [30]: y = np.zeros(x.shape+(3,))
In [31]: y.shape
Out[31]: (2, 3, 3)

and

In [32]: i,j = x.shape
In [33]: y = np.zeros((i,j,3))
In [34]: y.shape
Out[34]: (2, 3, 3)
hpaulj
  • 221,503
  • 14
  • 230
  • 353