[英]Why do I get IndexError: List index out of range when turning images into CSV file?
I am trying to turn images into a CSV file. 我正在尝试将图像转换为CSV文件。 When running the script, I obtain the error:
IndexError: list index out of range
. 运行脚本时,出现错误:
IndexError: list index out of range
。 Can someone help me solve this error? 有人可以帮我解决这个错误吗?
import sys
import os
import csv
import glob
SPLIT_CHAR = '\\'
MAX_IMG_PER_CLASS = 5000000
# Path to input directory; subdir conatain test image files and name of subdir matches class name
path = sys.argv[1]
directories = [x[0] for x in os.walk(path)]
data = []
for directory in directories:
tag = directory.rsplit(SPLIT_CHAR, 1)[-1]
images = glob.glob(directory + "/*.jpg")
if len(images) > 0:
img_Cnt = 0
for image in images:
if img_Cnt <= MAX_IMG_PER_CLASS:
taggedImage = [image, tag]
data.append(taggedImage)
print(taggedImage)
img_Cnt += 1
else:
print("Got {0} images, breaking".format(img_Cnt))
break
with open("images.csv", "w") as file:
writer = csv.writer(file)
writer.writerows(data)
input("All done. Press any key...")
runfile('C:/Users/otr/Documents/Python Scripts/csvfile.py', wdir='C:/Users/otr/Documents/Python Scripts')
The traceback is: 追溯为:
Traceback (most recent call last):
File "<ipython-input-7-bec6ed956596>", line 1, in <module>
runfile('C:/Users/otr/Documents/Python Scripts/csvfile.py', wdir='C:/Users/otr/Documents/Python Scripts')
File "C:\Users\otr\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\otr\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/otr/Documents/Python Scripts/csvfile.py", line 26, in <module>
path = sys.argv[1]
IndexError: list index out of range
Looks like your list containing command line arguments (sys.argv) doesn't contain anything else but the name of the script at index 0. 看起来您的包含命令行参数(sys.argv)的列表除了索引0处的脚本名称外不包含其他任何内容。
I quickly googled and found some information here . 我迅速搜索了一下,并在这里找到了一些信息。
"sys.argv is a list in Python, which contains the command-line arguments passed to the script. "
“ sys.argv是Python中的列表,其中包含传递给脚本的命令行参数。”
So I suppose no arguments are passed to your script. 所以我想没有参数传递给您的脚本。 Make sure to call the script from CLI with the path as a parameter, or hard-code the path into your script like
确保从CLI调用脚本,并将路径作为参数,或将路径硬编码到脚本中,例如
path = './images' #or your path
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.