我是python的新手,非常感谢您的帮助。 我有一个包含键值对的JSON文件,基本上我必须提取'regions'中存在的'all_points_x'和'all_points_y'。我创建了一个循环,但我没有给出正确的键来提取'regions',请需要你的帮助解决问题。 json_data文件内容
_via_img_metadata {'barley_Admixture_image28.jpg2218': {'filename': 'barley_Admixture_image28.jpg', 'size': 2218, 'regions': [{'shape_attributes': {'name': 'polygon', 'all_points_x': [35, 28, 27, 31, 40, 51, 62, 72, 74, 71, 65, 57, 41], 'all_points_y': [74, 55, 32, 16, 4, 6, 12, 35, 56, 74, 83, 86, 81]}, 'region_attributes': {}},
for i in range(len(json_data[keys]['regions'])):
coords = []
for j in range(len(json_data[keys]['regions'][i]['shape_attributes']['all_points_x'])):
coords.append((json_data[keys]['regions'][i]['shape_attributes']['all_points_x'][j], json_data[keys]['regions'][i]['shape_attributes']['all_points_y'][j]))
coords = np.asarray([coords], dtype=np.int32)
if i == 0:
mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
cv2.polylines(mask, coords, isClosed=True, color=255, thickness=4)
else:
mask1 = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
cv2.polylines(mask1, coords, isClosed=True, color=255, thickness=4)
mask = cv2.bitwise_or(mask,mask1)
答案 0 :(得分:1)
您可以像这样访问嵌套词典中的项目
for key,value in dictionary.items():
for k,v in value.items()
#do sth
据我了解,您的json_data下面的代码应该可以工作。
coords = []
for key,value in json_data.items():
regions = value['regions']
for i in range(len(regions)):
for x,y in zip(regions[i]['shape_attributes']['all_points_x'],regions[i]['shape_attributes']['all_points_y']):
coords.append((x,y))
答案 1 :(得分:1)
尝试以下操作以提取all_points_x和all_points_y元组,我假设您的json为input_json:
input_keys = input_json.keys()
for key in input_keys:
for obj in input_json[key]['regions']:
for i in range(len(obj['shape_attributes']['all_points_x'])):
coords.append((obj['shape_attributes']['all_points_x'][i], obj['shape_attributes']['all_points_y'][i]))
print(coords)