0

I have an opencv python program that runs correctly and prints the values. However when I try to write the printed values to a csv file, I am getting errors. The following is the code:

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

I tried doing this:

I added an argument before the for loop starts:

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

and used the loop as follows:

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

The above code prints the values as follows:

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

I am trying to get rid of the [] brackets. The desired action is to write the values that gets printed into a csv / text file.

1 Answer 1

1

Writing data in CSV format is a very common task - there is a library called csv you could use.

Make your output variable a CSV writer

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

Replace your last two lines

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

with this line

output.writerow((testingPath, x, y, w, h, brandname, len(boxes)))
Sign up to request clarification or add additional context in comments.

1 Comment

this sample code does not intend to make suggestions to improve code quality and/or readability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.