由于列表索引错误而无法读取图像

Unable to read images because of list index error

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

虽然我在 Colab 上尝试了相同的代码,但它工作正常,但在 Jupyter Notebook 中我收到 IndexError: list index out of range 错误

我在 jupyter notebook 中实现这段代码有什么问题?

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)
~\AppData\Local\Temp\ipykernel_2900890765231.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 变量并查看其输出,应该打印所有图像名称的列表