如何将分割的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转换为分割标签通常涉及将每个像素的类别标识(在mask中以不同的灰度值或颜色表示)转换为整数标签。这些标签通常用于机器学习或深度学习模型的训练、验证和测试阶段。 使用方式,控制台或者命令行使用以下命令: pyth…...

【动手学电机驱动】STM32-MBD(5)Simulink 模型开发之 PWM 输出
STM32-MBD(1)安装 Simulink STM32 硬件支持包 STM32-MBD(2)Simulink 模型部署入门 STM32-MBD(3)Simulink 状态机模型的部署 STM32-MBD(4)Simulink 状态机实现按键控制 STM32-MBD&…...

MySQL进阶突击系列(05)突击MVCC核心原理 | 左右护法ReadView视图和undoLog版本链强强联合
2024小结:在写作分享上,这里特别感谢CSDN社区提供平台,支持大家持续学习分享交流,共同进步。社区诚意满满的干货,让大家收获满满。 对我而言,珍惜每一篇投稿分享,每一篇内容字数大概6000字左右&…...

vue2日历组件
这个代码可以直接运行,未防止有组件库没安装,将组件库的代码,转成文字了 vue页面 <template><div class"about"><div style"height: 450px; width: 400px"><div style"height: 100%; overflo…...
【PyQt】多行纯文本框
[toc]qt多行纯文本框 QPlainTextEdit QPlainTextEdit 是可以多行的纯文本编辑框 文本浏览框 内置了一个** QTextDocument **类型的对象 ,存放文档。 1.信号:文本被修改 当文本框中的内容被键盘编辑,被点击就会发出 textChanged 信号&…...
workerman5.0篇〡异步非阻塞协程HTTP客户端
概述 workerman/http-client 是一个异步http客户端组件。所有请求响应异步非阻塞,内置连接池,消息请求和响应符合PSR7规范。 Workerman 5.0 版本中的异步HTTP协程客户端组件是一个基于PHP协程的高性能HTTP客户端,它能够充分利用PHP的异步特…...

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

python+pymysql
python操作mysql 一、python操作数据库 1、下载pymysql 库, 方法一:pip3 install pymysql 或pip install pymysql 方法二:在pycharm中setting下载pymysql 2、打开虚拟机上的数据库 3、pymysql连接 dbpymysql.Connection(host&qu…...
基于 Selenium 实现上海大学校园网自动登录
基于 Selenium 实现上海大学校园网自动登录 一、技术方案 核心工具: Selenium:一个用于自动化测试的工具,能够模拟用户在浏览器上的操作。Edge WebDriver:用于控制 Edge 浏览器的驱动程序。 功能设计: 检测网络状…...

啥!GitHub Copilot也免费使用了
文章目录 前言免费版直接修复代码多文件上下文Agent模式总结 前言 最近,GitHub 给开发者们带来了一个好消息:他们的 AI 编程助手 GitHub Copilot 现在可以免费使用了!以前,每个月要花 10 美元才能享受的服务,现在对所…...
Spring配置文件中:密码明文改为密文处理方式(通用方法)
目录 一、背景 二、思路 A) 普通方式 B) 适合bootstrap.properties方式 三、示例 A) 普通方式(连接Redis集群) A) 普通方式(连接RocketMQ) B) 适合bootstrap.properties方式 四、总结 一、背景 SpringBoot和Sprin…...

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

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

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

【2024年华为OD机试】(C卷,100分)- 分割均衡字符串 (Java JS PythonC/C++)
一、问题描述 题目描述 均衡串定义:字符串中只包含两种字符,且这两种字符的个数相同。 给定一个均衡字符串,请给出可分割成新的均衡子串的最大个数。 约定:字符串中只包含大写的 X 和 Y 两种字符。 输入描述 输入一个均衡串…...

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

GESP202312 四级【小杨的字典】题解(AC)
》》》点我查看「视频」详解》》》 [GESP202312 四级] 小杨的字典 题目描述 在遥远的星球,有两个国家 A 国和 B 国,他们使用着不同的语言:A 语言和 B 语言。小杨是 B 国的翻译官,他的工作是将 A 语言的文章翻译成 B 语言的文章…...
键盘过滤驱动
文章目录 概述注意源码参考资料 概述 irp请求会从io管理器中传递到设备栈中依次向下发送,当到达底层真实设备处理完成后,会依次返回,这时如果在设备栈中有我们自己注册的设备,就可以起到一个过滤的功能。键盘过滤驱动就是如此&am…...

dolphinscheduler2.0.9升级3.1.9版本问题记录
相关版本说明 JDK:JDK (1.8) DolphinScheduler :3.1.9 数据库:MySQL (8),驱动:MySQL JDBC Driver 8.0.16 注册中心:ZooKeeper (3.8.4) 问题一:dolphinscheduler2.0.9对应zk版本使用…...
【权限管理】Apache Shiro学习教程
Apache Shiro 是一个功能强大且灵活的安全框架,主要用于身份认证(Authentication)、授权(Authorization)、会话管理(Session Management)和加密(Cryptography)。它旨在为…...
[2025CVPR]DeepVideo-R1:基于难度感知回归GRPO的视频强化微调框架详解
突破视频大语言模型推理瓶颈,在多个视频基准上实现SOTA性能 一、核心问题与创新亮点 1.1 GRPO在视频任务中的两大挑战 安全措施依赖问题 GRPO使用min和clip函数限制策略更新幅度,导致: 梯度抑制:当新旧策略差异过大时梯度消失收敛困难:策略无法充分优化# 传统GRPO的梯…...
Golang 面试经典题:map 的 key 可以是什么类型?哪些不可以?
Golang 面试经典题:map 的 key 可以是什么类型?哪些不可以? 在 Golang 的面试中,map 类型的使用是一个常见的考点,其中对 key 类型的合法性 是一道常被提及的基础却很容易被忽视的问题。本文将带你深入理解 Golang 中…...
【Linux】C语言执行shell指令
在C语言中执行Shell指令 在C语言中,有几种方法可以执行Shell指令: 1. 使用system()函数 这是最简单的方法,包含在stdlib.h头文件中: #include <stdlib.h>int main() {system("ls -l"); // 执行ls -l命令retu…...
线程与协程
1. 线程与协程 1.1. “函数调用级别”的切换、上下文切换 1. 函数调用级别的切换 “函数调用级别的切换”是指:像函数调用/返回一样轻量地完成任务切换。 举例说明: 当你在程序中写一个函数调用: funcA() 然后 funcA 执行完后返回&…...
java调用dll出现unsatisfiedLinkError以及JNA和JNI的区别
UnsatisfiedLinkError 在对接硬件设备中,我们会遇到使用 java 调用 dll文件 的情况,此时大概率出现UnsatisfiedLinkError链接错误,原因可能有如下几种 类名错误包名错误方法名参数错误使用 JNI 协议调用,结果 dll 未实现 JNI 协…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)
UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中,UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化…...

Linux --进程控制
本文从以下五个方面来初步认识进程控制: 目录 进程创建 进程终止 进程等待 进程替换 模拟实现一个微型shell 进程创建 在Linux系统中我们可以在一个进程使用系统调用fork()来创建子进程,创建出来的进程就是子进程,原来的进程为父进程。…...
go 里面的指针
指针 在 Go 中,指针(pointer)是一个变量的内存地址,就像 C 语言那样: a : 10 p : &a // p 是一个指向 a 的指针 fmt.Println(*p) // 输出 10,通过指针解引用• &a 表示获取变量 a 的地址 p 表示…...

ubuntu22.04有线网络无法连接,图标也没了
今天突然无法有线网络无法连接任何设备,并且图标都没了 错误案例 往上一顿搜索,试了很多博客都不行,比如 Ubuntu22.04右上角网络图标消失 最后解决的办法 下载网卡驱动,重新安装 操作步骤 查看自己网卡的型号 lspci | gre…...
小木的算法日记-多叉树的递归/层序遍历
🌲 从二叉树到森林:一文彻底搞懂多叉树遍历的艺术 🚀 引言 你好,未来的算法大神! 在数据结构的世界里,“树”无疑是最核心、最迷人的概念之一。我们中的大多数人都是从 二叉树 开始入门的,它…...