无法读取图像,因为列表索引错误



我正在尝试使用以下代码从本地Jupyter Notebook上的目录读取图像:

当我在Colab上尝试相同的代码时,它工作得很好,但在Jupyter Notebook中,我得到IndexError: list index out of range错误

什么是错误的,当我实现这个代码在jupyter笔记本?

images = []
image_names = []
image_dir = 'flickr-30k-final/*.jpg'
for img in glob.glob(image_dir):
x = img.split("/")
name = x[1].split("\") # Change the index based on the number of subdirectories you have. Index Starts from 0.
image_names.append(name[0])
cv_img = cv2.imread(img)
images.append(cv_img)

详细错误输出:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
~AppDataLocalTempipykernel_290083390765231.py in <module>
5 for img in glob.glob(image_dir):
6     x = img.split("/")
----> 7     name = x[1].split("\") # Change the index based on the number of subdirectories you have. Index Starts from 0.
8     image_names.append(name[0])
9     cv_img = cv2.imread(img)

假设一个示例图像路径在将目录分割为"/"看起来像:

flickr-30k-final\imagename.jpg

下一行的索引值应该是1而不是0

image_names.append(name[0])
因此,您的最终代码应该看起来像:
images = []
image_names = []
image_dir = "flickr-30k-final/*.jpg"
for img in glob.glob(image_dir):
x = img.split("/")
name = x[0].split("\") # Change the index based on the number of subdirectories you have. Index Starts from 0.
image_names.append(name[1])
cv_img = cv2.imread(img)
images.append(cv_img)

这样做,如果成功运行,只需打印image_names变量并查看其输出,应该打印出所有图像名称的列表

相关内容

  • 没有找到相关文章

最新更新