X-AnyLabeling项目中使用自定义模型进行半自动标注的技术指南
2025-06-07 11:56:46作者:冯爽妲Honey
前言
在计算机视觉领域,标注数据是模型训练的重要基础工作。X-AnyLabeling作为一款优秀的标注工具,不仅提供了丰富的预训练模型支持,还允许用户导入自定义模型进行半自动标注,这大大提高了标注效率。本文将详细介绍如何在X-AnyLabeling中使用自定义模型进行半自动标注。
自定义模型的基本流程
使用自定义模型进行半自动标注主要包含以下几个步骤:
- 模型训练:在自己的数据集上训练模型
- 模型转换:将训练好的模型转换为ONNX格式
- 模型集成:将转换后的模型集成到X-AnyLabeling中
- 模型测试:验证模型在标注工具中的效果
模型转换详解
X-AnyLabeling要求模型必须为ONNX格式。对于PyTorch训练的用户,可以使用以下代码示例进行转换:
import torch
import segmentation_models_pytorch as smp
def pth_to_onnx():
# 加载训练好的模型
torch_model = torch.load('model.pth')
model = smp.UnetPlusPlus(
encoder_name="timm-regnety_320",
encoder_weights="imagenet",
in_channels=3,
classes=2,
)
model.load_state_dict(torch_model)
# 设置模型为评估模式
model.eval()
# 定义输入张量
batch_size = 32
input_shape = (3, 256, 256)
x = torch.randn(batch_size, *input_shape)
# 导出ONNX模型
torch.onnx.export(
model,
x,
"model.onnx",
opset_version=11,
do_constant_folding=True,
input_names=["input"],
output_names=["output"],
dynamic_axes={
"input": {0: "batch_size"},
"output": {0: "batch_size"}
}
)
转换时需要注意以下几点:
- 确保opset_version与X-AnyLabeling兼容
- 检查输入输出名称是否正确
- 验证转换后的模型能否正常推理
自定义模型集成
在X-AnyLabeling中集成自定义模型需要创建一个继承自Model类的Python文件。以下是一个完整的示例:
import cv2
import numpy as np
from PyQt5.QtCore import QCoreApplication
from anylabeling.views.labeling.shape import Shape
from anylabeling.views.labeling.utils.opencv import qt_img_to_rgb_cv_img
from .model import Model
from .types import AutoLabelingResult
from .engines.build_onnx_engine import OnnxBaseModel
class CustomModel(Model):
"""自定义语义分割模型"""
class Meta:
required_config_names = [
"type",
"name",
"display_name",
"model_path",
"classes",
]
widgets = ["button_run"]
output_modes = {
"polygon": QCoreApplication.translate("Model", "多边形"),
}
default_output_mode = "polygon"
def __init__(self, model_config, on_message):
super().__init__(model_config, on_message)
model_abs_path = self.get_model_abs_path(self.config, "model_path")
self.net = OnnxBaseModel(model_abs_path, "cuda")
self.classes = self.config["classes"]
self.input_shape = self.net.get_input_shape()[-2:]
def preprocess(self, input_image):
"""图像预处理"""
input_h, input_w = self.input_shape
image = cv2.resize(input_image, (input_w, input_h))
image = np.transpose(image, (2, 0, 1))
image = image.astype(np.float32) / 255.0
image = (image - 0.5) / 0.5
return np.expand_dims(image, axis=0)
def postprocess(self, image, outputs):
"""结果后处理"""
outputs = np.argmax(outputs, axis=1)
results = []
for i, class_name in enumerate(self.classes):
if class_name == '_background_':
continue
mask = outputs[0] == i
mask_resized = cv2.resize(
mask.astype(np.uint8),
(image.shape[1], image.shape[0])
contours, _ = cv2.findContours(
mask_resized,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
results.append((
class_name,
[np.squeeze(contour).tolist() for contour in contours]))
return results
def predict_shapes(self, image, image_path=None):
"""预测形状"""
if image is None:
return []
try:
image = qt_img_to_rgb_cv_img(image, image_path)
blob = self.preprocess(image)
outputs = self.net.get_ort_inference(blob)
results = self.postprocess(image, outputs)
shapes = []
for label, contours in results:
for points in contours:
points.append(points[0]) # 闭合多边形
shape = Shape(flags={})
for point in points:
shape.add_point(QtCore.QPointF(point[0], point[1]))
shape.shape_type = "polygon"
shape.closed = True
shape.label = label
shapes.append(shape)
return AutoLabelingResult(shapes, replace=True)
except Exception as e:
print(f"推理错误: {e}")
return []
常见问题与解决方案
-
模型推理错误:
- 检查预处理和后处理是否与训练时一致
- 验证ONNX模型是否能单独运行
- 确保输入尺寸与模型要求匹配
-
标注结果不准确:
- 检查类别标签是否正确配置
- 验证模型在原始测试集上的表现
- 调整后处理中的阈值参数
-
性能问题:
- 尝试减小输入尺寸
- 使用更轻量级的模型架构
- 确保使用GPU加速
最佳实践建议
-
模型优化:
- 在转换ONNX前对模型进行量化
- 使用TensorRT进一步优化推理速度
- 考虑使用动态输入尺寸提高灵活性
-
标注流程:
- 先使用自动标注生成初步结果
- 然后人工检查和修正
- 建立质量检查机制确保标注一致性
-
模型迭代:
- 定期用新标注数据重新训练模型
- 建立模型性能监控机制
- 考虑使用主动学习策略优化标注效率
结语
通过X-AnyLabeling的自定义模型功能,用户可以显著提高标注效率,特别是在处理专业领域数据时。本文详细介绍了从模型转换到集成的完整流程,并提供了实用建议。希望这些内容能帮助用户更好地利用X-AnyLabeling的强大功能,构建高效的标注工作流程。
登录后查看全文
热门项目推荐
相关项目推荐
kernelopenEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。C087
baihu-dataset异构数据集“白虎”正式开源——首批开放10w+条真实机器人动作数据,构建具身智能标准化训练基座。00
mindquantumMindQuantum is a general software library supporting the development of applications for quantum computation.Python057
PaddleOCR-VLPaddleOCR-VL 是一款顶尖且资源高效的文档解析专用模型。其核心组件为 PaddleOCR-VL-0.9B,这是一款精简却功能强大的视觉语言模型(VLM)。该模型融合了 NaViT 风格的动态分辨率视觉编码器与 ERNIE-4.5-0.3B 语言模型,可实现精准的元素识别。Python00
GLM-4.7GLM-4.7上线并开源。新版本面向Coding场景强化了编码能力、长程任务规划与工具协同,并在多项主流公开基准测试中取得开源模型中的领先表现。 目前,GLM-4.7已通过BigModel.cn提供API,并在z.ai全栈开发模式中上线Skills模块,支持多模态任务的统一规划与协作。Jinja00
agent-studioopenJiuwen agent-studio提供零码、低码可视化开发和工作流编排,模型、知识库、插件等各资源管理能力TSX0137
Spark-Formalizer-X1-7BSpark-Formalizer 是由科大讯飞团队开发的专用大型语言模型,专注于数学自动形式化任务。该模型擅长将自然语言数学问题转化为精确的 Lean4 形式化语句,在形式化语句生成方面达到了业界领先水平。Python00
项目优选
收起
deepin linux kernel
C
27
11
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
473
3.5 K
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
213
87
暂无简介
Dart
719
173
Ascend Extension for PyTorch
Python
278
315
React Native鸿蒙化仓库
JavaScript
286
333
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
848
433
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.27 K
696
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
10
1
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
65
19