IndexError: list index out of range - when plotting images

IndexError: list index out of range - when plotting images

编写了一个函数来显示来自 2 个不同文件夹的 6 张胸部 X 光图像。图像被分成包含在 1 个文件夹中的 2 个文件夹。 (训练数据是主文件夹,里面有 2 个文件夹名称 'PNEUMONUA' 和 'NORMAL'。

当我 运行 对一个文件夹中的图片使用该功能时,它完美运行,当我对另一个文件夹使用该功能时,我得到 "Index Error: list index out of range."

代码:

TRAINING_DATA = "/home/jack/Desktop/chest_xray/train/"

TEST_DATA = "/home/jack/Desktop/chest_xray/test/"

VALIDATION_DATA = "/home/jack/Desktop/chest_xray/val/"



def plot_images(path, labeled=True, max_images=6):
  amount = 0
  fig = plt.figure(figsize=(10, 6))

  for file in os.listdir(path):
    if file.endswith('.jpeg'):
      if amount == max_images:
        break

      img = mpimg.imread(os.path.join(path, file))
      plt.subplot(231+amount)
      if labeled:
        plt.title(file.split('_')[1])
      imgplot = plt.imshow(img)

      amount += 1


plot_images(TRAINING_DATA + '/NORMAL')
#ERROR

plot_images(TRAINING_DATA + '/PNEUMONIA')
#WORKS FINE

有什么想法吗?

'NORMAL'文件夹中图片的文件名没有'_'分割(例如IM-0115-0001.jpeg,NORMAL2-IM-0666-0001.jpeg ).所以你不能根据'_'拆分它。

我刚刚评论了你代码中的第 2 行,它工作正常。

TRAINING_DATA = "<path>/chest_xray/train/" 


def plot_images(path, labeled=True, max_images=6):
  amount = 0
  fig = plt.figure(figsize=(10, 6))

  for file in os.listdir(path):
    if file.endswith('.jpeg'):
      if amount == max_images:
        break

      img = cv2.imread(os.path.join(path, file))
      plt.subplot(231+amount)
      plt.title("Normal")
      imgplot = plt.imshow(img)

      amount += 1

plot_images(TRAINING_DATA + '/NORMAL')

希望对您有所帮助。