python将旋转目标检测到的txt转labelimg2中斜矩形框的xml(正矩形通用)

#-*-codeing:uft-8-*-
import xml.etree.ElementTree as ET
import cv2
import platform
import os
import numpy as np
import math
import random
import shutil



img_dir = r'E:\rotate-yolov5\runs\detect\exp2'
txt_dirs = r"E:\rotate-yolov5\runs\detect\exp2\labels"
same_name = r"E:\rotate-yolov5\runs\detect\exp2\same_name"
xml_dirs = r"txt2xml"
if  not os.path.exists(xml_dirs):
    os.mkdir(xml_dirs)
else:
    shutil.rmtree(xml_dirs)
    os.mkdir(xml_dirs)

CLASSES = ["0","1","2","4","5","6","7","8","9"]
def xml_write(rota_p_img, label, AUG_DIR, aug_name, mode = "bndbox"):
    xml_path = os.path.join(AUG_DIR,aug_name.rsplit(".", 1)[0]+".xml")
    image_path = os.path.join(AUG_DIR,aug_name)
    flag = 0
    for spt in label:
        if spt[4] in CLASSES:
            flag = 1
    
    if flag == 1:
        height, width = rota_p_img.shape[0:2]
        floder = AUG_DIR.split('\\')[-1]
        xml_file = open(xml_path, 'w')
        xml_file.write('<annotation>\n')
        xml_file.write('    <folder>' + floder + '</folder>\n')
        xml_file.write('    <filename>' + str(image_path) + '</filename>\n')
        xml_file.write('    <size>\n')
        xml_file.write('        <width>' + str(width) + '</width>\n')
        xml_file.write('        <height>' + str(height) + '</height>\n')
        xml_file.write('        <depth>3</depth>\n')
        xml_file.write('    </size>\n')

        for spt in label:
            if spt[4] not in CLASSES:
                continue
            # print('spt',spt)
            xml_file.write('    <object>\n')
            xml_file.write('        <name>' + spt[4]+ '</name>\n')
            xml_file.write('        <pose>Unspecified</pose>\n')
            xml_file.write('        <truncated>0</truncated>\n')
            xml_file.write('        <difficult>0</difficult>\n')
            if mode == "robndbox":
                xml_file.write('        <robndbox>\n')
                xml_file.write('            <cx>' + str((int)(spt[0])) + '</cx>\n')
                xml_file.write('            <cy>' + str((int)(spt[1])) + '</cy>\n')
                xml_file.write('            <w>' + str((int)(spt[2])) + '</w>\n')
                xml_file.write('            <h>' + str((int)(spt[3])) + '</h>\n')
                xml_file.write('            <angle>' + str(spt[5]) + '</angle>\n')
                xml_file.write('        </robndbox>\n')
            if mode == "bndbox":
                xml_file.write('        <bndbox>\n')
                xml_file.write('            <xmin>' + str((int)(spt[0])) + '</xmin>\n')
                xml_file.write('            <ymin>' + str((int)(spt[1])) + '</ymin>\n')
                xml_file.write('            <xmax>' + str((int)(spt[2])) + '</xmax>\n')
                xml_file.write('            <ymax>' + str((int)(spt[3])) + '</ymax>\n')
                xml_file.write('        </bndbox>\n')
            xml_file.write('    </object>\n')

        xml_file.write('</annotation>')

old_name_list = []
for root,dirs,files in os.walk(img_dir):
    for file in files:
        if file.endswith((".jpg", ".bmp", ".png",".jpeg")):
            img_path = os.path.join(root, file)
            name = file.rsplit(".", 1)[0]
            if name in old_name_list:
                shutil.move(img_path, same_name)
                continue
            old_name_list.append(name)
            txt_path = os.path.join(txt_dirs, name+".txt")   
            if not os.path.exists(txt_path):
                continue
            img = cv2.imread(img_path)
            h,w = img.shape[0:2]
            labels = []
            with open(txt_path,'r',encoding='utf-8',errors='ignore') as f:
                lines = f.readlines()
                for line in lines:
                    num = line.split(" ")
                    cls = CLASSES[int(num[0])]
                    cx = float(num[1])*w
                    cy = float(num[2])*h
                    cw = float(num[3])*w
                    ch = float(num[4])*h
                    xmin = cx - cw * 0.5
                    xmax = cx + cw * 0.5
                    ymin = cy - ch * 0.5
                    ymax = cy + ch * 0.5
                    # labels.append([cx,cy,cw,ch,cls])
                    labels.append([xmin,ymin,xmax,ymax,cls])
            
            xml_write(img, labels, xml_dirs, file)
            shutil.copy(img_path, xml_dirs)
            
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
如果要使用OpenCV库中的物体检测算法获得目标框和类别信息,可以按照以下步骤进行: 1. 首先,使用OpenCV库读取图像并将其换为数组。可以使用`cv2.imread()`函数来读取图像,该函数返回一个NumPy数组,表示图像的像素值。例如: ```python import cv2 import numpy as np # 读取图像 img = cv2.imread('image.png') # 将图像换为数组 img_arr = np.asarray(img) ``` 2. 接着,使用OpenCV库中的某种物体检测算法来对图像进行目标检测。例如,可以使用Haar级联分类器来对图像进行人脸检测: ```python # 加载Haar级联分类器 face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # 运行人脸检测算法 faces = face_cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=5) ``` 在上面的示例代码中,首先加载Haar级联分类器`face_cascade`,然后使用`detectMultiScale()`函数运行人脸检测算法,得到目标框的坐标和尺寸信息。 3. 最后,使用`faces`数组来获取目标框和类别信息。例如,可以使用以下代码将所有检测到的人脸绘制在图像上,并输出每个人脸的坐标和尺寸信息: ```python # 在图像上绘制所有检测到的人脸 for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) # 输出每个人脸的坐标和尺寸信息 for i, (x,y,w,h) in enumerate(faces): print("Face %d: x=%d, y=%d, w=%d, h=%d" % (i+1, x, y, w, h)) ``` 在上面的示例代码中,`cv2.rectangle()`函数用于在图像上绘制矩形框,`faces`数组包含所有检测到的人脸的坐标和尺寸信息。你可以使用`faces`数组来获取图像中的目标框和类别信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

誓天断发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值