Python将多个数组写为csv

时间:2017-09-27 12:28:51

标签: python csv

我有一个正确运行并打印值的opencv python程序。但是,当我尝试将打印值写入csv文件时,我收到错误。 以下是代码:

for testingPath in paths.list_images(args["testing"]):
    # load the image and make predictions
    image = cv2.imread(testingPath)
    boxes = detector(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    # loop over the bounding boxes and draw them
    for b in boxes:
        (x, y, w, h) = (b.left(), b.top(), b.right(), b.bottom())
        cv2.rectangle(image, (x, y), (w, h), (0, 255, 0), 2)
        #print(basename(testingPath),"CX:"+str(x),"CY:"+str(y),"Width:"+str(w),"Height:"+str(h),brandname,"Number of brands detected: {}".format(len(boxes))) -----this prints all the required values without problem on the console

我试过这样做:

我在for循环开始之前添加了一个参数:

ap.add_argument("-i", "--index", required=True, help="Path to directory of output")
output = open(args["index"], "w")

并使用循环如下:

for testingPath in paths.list_images(args["testing"]):
    # load the image and make predictions
    image = cv2.imread(testingPath)
    #filename = testingPath[testingPath.rfind("/") + 1:]
    boxes = detector(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    #print(basename(testingPath), brandname,"Number of brands detected: {}".format(len(boxes)))
    # loop over the bounding boxes and draw them
    for b in boxes:
        (x, y, w, h) = (b.left(), b.top(), b.right(), b.bottom())
        cv2.rectangle(image, (x, y), (w, h), (0, 255, 0), 2)
        #print(basename(testingPath),"CX:"+str(x),"CY:"+str(y),"Width:"+str(w),"Height:"+str(h),brandname,"Number of brands detected: {}".format(len(boxes)))
        dat = str([x, y, w, h, brandname, len(boxes)])
        output.write("{},{}\n".format(testingPath, "".join(dat)))

以上代码按以下方式打印值:

/home/mycomp/VideoExtract/28157.jpg,[83, 349, 164, 383, 'Pirelli', 1]

我试图摆脱[]括号。所需的操作是将打印的值写入csv / text文件。

1 个答案:

答案 0 :(得分:1)

以CSV格式编写数据是一项非常常见的任务 - 您可以使用library called csv

使输出变量成为CSV编写器

output = csv.writer(open(args["index"], "w"))

替换最后两行

dat = str([x, y, w, h, brandname, len(boxes)])
output.write("{},{}\n".format(testingPath, "".join(dat)))

这一行

output.writerow((testingPath, x, y, w, h, brandname, len(boxes)))