首页 > 解决方案 > 在python中替换json文件中的列表

问题描述

我正在开发一个水平翻转图像注释的程序。注释文件是一个 json 文件,其中包含在图像上绘制的点的坐标作为列表。例如

{"filename":"262.JPG","size":299425,"regions":[{"shape_attributes":{"name":"polygon","all_points_x":[255,293,293,255],"all_points_y":[559,561,593,592]}...

你可以在这里看到我的代码:

annotations = list(annotations.values())  # don't need the dict keys
annotations = [a for a in annotations if a['regions']]
print(type(annotations))
i=0

for a in annotations:
    # Get the x, y coordinaets of points of the polygons that make up
    # the outline of each object instance.
    polygons = [r['shape_attributes'] for r in a['regions']]
    print(len(polygons))

    for p in polygons:
        i+=1

        all_x = p["all_points_x"]

        print("all_x"+"_"+str(i),all_x)

        all_x_flip = []
        for x in all_x:
            # image width = 1228 pixel
            x = 1228 - x - 1
            all_x_flip.append(x)
        for r in a["regions"]:
            # if len(all_x )== len(all_x_flip):

            r["shape_attributes"]["all_points_x"] = all_x_flip
            print("flipped "+"_"+str(i),r["shape_attributes"]["all_points_x"])
            break

with open('262_flip_0.json', 'w') as file:
    print("writing json file")
    json.dump(annotations, file, separators=(',', ':'))

执行时它以正确的顺序打印列表

all_x_1 [255, 293, 293, 255]
flipped _1 [972, 934, 934, 972]
all_x_2 [350, 359, 364, 363, 354, 350]
flipped _2 [877, 868, 863, 864, 873, 877]
all_x_3 [577, 593, 594, 583, 577]
flipped _3 [650, 634, 633, 644, 650]
all_x_4 [809, 801, 801, 804, 816, 817]
flipped _4 [418, 426, 426, 423, 411, 410]
all_x_5 [771, 780, 777, 771]
flipped _5 [456, 447, 450, 456]

但我的问题是将这些列表(翻转)写入 json 文件。新的 json 文件将 forloop 中生成的最后一个列表替换为原始 json 文件中的第一个列表,其他列表保持不变。

我试图以许多不同的方式更改我的 for 循环,但没有成功......

标签: pythonjson

解决方案


问题就在这里

for r in a["regions"]:
        # if len(all_x )== len(all_x_flip):

        r["shape_attributes"]["all_points_x"] = all_x_flip
        print("flipped "+"_"+str(i),r["shape_attributes"]["all_points_x"])
        break

因为您再次进行迭代并始终​​更新列表中的第一个元素(实际上有一个中断)

你需要类似的东西:

for a in annotations:
    for curr_polygon in a["regions"]:
        p = curr_polygon['shape_attributes']
        i+=1
        all_x = p["all_points_x"]
        print("all_x"+"_"+str(i),all_x)
        all_x_flip = []
        for x in all_x:
            # image width = 1228 pixel
            x = 1228 - x - 1
            all_x_flip.append(x)
        curr_polygon["shape_attributes"]["all_points_x"] = all_x_flip

推荐阅读