Migrate python2 to 3 IndexError: only integers, slices (`:`), ellipsis (`…`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

Question:

So I try to migrate legacy python2 script to python3 but i got error on the some code

print ('resizing images')
for x in range(0, len(img)):
    imgResized.append(cv2.resize(img[x], (301 * len(img), 301)))

print ('resizing done')
source = interlace(imgResized, 301 * len(img), 301 * len(img))
cv2_im = cv2.cvtColor(source, cv2.COLOR_BGR2RGB)

so i got error on source = interlace(imgResized, 301 * len(img), 301 * len(img))
that interlance its function for do

def interlace(img, h, w):
    inter = np.empty((h, w, 3), img[0].dtype)
    for i in range(h - 1):
        val = i % NUM_FRAMES
        print('index') 
        print(img[val])
        inter[i, :, :] = img[val][i / NUM_FRAMES, :, :]
    return inter

on the interlace function the error come from inter[i, :, :] = img[val][i / NUM_FRAMES, :, :]

this the complete stacktree

Traceback (most recent call last):
  File "/Users/sagara/Downloads/Printing Script/mnd_75 (latest).py", line 171, in <module>
    source = interlace(imgResized, 301 * len(img), 301 * len(img))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/sagara/Downloads/Printing Script/mnd_75 (latest).py", line 126, in interlace
    inter[i, :, :] = img[val][i / NUM_FRAMES, :, :]
                     ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

and the print console from print('index')and print(img[val])i got this value

index
[[[239 236 238]
  [240 237 240]
  [247 245 246]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 [[211 208 210]
  [215 212 214]
  [233 230 232]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 [[229 227 228]
  [232 229 231]
  [242 240 242]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 ...

 [[149 151 152]
  [159 161 162]
  [200 202 203]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 [[156 158 159]
  [166 168 169]
  [204 206 207]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 [[128 129 131]
  [140 142 143]
  [190 192 192]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]]

its maybe because the img[val] its in not correct value?

Asked By: Rofie Sagara

||

Answers:

The issue is that i / NUM_FRAMES is a float. You need to cast to an integer using the int() function or use the integer division operator, //

i // NUM_FRAMES
Answered By: Roy Smart
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.