zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python工具方法 24 语义分割结果按连通域分割提取其外接矩形保存为yolo标注

Python方法工具 结果 保存 分割 提取 24
2023-09-14 09:15:04 时间

将语义分割结果按每一种label下的连通域进行分割,并提取其外接矩形(x,y,h,w),并除以图像的size转化相对值描述的yolo标注。

1、单个图片转矩形框用txt描述

特别说明的是,对于图片以0为背景值,但保存的txt描述,class_index会减1。如果不适用于自己的数据,请将now_t-1修改为now_t即可

import cv2
import numpy as np
from PIL import Image

def get_rect(path,min_area=4):
    img = Image.open(path)
    gray = np.array(img)
    size=gray.shape[:2]
    #获取全部的label
    type=np.unique(gray)
    cc=0
    #针对每一个label进行掩码操作
    f=open(path.replace(path.split('.')[-1],'txt'),'w')
    for t in type:
        #跳过背景
        if t==0:
            continue
        binary=gray.copy()
        binary[binary!=t]=0
        binary[binary>0]=1
        binary=(binary*255).astype(np.uint8)
        contours,hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)#查找轮廓
        #print(len(contours))
        #针对特定的label下&