1

I would to print the images on index i but I get an error of only integer scalar arrays can be converted to a scalar index. How can I convert I to int for each iteration

I have tried replacing images[i] with images[n] it worked but not the result I want.

c = [1 1 1 0 1 2 2 3 4 1 3]
#c here is list of cluster labels obtained after Affinity propagation 
num_clusters = len(set(c))
images = os.listdir(DIR_NAME)

for n in range(num_clusters):
   print("\n --- Images from cluster #%d ---" % n)
   for i in np.argwhere(c == n):
     if i != -1:
        print("Image %s" % images[i])

I expect the output to be the name of the image, but I instead get TypeError: only integer scalar arrays can be converted to a scalar index that is because i is of type numpy.ndarray

Biasi Wiga
  • 106
  • 9
  • Have you looked at the output of `argwhere`, at `i`? What's the purpose of the -1 test? – hpaulj May 30 '19 at 14:58
  • yes I did is type of `numpy.ndarray` – Biasi Wiga May 30 '19 at 16:32
  • `argwhere` doesn't produce `-1` (like some string or list 'find' methods). The array will have 0 rows if it doesn't find a match. I'd suggest printing `c==n`, `np.where(c==n)` and `np.argwhere(c==n)` to get a better sense of what that code does. – hpaulj May 30 '19 at 19:03

1 Answers1

1

Look at the doc of np.argwhere, it does not return a list of integers, but a list of lists

x = array([[0, 1, 2], [3, 4, 5]])
np.argwhere(x>1)
>>> array([[0, 2], [1, 0], [1, 1], [1, 2]])

y = np.array([0, 1, 2, 3, 4, 6, 7])
np.argwhere(y>3)
>>> array([[4], [5], [6]])

so without knowing what your c looks like, I assume your i will be of the form np.array([[3]]) instead of an integer, and therefore your code fails. Print i for testing and extract (e.g. i[0][0] and a test that it is non-empty) the desired index first before you do i != -1.

Meta

It is best practise to post a minimal reconstructable example, i.e. other people should be able to copy-paste the code and run it. Moreover, if you post at least a couple lines of the traceback (instead of just the error), we would be able to tell where exactly the error is happening.

Snow bunting
  • 1,120
  • 8
  • 28