labelme标注结果可视化(持续补充)

        图像数据常用的标注工具是labelme,标注的格式是json。labelme标注结果可视化,是将标注结果绘制到原始图像上,以方便查看标注结果。

1 json文件读取与保存

        由于labelme标注的保存格式为json,所以必须掌握json文件的读取与保存。

import json
#json文件读取
anno= json.load(open("test.json", "r", encoding="utf-8"))
#json文件保存
with open('test.json', 'w') as f:
    json.dump(ann, f)

2 opencv中文路径读写

        opencv默认的cv2.imwrite()和cv2.imread()函数是不支持中文路径的。

import os
import cv2
from pathlib import Path

#支持中文路径读取图片
def cv_imread(filePath):
    cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),-1)
    cv_img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR)
    return cv_img

#支持中文路径存储图片
cv2.imencode('.png', image)[1].tofile(save_dir+image_path)

3 矩形rectangle目标可视化

        定义线line目标可视化函数为vis_labelme_line_label。label_dir为labelme标注文件和原始图片存储目录,save_dir为可视化图片保存的文件目录。

import os
import cv2
from pathlib import Path

#支持中文路径
def cv_imread(filePath):
    cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),-1)
    cv_img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR)
    return cv_img

def vis_labelme_rect_label(label_dir, save_dir='res/'):
    label_dir = str(Path(label_dir)) + '/'
    save_dir  = str(Path(save_dir))  + '/'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    label_files = glob(label_dir+'*.json')
    for label_file in label_files:
        anno= json.load(open(label_file, "r", encoding="utf-8"))
        image_path = anno['imagePath']
        image = cv_imread(label_dir+image_path)
        shapes = anno['shapes']
        for s in shapes:
            pts = np.array(s['points']).astype(np.int)
            x1  = min(pts[:, 0])
            y1  = min(pts[:, 1])
            x2  = max(pts[:, 0])
            y2  = max(pts[:, 1])
            cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 255), 1)
        cv2.imencode('.png', image)[1].tofile(save_dir+image_path)

4 线line目标可视化

        定义线line目标可视化函数为vis_labelme_line_label。label_dir为labelme标注文件和原始图片存储目录,save_dir为可视化图片保存的文件目录。

import os
import cv2
from pathlib import Path

#支持中文路径
def cv_imread(filePath):
    cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),-1)
    cv_img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR)
    return cv_img

def vis_labelme_line_label(label_dir, save_dir='res/'):
    label_dir = str(Path(label_dir)) + '/'
    save_dir  = str(Path(save_dir))  + '/'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    label_files = glob(label_dir+'*.json')
    for label_file in label_files:
        anno= json.load(open(label_file, "r", encoding="utf-8"))
        image_path = anno['imagePath']
        image = cv_imread(label_dir+image_path)
        shapes = anno['shapes']
        for s in shapes:
            pts = s['points']
            x1, y1 = pts[0]
            x2, y2 = pts[1]
            cv2.line(image, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 255), 1)
        cv2.imencode('.png', image)[1].tofile(save_dir+image_path)

【python三维深度学习】python三维点云从基础到深度学习_Coding的叶子的博客-CSDN博客_三维点云深度学习

更多三维、二维感知算法和金融量化分析算法请关注“乐乐感知学堂”微信公众号,并将持续进行更新。

### 如何在 LabelMe 中查看已标注的标签 对于已经完成标注的任务,在 LabelMe 中重新打开这些带有标注信息的图片文件即可查看之前保标注结果[^4]。 当通过命令行启动 LabelMe 并加载含有先前保过的 JSON 文件对应的图像时,程序能够自动读取同名(除了扩展名为 .json)的标注文件并显示所有曾经绘制过的形状连同样本类别名称。如果是在图形界面下操作,则只需导航至相应目录选取该类图像文件就能实现上述功能[^1]。 另外,若要批量浏览多个已完成标注的项目,可利用 `labelme json_to_dataset` 命令转换指定路径下的 JSON 文件为数据集结构,但这一步骤并非用于直接观看而是准备训练模型所需的数据格式;不过此过程也会创建包含可视化效果图的新文件夹,从中可以间接观察到原始图片上的标注情况[^2]。 #### 使用 Python 脚本预览特定文件中的标注 也可以编写简单的Python脚本来快速查看单个或一组JSON文件内的标注详情: ```python import labelme.utils.draw as draw_utils from PIL import Image, ImageDraw import os import json def visualize_labels(image_path, json_file): with open(json_file) as f: data = json.load(f) img = Image.open(image_path) drawable_img = ImageDraw.Draw(img) for shape in data['shapes']: points = shape["points"] label = shape["label"] if shape["shape_type"] == "rectangle": drawable_img.rectangle(points, outline="red", width=2) elif shape["shape_type"] == "polygon": drawable_img.polygon(points, outline="blue", fill=None) position_for_text = tuple(map(int, points[0])) drawable_img.text(position_for_text , label, fill='white') display(img) image_dir = "./path/to/images" annotations_dir = "./path/to/jsons" for filename in os.listdir(annotations_dir): if not filename.endswith(".json"): continue image_filename = os.path.splitext(filename)[0]+".jpg" # 或者其他可能的图片格式 full_image_path = os.path.join(image_dir,image_filename ) try: visualize_labels(full_image_path,os.path.join(annotations_dir,filename)) except Exception as e: print(f"{filename} 处理失败: {str(e)}") ``` 这段代码遍历给定文件夹里的每一个 `.json` 文件,并尝试找到匹配的图像文件来一起渲染出带有所属分类标记的结果图象。注意调整变量 `image_dir` 和 `annotations_dir` 的值指向实际储位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coding的叶子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值