1

I know that I can get the true bits with the simple loop, but looping is ridiculously slow

   locations = []
   width, height = mask.shape[0], mask.shape[1]
   for x in range(len(0,width)):
      for y in range(len(0,height):
        if mask[x][y] is 1:
          location.append([x,y])

I kidda what to avoid the loop overhead. I am learning python and I do not understand this array[:] thing

4

1 に答える 1

2

You can use nonzero. It returns the indices grouped by axis -- in other words, a tuple of the form (array([x1, x2, x3,...]), array([y1, y2, y3,...]), array([z1, z2, z3,...]),...):

>>> a = numpy.array([[0, 0], [0, 1], [1, 0]], dtype=numpy.bool)
>>> numpy.nonzero(a)
(array([1, 2]), array([1, 0]))

You can use the result as an index to get the nonzero values:

>>> a[numpy.nonzero(a)]
array([ True,  True], dtype=bool)
于 2012-06-23T20:27:50.660 に答える