Labelme 是一款开源图像标注工具,常用于机器学习、深度学习等领域中的数据预处理。在使用 Labelme 标注完图片后,会得到一个 JSON 数据文件,里面包含了图片的路径、尺寸、标注信息等。本文将介绍如何使用 Python 解析 Labelme 格式的 JSON 数据,并自动提取标题。
一般而言,JSON 数据文件中的 “shapes” 键对应的值是一个列表,其中每个元素代表一条标注信息,包括类别、坐标点等信息。我们可以遍历这个列表,找到最上方和最左侧的两个点,以此生成一个矩形框,然后从该矩形框中心点开始向上下左右四个方向扫描,直到扫描到不为空的字符串,即可作为标题。
接下来是实现代码:
import json
def extract_title_from_labelme(labelme_file_path):
with open(labelme_file_path, "r") as f:
data = json.load(f)
shapes = data["shapes"]
x_min, y_min = float("inf"), float("inf")
x_max, y_max = float("-inf"), float("-inf")
for shape in shapes:
points = shape["points"]
x1, y1 = points[0]
x2, y2 &#