简体   繁体   English

如何解决停止迭代错误? 我收到 Traceback(最近一次通话最后一次)错误

[英]How to solve stopiteration error? i got Traceback (most recent call last) error

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帮我

os.walk returns a generator which is a type of iterator. os.walk返回一个生成器,它是一种迭代器。 Iterators emit values from a sequence and then raise StopIteration when done.迭代器从序列中发出值,然后在完成时引发StopIteration next tries to get the next value from an iterator. next尝试从迭代器中获取下一个值。 The iterator, following the rules just noted, will either return the next value or raise StopIteration .遵循刚才提到的规则,迭代器将返回下一个值或引发StopIteration

Since you saw StopIteration on the first next call, it means that os.walk didn't find the path at all.由于您在第一次next调用时看到了StopIteration ,这意味着os.walk根本没有找到路径。 There was nothing to iterate, so StopIteration was raised immediately.没有要迭代的内容,因此立即引发了StopIteration 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.您可以执行print(os.getcwd())来查看当前路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM