### 将数据集转换为适用于 mmpose 的 COCO 格式
为了使数据集能够被 mmpose 使用,将其转换为 COCO 格式的必要性在于该格式具有良好的结构化信息表示能力以及广泛的支持度。具体来说,在基于 Labelme 创建的手部关键点数据集中,由于 Open-MMLab 更好地支持 COCO 格式,因此推荐将此类数据集转化为 COCO 格式[^1]。
#### 数据预处理阶段
当面对单个目标的关键点标注时,可以采用 labelme 工具完成初步的点位标记工作。然而需要注意的是,labelme 默认并不直接提供符合 COCO 要求的 `x, y, v` 坐标格式输出;这里 `v` 表示可见性标志。为此,需编写额外的 Python 脚本来实现从 labelme JSON 文件到标准 COCO JSON 文件之间的转换操作[^2]。
```python
import json
from pathlib import Path
def convert_labelme_to_coco(labelme_jsons_dir: str, output_path: str):
coco_data = {
"images": [],
"annotations": [],
"categories": [{"id": 1, "name": "hand", "supercategory": "", "keypoints": ["palm", ...], "skeleton": []}]
}
image_id = 0
annotation_id = 0
for file_name in Path(labelme_jsons_dir).glob('*.json'):
with open(file_name) as f:
data = json.load(f)
# Add Image Info
img_info = {"file_name": data['imagePath'], "height": data['imageHeight'], "width": data['imageWidth'], "id": image_id}
coco_data["images"].append(img_info)
keypoints = []
num_keypoints = 0
for shape in data['shapes']:
if shape['shape_type'] != 'point':
continue
x, y = shape['points'][0]
visible = 2 # Assuming all points are labeled and visible
keypoints.extend([float(x), float(y), int(visible)])
num_keypoints += 1
ann_info = {
"segmentation": [],
"num_keypoints": num_keypoints,
"area": 0,
"iscrowd": 0,
"keypoints": keypoints,
"image_id": image_id,
"bbox": [min_x, min_y, width, height],
"category_id": 1,
"id": annotation_id
}
coco_data["annotations"].append(ann_info)
image_id += 1
annotation_id += 1
with open(output_path, 'w') as outfile:
json.dump(coco_data, outfile)
convert_labelme_to_coco('/path/to/your/labelme/json/files', '/output/path/coco_format.json')
```
上述脚本展示了如何读取由 labelme 导出的一系列 JSON 文件,并按照 COCO 关键点检测任务的标准构建相应的图像和注解条目。其中特别注意到了对每个关键点位置及其可见性的编码方式。
对于多目标场景下的关键点标注,则建议使用专门设计用于此目的的工具如 coco-annotate 来简化流程并提高效率。