【问题标题】:List Index out of range.. works on google colab but not on local machine?列表索引超出范围.. 适用于 google colab 但不适用于本地计算机?
【发布时间】:2020-08-18 09:10:24
【问题描述】:

我正在尝试在我的本地机器上重新创建这个项目。它旨在在 Google Colab 上运行,我在那里重新创建了它,它运行良好。我现在想尝试在本地机器上运行它,所以我安装了所有必需的包,anaconda,Juypter Notebook 等。

当我来到处理图像的部分时:

# Loops through imagepaths to load images and labels into arrays
for path in imagepaths:
  img = cv2.imread(path) # Reads image and returns np.array
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Converts into the corret colorspace (GRAY)
  img = cv2.resize(img, (320, 120)) # Reduce image size so training can be faster
  X.append(img)

  #Processing label in image path   
  category = path.split("/")[3]   
  label = int(category.split("_")[0][1])   
  y.append(label) 

它会抛出以下错误:

IndexError: list index out of range 

代码大部分没有改变,数据集是一样的。唯一的区别是我在本地运行 vs google colab。我在网上搜索,有人说做 len(path) 来验证(在我的情况下)它会上升到 [3],它确实(它的大小为 33)。

此处的代码已更改:

我没有使用这条线,因为我没有使用 google colab:

from google.colab import files

这部分代码使用了“文件”:

# We need to get all the paths for the images to later load them
imagepaths = []

# Go through all the files and subdirectories inside a folder and save path to images inside list
for root, dirs, files in os.walk(".", topdown=False): 
  for name in files:
    path = os.path.join(root, name)
    if path.endswith("png"): # We want only the images
      imagepaths.append(path)

print(len(imagepaths)) # If > 0, then a PNG image was loaded

在我的本地计算机上,我删除了 from google.colab... 行,并正常运行其他所有内容。关键字 files 在上面的代码 sn-p 中使用,但是在运行它时我没有抛出任何错误。 **NOTE len(path) on Jupyter shows 33, len(path) on Google shows 16..?**

有人知道问题可能是什么吗?我不认为它来自删除那一行代码。如果是这样,您建议我如何解决?

【问题讨论】:

  • 听起来问题出在你的一个分裂中(你忘了告诉我们哪一个是给你带来问题的那个)。 path 在 google colab 和您的本地计算机上的值是多少?
  • 嗨@SergioR,问题出在 Jupyter 上。这正是错误指向的地方。在谷歌上做 len(path) 我得到 16,但在 Jupyter 我得到 33..?
  • 您可以为 google colab 和您的本地计算机提供 path 的输出吗?您可以为此使用print(imagepaths[0])
  • @user_3pij, print(imagepaths[0]) 结果如下:./leapgestrecog/leapGestRecog/00/01_palm/frame_00_01_0001.png 在我的本地机器上,它的'.\\00\\01_palm\\frame_00_01_0001.png'

标签: python list tensorflow indexing range


【解决方案1】:

您的本地计算机在Windows 上运行,而colablinux 上运行,并且两者的路径分隔符不同。 现在你需要更换

category = path.split("/")[3]

category = path.split("\\")[2]

你的代码应该可以工作。

【讨论】:

  • 谢谢!原来如此,我没有意识到。干杯!
猜你喜欢
  • 2013-03-16
  • 2021-01-28
  • 1970-01-01
  • 2016-01-28
  • 2022-09-28
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多