有没有办法在python的循环中存储列表值

时间:2019-08-19 19:57:33

标签: json python-3.x opencv

我正在尝试使用yolov3OpenCV和python来检测对象 我想以JSON格式存储检测到的对象的坐标,但是我只是获取最后一个坐标,如何将所有值存储在列表中

for i in range(len(boxes)):
    if i in indexes:
        x, y, w, h = boxes[i]

        label = str(classes[class_ids[i]])

        labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
        y = max(y, labelSize[1])
        cv2.rectangle(img, (x, y - round(1.5 * labelSize[1])), (x + round(1.5 * labelSize[0]), y + baseLine),
                     (255, 255, 255), cv2.FILLED)
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 255, 255), 1)
        # print ("x1=",(left,right),"y:",top,bottom,label)
        cv2.putText(img, label, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 0), 1)

        book = {
            "frame_url": "frame",
            "frame_width": width,
            "frame_height": height,
            "objeler": [
                {

                    "tur": label,
                    "x0": x,
                    "y0": y,
                    "x1": x+w,
                    "y1": y+h
                }]

        }

        s = json.dumps(book, indent=2)
        with open("f.json", "w")as f:
            f.write(s)


        cv2.imshow("Image", img)


cv2.waitKey(0)
cv2.destroyAllWindows()

这是我得到的输出

{
  "frame_url": "frame",
  "frame_width": 768,
  "frame_height": 360,
  "objeler": [
    {
      "tur": "arac",
      "x0": 273,
      "y0": 256,
      "x1": 299,
      "y1": 269
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

您应该在for循环之外创建一个列表。然后,在循环中,将其追加到该列表。循环结束后,将列表转换为json。

一般示例:

import json
# create an empty list
books = []

for x in range(10):
        # add to the list
        books.append({"key":x})

print(json.dumps(books))

编辑:评论中的问题。
您可以使用glob来获取所有文件名,如下所示:

import glob
# location of images
folder = ""
# print all filenames of .jpg in folder
for filename in glob.glob(folder + "*.jpg"):
        image = cv.imread(folder+filename)
        # Process image...