0

This is the code that i wrote:

img_files = next(os.walk('MyDrive/FYP/Fig_Dataset'))[2]
msk_files = next(os.walk('MyDrive/FYP/Ground_Truth'))[2]

img_files.sort(2)
msk_files.sort(2)

print(len(img_files))
print(len(msk_files))

X = [2]
Y = [2]

for img_fl in tqdm(img_files):    
if(img_fl.split('.')[-1]=='jpg'):
    img = cv2.imread('MyDrive//FYP/Fig_Dataset/{}'.format(img_fl))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    resized_img = cv2.resize(img,(256, 192), interpolation = cv2.INTER_CUBIC)
    X.append(resized_img)
    
msk = cv2.imread('MyDrive//FYP/Ground_Truth/{}'.format(img_fl.split('.')[0]+'_segmentation.png'),cv2.IMREAD_GRAYSCALE)
    resized_msk = cv2.resize(msk,(256, 192), interpolation = cv2.INTER_CUBIC)
    Y.append(resized_msk)

And this is the error that i got

StopIteration                             Traceback (most recent call last)
<ipython-input-19-40a26ba7758c> in <module>()
----> 1 img_files = next(os.walk('FYP/Fig_Dataset'))[2]

i dont know how to solve this. Help me

  • `[2]` is apparently out of range for that iterator. Have you tried `print(list(os.walk('MyDrive/FYP/Fig_Dataset')))` to confirm how many entries exist? – Cory Kramer Apr 19 '22 at 15:41
  • Here is a similar question: https://stackoverflow.com/questions/65013199/stopiteration-error-while-trying-to-build-data-input-for-a-model – user16941410 Apr 19 '22 at 15:43
  • 1
    `os.walk` returned an iterator, but there wasn't anything to iterate. The `next` had nothing to emit, so rasied StopIteration. This is the normal thing when a directory doesn't exist or is empty. If that's a normal case, then catch the exception and stop the other work. Otherwise its a legitimate indication of a bug. – tdelaney Apr 19 '22 at 15:45

1 Answers1

0

os.walk returns a generator which is a type of iterator. Iterators emit values from a sequence and then raise StopIteration when done. next tries to get the next value from an iterator. The iterator, following the rules just noted, will either return the next value or raise StopIteration.

Since you saw StopIteration on the first next call, it means that os.walk didn't find the path at all. There was nothing to iterate, so StopIteration was raised immediately. You could catch this exception as a way of knowing that the directory itself was invalid.

try:
    fig_path = 'MyDrive/FYP/Fig_Dataset'
    img_files = next(os.walk('MyDrive/FYP/Fig_Dataset'))[2]
    msk_files = next(os.walk('MyDrive/FYP/Ground_Truth'))[2]
except StopIteration:
    print("Directory not found")
    exit(2)

The remaining question is why these paths aren't correct. You could do print(os.getcwd()) to see your current path.

tdelaney
  • 73,364
  • 6
  • 83
  • 116