
3步搞定LabelImg二次开发从矩形框到多边形标注的华丽升级【免费下载链接】labelImgLabelImg is now part of the Label Studio community. The popular image annotation tool created by Tzutalin is no longer actively being developed, but you can check out Label Studio, the open source data labeling tool for images, text, hypertext, audio, video and time-series data.项目地址: https://gitcode.com/gh_mirrors/lab/labelImg想要扩展LabelImg的图像标注能力厌倦了只能标注矩形框的局限本文将带你轻松掌握LabelImg二次开发的核心技巧通过3个关键步骤实现多边形标注功能的完整集成。我们将从项目架构解析入手逐步实现工具栏扩展、画布交互优化和格式兼容性处理让你在30分钟内完成从矩形框到多边形标注的华丽升级。核心概念解析LabelImg的模块化架构LabelImg作为经典的图像标注工具其核心架构采用模块化设计主要包含以下几个关键组件主程序入口labelImg.py是整个应用的入口点负责初始化主窗口、连接各个模块的信号槽。这是我们扩展新功能的起点。画布渲染引擎libs/canvas.py处理所有的鼠标事件和图形绘制逻辑包括矩形框的创建、移动和编辑。这是我们要重点改造的核心模块。形状数据模型libs/shape.py定义了标注形状的数据结构目前主要支持矩形框。我们需要在这里扩展多边形形状的支持。工具栏管理libs/toolBar.py管理界面上的各种工具按钮我们需要在这里添加多边形工具按钮。数据格式适配器libs/pascal_voc_io.py、libs/yolo_io.py等文件负责将标注数据转换为不同的格式输出需要适配多边形数据格式。LabelImg界面展示绿色矩形框标注人物目标右侧标签面板管理分类实战5分钟集成多边形工具按钮步骤1扩展工具栏类首先打开libs/toolBar.py文件在ToolBar类中添加多边形工具按钮。我们需要创建一个新的QAction并将其连接到相应的处理函数# 在libs/toolBar.py的ToolBar类中添加 def add_polygon_tool(self): 添加多边形标注工具按钮 polygon_action QAction( QIcon(:/icons/polygon.png), # 使用项目资源中的图标 多边形标注, self ) polygon_action.setShortcut(P) # 设置快捷键P polygon_action.setCheckable(True) # 设置为可选中状态 polygon_action.triggered.connect(self.parent().on_polygon_tool_clicked) self.addAction(polygon_action) return polygon_action步骤2更新主窗口状态管理接下来修改labelImg.py中的MainWindow类添加多边形模式的状态管理# 在labelImg.py的MainWindow类中添加 def on_polygon_tool_clicked(self): 多边形工具点击事件处理 if self.canvas: self.canvas.set_drawing_mode(polygon) self.actions.create.setText(多边形标注) self.statusBar().showMessage(多边形模式点击添加顶点右键完成绘制) # 取消其他工具的选中状态 for action in self.tool_actions: if action ! self.polygon_action: action.setChecked(False)步骤3创建多边形工具图标在项目的资源文件中添加多边形图标或者使用简单的几何图形作为占位符# 创建简单的多边形图标16x16像素 def create_polygon_icon(): pixmap QPixmap(16, 16) pixmap.fill(Qt.transparent) painter QPainter(pixmap) painter.setPen(QPen(Qt.green, 2)) painter.setBrush(QBrush(Qt.green, Qt.SolidPattern)) points [QPoint(4, 4), QPoint(12, 4), QPoint(12, 12), QPoint(8, 16), QPoint(4, 12)] painter.drawPolygon(points) painter.end() return QIcon(pixmap)进阶技巧画布交互与多边形绘制核心改造Canvas类的多边形支持打开libs/canvas.py这是实现多边形绘制的关键。我们需要扩展Canvas类以支持多边形绘制模式# 在libs/canvas.py的Canvas类中添加 def set_drawing_mode(self, mode): 设置绘图模式rectangle或polygon self.drawing_mode mode if mode polygon: self.polygon_points [] # 存储多边形顶点 self.setCursor(CURSOR_DRAW) self.drawingPolygon.emit(True) # 发出信号 else: self.setCursor(CURSOR_DEFAULT) self.drawingPolygon.emit(False) def mousePressEvent(self, ev): 处理鼠标按下事件 pos self.transform_pos(ev.pos()) # 多边形模式处理 if self.drawing_mode polygon and ev.button() Qt.LeftButton: self.polygon_points.append(pos) if len(self.polygon_points) 1: self.update() # 重绘预览 return # 原有矩形模式处理保持兼容 # ... 原有代码 ...多边形形状数据扩展现在修改libs/shape.py扩展Shape类以支持多边形形状# 在libs/shape.py的Shape类中添加 def __init__(self, labelNone, line_colorNone, difficultFalse, paint_labelFalse, shape_typerectangle): self.label label self.points [] self.shape_type shape_type # 新增形状类型标识 self.fill False self.selected False self.difficult difficult self.paint_label paint_label # ... 其他初始化代码 ... def is_polygon(self): 判断是否为多边形形状 return self.shape_type polygon def add_point(self, point): 添加顶点到多边形 if self.is_polygon(): self.points.append(point) return True return False def close_polygon(self): 闭合多边形 if self.is_polygon() and len(self.points) 3: # 多边形自动闭合首尾相连 return True return False多边形标注效果适合标注不规则形状的目标如花朵、建筑物等避坑指南数据格式兼容性与常见问题格式适配Pascal VOC多边形支持多边形数据需要适配现有的标注格式。修改libs/pascal_voc_io.py# 在PascalVocWriter类中添加 def addPolygon(self, label, points): 添加多边形标注到XML obj ET.SubElement(self.annotation, object) ET.SubElement(obj, name).text label ET.SubElement(obj, pose).text Unspecified ET.SubElement(obj, truncated).text 0 ET.SubElement(obj, difficult).text 0 # 多边形数据存储 polygon ET.SubElement(obj, polygon) for i, point in enumerate(points): point_elem ET.SubElement(polygon, fpoint{i1}) ET.SubElement(point_elem, x).text str(int(point.x())) ET.SubElement(point_elem, y).text str(int(point.y()))常见问题与解决方案多边形顶点过多导致性能问题解决方案限制最大顶点数或使用贝塞尔曲线简化多边形自相交检测实现交叉检测算法避免无效多边形顶点编辑的精度控制添加网格吸附功能提高标注精度与现有矩形标注的兼容性保持向后兼容确保原有功能不受影响# 多边形顶点数量限制 MAX_POLYGON_POINTS 50 def validate_polygon(self, points): 验证多边形有效性 if len(points) 3: return False, 多边形至少需要3个顶点 if len(points) MAX_POLYGON_POINTS: return False, f多边形顶点数不能超过{MAX_POLYGON_POINTS} # 自相交检测 if self.has_self_intersection(points): return False, 多边形存在自相交 return True, 扩展功能智能编辑与效率提升智能吸附功能实现顶点自动吸附到网格或已有标注边缘def snap_to_grid(self, point, grid_size10): 将点吸附到最近的网格线 x round(point.x() / grid_size) * grid_size y round(point.y() / grid_size) * grid_size return QPointF(x, y) def snap_to_existing_edges(self, point, threshold5): 吸附到已有标注的边缘 for shape in self.shapes: if shape.is_polygon(): for i in range(len(shape.points)): p1 shape.points[i] p2 shape.points[(i 1) % len(shape.points)] # 计算点到线段的距离 distance self.point_to_line_distance(point, p1, p2) if distance threshold: return self.project_point_to_line(point, p1, p2) return point撤销/重做功能实现添加操作历史记录支持撤销和重做class Canvas(QWidget): def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) self.history [] # 操作历史栈 self.history_index -1 # 当前历史位置 self.max_history 50 # 最大历史记录数 def add_to_history(self, action_type, data): 添加操作到历史记录 # 截断当前位置后的历史 self.history self.history[:self.history_index 1] self.history.append({ type: action_type, data: data, timestamp: time.time() }) self.history_index 1 # 限制历史记录数量 if len(self.history) self.max_history: self.history.pop(0) self.history_index - 1 def undo(self): 撤销上一步操作 if self.history_index 0: action self.history[self.history_index] if action[type] add_polygon: # 移除添加的多边形 self.shapes.remove(action[data][shape]) self.history_index - 1 self.update()开发环境集成左侧终端运行Git和Python代码右侧显示LabelImg界面下一步行动建议从简单开始先实现基本的多边形绘制功能再逐步添加高级特性测试驱动为每个新功能编写单元测试确保代码质量社区贡献将你的扩展功能提交到LabelImg社区帮助更多开发者持续优化收集用户反馈不断改进多边形标注的用户体验探索更多形状尝试添加圆形、椭圆形等其他形状的支持通过本文的指导你已经掌握了LabelImg二次开发的核心技能。多边形标注只是开始你可以基于这个框架继续扩展更多功能如AI辅助标注、批量处理工具等。记住优秀的工具开发始终以用户体验为中心不断迭代优化才能创造真正有价值的产品。快速开始路径如果你只想快速体验多边形标注可以直接修改libs/canvas.py和libs/shape.py添加基本的绘制逻辑。深入探索路径如果你希望全面掌握LabelImg的架构建议从labelImg.py的主程序入口开始逐步理解各个模块的协作关系。无论选择哪条路径动手实践都是最好的学习方式。现在就开始你的LabelImg二次开发之旅吧【免费下载链接】labelImgLabelImg is now part of the Label Studio community. The popular image annotation tool created by Tzutalin is no longer actively being developed, but you can check out Label Studio, the open source data labeling tool for images, text, hypertext, audio, video and time-series data.项目地址: https://gitcode.com/gh_mirrors/lab/labelImg创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考