2017-09-27 11 views
0

私は正しく動作し、値を表示するopencvのpythonプログラムを持っています。しかし、印刷された値をCSVファイルに書き込もうとすると、エラーが発生します。 次のコードです:複数の配列をcsvとして書くPython

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

データをCSV形式で書き込むことは非常に一般的な作業です。使用できるのはlibrary called csvです。

は、このサンプルコードでは、改善するための提案をするつもりはありません

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

このラインであなたの最後の2行

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

を交換し、あなたの出力変数CSVライター

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

を作りますコードの品質および/または可読性を向上させる。 –

+0

ありがとうございました....この変更は機能しました。 – Apricot

関連する問題