当前位置: 首页 > news >正文

如何将分割的mask转为为分割标签

将分割的mask转换为分割标签通常涉及将每个像素的类别标识(在mask中以不同的灰度值或颜色表示)转换为整数标签。这些标签通常用于机器学习或深度学习模型的训练、验证和测试阶段。

使用方式,控制台或者命令行使用以下命令:

python polygon_mask_conversion.py --img_path xxx_folder --mask_path xxx_folder --mode mask2poly    

转换代码,来自X_anyLabeling的tool文件夹下的转换文件。

import argparse
import json
import os
import time
import cv2from PIL import Image
from tqdm import tqdm
from datetime import dateimport numpy as np
import matplotlib as pltimport syssys.path.append("./")
from anylabeling.app_info import __version__# ======================================================================= Usage ========================================================================#
#                                                                                                                                                      #
# -------------------------------------------------------------------- mask2poly  ----------------------------------------------------------------------#
# python tools/polygon_mask_conversion.py --img_path xxx_folder --mask_path xxx_folder --mode mask2poly                                                #
#                                                                                                                                                      #
# -------------------------------------------------------------------- poly2mask  ----------------------------------------------------------------------#
# [option1] python tools/polygon_mask_conversion.py --img_path xxx_folder --mask_path xxx_folder --mode poly2mask                                      #
# [option2] python tools/polygon_mask_conversion.py --img_path xxx_folder --mask_path xxx_folder --json_path xxx_folder --mode poly2mask               #
#                                                                                                                                                      #
# ======================================================================= Usage ========================================================================#VERSION = __version__
IMG_FORMATS = [".bmp",".dng",".jpeg",".jpg",".mpo",".png",".tif",".tiff",".webp",".pfm",
]class PolygonMaskConversion:def __init__(self, epsilon_factor=0.001):self.epsilon_factor = epsilon_factordef reset(self):self.custom_data = dict(version=VERSION,flags={},shapes=[],imagePath="",imageData=None,imageHeight=-1,imageWidth=-1,)def get_image_size(self, image_file):with Image.open(image_file) as img:width, height = img.sizereturn width, heightdef mask_to_polygon(self, img_file, mask_file, json_file):self.reset()binary_mask = cv2.imread(mask_file, cv2.IMREAD_GRAYSCALE)contours, _ = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)for contour in contours:epsilon = self.epsilon_factor * cv2.arcLength(contour, True)approx = cv2.approxPolyDP(contour, epsilon, True)if len(approx) < 5:continueshape = {"label": "object","text": "","points": [],"group_id": None,"shape_type": "polygon","flags": {},}for point in approx:x, y = point[0].tolist()shape["points"].append([x, y])self.custom_data["shapes"].append(shape)image_width, image_height = self.get_image_size(img_file)self.custom_data["imagePath"] = os.path.basename(img_file)self.custom_data["imageHeight"] = image_heightself.custom_data["imageWidth"] = image_widthwith open(json_file, "w", encoding="utf-8") as f:json.dump(self.custom_data, f, indent=2, ensure_ascii=False)def polygon_to_mask(self, img_file, mask_file, json_file):with open(json_file, "r") as f:data = json.load(f)polygons = []for shape in data["shapes"]:points = shape["points"]polygon = []for point in points:x, y = pointpolygon.append((x, y))polygons.append(polygon)image_width, image_height = self.get_image_size(img_file)image_shape = (image_height, image_width)binary_mask = np.zeros(image_shape, dtype=np.uint8)for polygon_points in polygons:np_polygon = np.array(polygon_points, np.int32)np_polygon = np_polygon.reshape((-1, 1, 2))cv2.fillPoly(binary_mask, [np_polygon], color=255)cv2.imwrite(mask_file, binary_mask)def main():parser = argparse.ArgumentParser(description="Polygon Mask Conversion")parser.add_argument("--img_path", help="Path to image directory")parser.add_argument("--mask_path", help="Path to mask directory")parser.add_argument("--json_path", default="", help="Path to json directory")parser.add_argument("--epsilon_factor",default=0.001,type=float,help="Control the level of simplification when converting a polygon contour to a simplified version",)parser.add_argument("--mode",choices=["mask2poly", "poly2mask"],required=True,help="Choose the conversion mode what you need",)args = parser.parse_args()print(f"Starting conversion to {args.mode}...")start_time = time.time()converter = PolygonMaskConversion(args.epsilon_factor)if args.mode == "mask2poly":file_list = os.listdir(args.mask_path)for file_name in tqdm(file_list, desc="Converting files", unit="file", colour="blue"):img_file = os.path.join(args.img_path, file_name)mask_file = os.path.join(args.mask_path, file_name)json_file = os.path.join(args.img_path, os.path.splitext(file_name)[0] + ".json")converter.mask_to_polygon(img_file, mask_file, json_file)elif args.mode == "poly2mask":# Only binary mask transformations are supported.os.makedirs(args.mask_path, exist_ok=True)file_list = os.listdir(args.img_path)for file_name in tqdm(file_list, desc="Converting files", unit="file", colour="blue"):base_name, suffix = os.path.splitext(file_name)if suffix.lower() not in IMG_FORMATS:continueimg_file = os.path.join(args.img_path, file_name)if not args.json_path:json_file = os.path.join(args.img_path, base_name + ".json")else:json_file = os.path.join(args.json_path, base_name + ".json")mask_file = os.path.join(args.mask_path, base_name + ".png")converter.polygon_to_mask(img_file, mask_file, json_file)end_time = time.time()print(f"Conversion completed successfully!")print(f"Conversion time: {end_time - start_time:.2f} seconds")if __name__ == "__main__":main()

相关文章:

如何将分割的mask转为为分割标签

将分割的mask转换为分割标签通常涉及将每个像素的类别标识&#xff08;在mask中以不同的灰度值或颜色表示&#xff09;转换为整数标签。这些标签通常用于机器学习或深度学习模型的训练、验证和测试阶段。 使用方式&#xff0c;控制台或者命令行使用以下命令&#xff1a; pyth…...

【动手学电机驱动】STM32-MBD(5)Simulink 模型开发之 PWM 输出

STM32-MBD&#xff08;1&#xff09;安装 Simulink STM32 硬件支持包 STM32-MBD&#xff08;2&#xff09;Simulink 模型部署入门 STM32-MBD&#xff08;3&#xff09;Simulink 状态机模型的部署 STM32-MBD&#xff08;4&#xff09;Simulink 状态机实现按键控制 STM32-MBD&…...

MySQL进阶突击系列(05)突击MVCC核心原理 | 左右护法ReadView视图和undoLog版本链强强联合

2024小结&#xff1a;在写作分享上&#xff0c;这里特别感谢CSDN社区提供平台&#xff0c;支持大家持续学习分享交流&#xff0c;共同进步。社区诚意满满的干货&#xff0c;让大家收获满满。 对我而言&#xff0c;珍惜每一篇投稿分享&#xff0c;每一篇内容字数大概6000字左右&…...

vue2日历组件

这个代码可以直接运行&#xff0c;未防止有组件库没安装&#xff0c;将组件库的代码&#xff0c;转成文字了 vue页面 <template><div class"about"><div style"height: 450px; width: 400px"><div style"height: 100%; overflo…...

【PyQt】多行纯文本框

[toc]qt多行纯文本框 QPlainTextEdit QPlainTextEdit 是可以多行的纯文本编辑框 文本浏览框 内置了一个** QTextDocument **类型的对象 &#xff0c;存放文档。 1.信号&#xff1a;文本被修改 当文本框中的内容被键盘编辑&#xff0c;被点击就会发出 textChanged 信号&…...

workerman5.0篇〡异步非阻塞协程HTTP客户端

概述 workerman/http-client 是一个异步http客户端组件。所有请求响应异步非阻塞&#xff0c;内置连接池&#xff0c;消息请求和响应符合PSR7规范。 Workerman 5.0 版本中的异步HTTP协程客户端组件是一个基于PHP协程的高性能HTTP客户端&#xff0c;它能够充分利用PHP的异步特…...

JavaScript 延迟加载的方法( 7种 )

JavaScript脚本的延迟加载&#xff08;也称为懒加载&#xff09;是指在网页的主要内容已经加载并显示给用户之后&#xff0c;再加载或执行额外的JavaScript代码。这样做可以加快页面的初始加载速度&#xff0c;改善用户体验&#xff0c;并减少服务器的压力。 以下是几种常见的延…...

python+pymysql

python操作mysql 一、python操作数据库 1、下载pymysql 库&#xff0c; 方法一&#xff1a;pip3 install pymysql 或pip install pymysql 方法二&#xff1a;在pycharm中setting下载pymysql 2、打开虚拟机上的数据库 3、pymysql连接 dbpymysql.Connection(host&qu…...

基于 Selenium 实现上海大学校园网自动登录

基于 Selenium 实现上海大学校园网自动登录 一、技术方案 核心工具&#xff1a; Selenium&#xff1a;一个用于自动化测试的工具&#xff0c;能够模拟用户在浏览器上的操作。Edge WebDriver&#xff1a;用于控制 Edge 浏览器的驱动程序。 功能设计&#xff1a; 检测网络状…...

啥!GitHub Copilot也免费使用了

文章目录 前言免费版直接修复代码多文件上下文Agent模式总结 前言 最近&#xff0c;GitHub 给开发者们带来了一个好消息&#xff1a;他们的 AI 编程助手 GitHub Copilot 现在可以免费使用了&#xff01;以前&#xff0c;每个月要花 10 美元才能享受的服务&#xff0c;现在对所…...

Spring配置文件中:密码明文改为密文处理方式(通用方法)

目录 一、背景 二、思路 A) 普通方式 B) 适合bootstrap.properties方式 三、示例 A) 普通方式&#xff08;连接Redis集群&#xff09; A) 普通方式&#xff08;连接RocketMQ&#xff09; B) 适合bootstrap.properties方式 四、总结 一、背景 SpringBoot和Sprin…...

Linux下ext2文件系统

文章目录 一 :penguin:基本概述二 :star: ext2文件系统:star:​ 1. :star:​Boot Block&#xff08;引导块&#xff09;位置与作用 三 Block Group(块组):star:​1.:star:​ Super Block(超级块):star:​2.:star:​ Group Descriptor&#xff08;块组描述符&#xff09;:star:​…...

BUUCTF:web刷题记录(1)

目录 [极客大挑战 2019]EasySQL1 [极客大挑战 2019]Havefun1 [极客大挑战 2019]EasySQL1 根据题目以及页面内容&#xff0c;这是一个sql注入的题目。 直接就套用万能密码试试。 admin or 1 # 轻松拿到flag 换种方式也可以轻松拿到flag 我们再看一下网页源码 这段 HTML 代码…...

【微服务】面试题 6、分布式事务

分布式事务面试题讲解 一、问题背景与解决方案概述 因微服务项目涉及远程调用可能引发分布式事务问题&#xff0c;需解决。主流解决方案有阿里 Seata 框架&#xff08;含 XA、AT、TCC 模式&#xff09;和 MQ。 二、Seata 框架关键角色 事务协调者&#xff08;TC&#xff09;&…...

【2024年华为OD机试】(C卷,100分)- 分割均衡字符串 (Java JS PythonC/C++)

一、问题描述 题目描述 均衡串定义&#xff1a;字符串中只包含两种字符&#xff0c;且这两种字符的个数相同。 给定一个均衡字符串&#xff0c;请给出可分割成新的均衡子串的最大个数。 约定&#xff1a;字符串中只包含大写的 X 和 Y 两种字符。 输入描述 输入一个均衡串…...

Spring Data Elasticsearch简介

一、Spring Data Elasticsearch简介 1 SpringData ElasticSearch简介 Elasticsearch是一个实时的分布式搜索和分析引擎。它底层封装了Lucene框架,可以提供分布式多用户的全文搜索服务。 Spring Data ElasticSearch是SpringData技术对ElasticSearch原生API封装之后的产物,它通…...

GESP202312 四级【小杨的字典】题解(AC)

》》》点我查看「视频」详解》》》 [GESP202312 四级] 小杨的字典 题目描述 在遥远的星球&#xff0c;有两个国家 A 国和 B 国&#xff0c;他们使用着不同的语言&#xff1a;A 语言和 B 语言。小杨是 B 国的翻译官&#xff0c;他的工作是将 A 语言的文章翻译成 B 语言的文章…...

键盘过滤驱动

文章目录 概述注意源码参考资料 概述 irp请求会从io管理器中传递到设备栈中依次向下发送&#xff0c;当到达底层真实设备处理完成后&#xff0c;会依次返回&#xff0c;这时如果在设备栈中有我们自己注册的设备&#xff0c;就可以起到一个过滤的功能。键盘过滤驱动就是如此&am…...

dolphinscheduler2.0.9升级3.1.9版本问题记录

相关版本说明 JDK&#xff1a;JDK (1.8&#xff09; DolphinScheduler &#xff1a;3.1.9 数据库&#xff1a;MySQL (8)&#xff0c;驱动&#xff1a;MySQL JDBC Driver 8.0.16 注册中心&#xff1a;ZooKeeper (3.8.4) 问题一&#xff1a;dolphinscheduler2.0.9对应zk版本使用…...

【权限管理】Apache Shiro学习教程

Apache Shiro 是一个功能强大且灵活的安全框架&#xff0c;主要用于身份认证&#xff08;Authentication&#xff09;、授权&#xff08;Authorization&#xff09;、会话管理&#xff08;Session Management&#xff09;和加密&#xff08;Cryptography&#xff09;。它旨在为…...

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇&#xff0c;在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下&#xff1a; 【Note】&#xff1a;如果你已经完成安装等操作&#xff0c;可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作&#xff0c;重…...

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…...

大数据学习栈记——Neo4j的安装与使用

本文介绍图数据库Neofj的安装与使用&#xff0c;操作系统&#xff1a;Ubuntu24.04&#xff0c;Neofj版本&#xff1a;2025.04.0。 Apt安装 Neofj可以进行官网安装&#xff1a;Neo4j Deployment Center - Graph Database & Analytics 我这里安装是添加软件源的方法 最新版…...

Prompt Tuning、P-Tuning、Prefix Tuning的区别

一、Prompt Tuning、P-Tuning、Prefix Tuning的区别 1. Prompt Tuning(提示调优) 核心思想:固定预训练模型参数,仅学习额外的连续提示向量(通常是嵌入层的一部分)。实现方式:在输入文本前添加可训练的连续向量(软提示),模型只更新这些提示参数。优势:参数量少(仅提…...

Docker 运行 Kafka 带 SASL 认证教程

Docker 运行 Kafka 带 SASL 认证教程 Docker 运行 Kafka 带 SASL 认证教程一、说明二、环境准备三、编写 Docker Compose 和 jaas文件docker-compose.yml代码说明&#xff1a;server_jaas.conf 四、启动服务五、验证服务六、连接kafka服务七、总结 Docker 运行 Kafka 带 SASL 认…...

STM32F4基本定时器使用和原理详解

STM32F4基本定时器使用和原理详解 前言如何确定定时器挂载在哪条时钟线上配置及使用方法参数配置PrescalerCounter ModeCounter Periodauto-reload preloadTrigger Event Selection 中断配置生成的代码及使用方法初始化代码基本定时器触发DCA或者ADC的代码讲解中断代码定时启动…...

渲染学进阶内容——模型

最近在写模组的时候发现渲染器里面离不开模型的定义,在渲染的第二篇文章中简单的讲解了一下关于模型部分的内容,其实不管是方块还是方块实体,都离不开模型的内容 🧱 一、CubeListBuilder 功能解析 CubeListBuilder 是 Minecraft Java 版模型系统的核心构建器,用于动态创…...

智能在线客服平台:数字化时代企业连接用户的 AI 中枢

随着互联网技术的飞速发展&#xff0c;消费者期望能够随时随地与企业进行交流。在线客服平台作为连接企业与客户的重要桥梁&#xff0c;不仅优化了客户体验&#xff0c;还提升了企业的服务效率和市场竞争力。本文将探讨在线客服平台的重要性、技术进展、实际应用&#xff0c;并…...

五年级数学知识边界总结思考-下册

目录 一、背景二、过程1.观察物体小学五年级下册“观察物体”知识点详解&#xff1a;由来、作用与意义**一、知识点核心内容****二、知识点的由来&#xff1a;从生活实践到数学抽象****三、知识的作用&#xff1a;解决实际问题的工具****四、学习的意义&#xff1a;培养核心素养…...