python - 索引错误: list index out of range - when plotting images

标签 python image plot directory index-error

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

当我对一个文件夹中的图片运行该函数时,它工作得很好,当我在另一个文件夹上使用该函数时,我收到“索引错误:列表索引超出范围”。

代码:

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')

希望这有帮助。

关于python - 索引错误: list index out of range - when plotting images,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127117/

相关文章:

python - 带有 numpy 数组的 numpy 日志

python - 如何让 web2py 开发服务器跟踪文件更改并自动重启?

html - 使用图像文件作为菜单文本

R:向图中添加文本不起作用

python - 列表理解的结果是平面列表

python - 带有身份验证的 requests.post 在 python 中为 jira rest api 提供错误 415

python - 如何将Excel文件中的像素值转换为图像?

python - 高效有效的返回包含图片的mongodb结果

python - 加速 Matplotlib?

image - 如何在 MATLAB 中以 2-D 和 3-D 绘制图像 (.jpg)?