为什么在将图像转换为CSV文件时索引器错误:列表索引超出范围?

2024-09-29 07:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将图像转换为CSV文件。运行脚本时,我得到错误:IndexError: list index out of range。有人能帮我解决这个错误吗

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

回溯是:

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

Tags: ofinpyimportimgsyslinescripts
1条回答
网友
1楼 · 发布于 2024-09-29 07:30:10

看起来包含命令行参数(sys.argv)的列表中除了索引0处的脚本名称之外,没有其他内容

我很快在google上找到了一些信息here

"sys.argv is a list in Python, which contains the command-line arguments passed to the script. "

所以我想没有参数被传递给你的脚本。确保使用路径作为参数从CLI调用脚本,或将路径硬编码到脚本中,如

path = './images' #or your path 

相关问题 更多 >