制作yolov8-obb训练集
·
import math
import os
from lxml import etree
import cv2
def xywhr_to_xyxyxyxy(x_center, y_center, width, height, angle_rad):
"""
将中心点坐标 (x_center, y_center)、宽度、高度、旋转弧度角转换为四个角点坐标。
参数:
x_center, y_center: 中心点坐标(归一化或绝对值均可,需与后续图像尺寸匹配)
width, height: 目标的宽度和高度
angle_rad: 旋转角度(弧度),范围通常为 [-π/2, π/2)
返回:
list: 四个角点的坐标 [x1, y1, x2, y2, x3, y3, x4, y4]
"""
# 计算旋转矩阵
cos = math.cos(angle_rad)
sin = math.sin(angle_rad)
# 计算未旋转时的四个角点(相对于中心点)
w = width / 2
h = height / 2
corners = [
(-w, -h), # 左上角相对坐标
(w, -h), # 右上角
(w, h), # 右下角
(-w, h) # 左下角
]
# 应用旋转矩阵并转换到绝对坐标
rotated_corners = []
for x, y in corners:
x_rot = x * cos - y * sin + x_center
y_rot = x * sin + y * cos + y_center
rotated_corners.extend([x_rot, y_rot])
return rotated_corners
baseDir = r'F:\HRSC2016_dataset\HRSC2016\FullDataSet\Annotations'
for filename in os.listdir(baseDir):
filepath = os.path.join(baseDir,filename)
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(filepath, parser)
root = tree.getroot()
Img_SizeWidth = int(root.find('Img_SizeWidth').text)
Img_SizeHeight = int(root.find('Img_SizeHeight').text)
HRSC_Objects = root.find('HRSC_Objects')
if len(HRSC_Objects.findall('HRSC_Object')) > 0:
try:
img = cv2.imread(
r'F:\HRSC2016_dataset\HRSC2016\FullDataSet\AllImages\{}'.format(filename.replace('xml', 'bmp')))
cv2.imwrite(r'F:\obb\train\images\{}'.format(filename.replace('xml', 'jpg')), img)
fw = open(os.path.join(r'F:\obb\train\labels', filename.replace('xml', 'txt'), ), 'w')
for HRSC_Object in HRSC_Objects.findall('HRSC_Object'):
mbox_cx = float(HRSC_Object.find('mbox_cx').text)# / Img_SizeWidth
mbox_cy = float(HRSC_Object.find('mbox_cy').text)# / Img_SizeHeight
mbox_w = float(HRSC_Object.find('mbox_w').text)# / Img_SizeWidth
mbox_h = float(HRSC_Object.find('mbox_h').text)# / Img_SizeHeight
mbox_ang = float(HRSC_Object.find('mbox_ang').text)
# fw.write('0 ' + str(mbox_cx) + ' ' + str(mbox_cy) + ' ' + str(mbox_w) + ' ' + str(mbox_h) + ' ' + str(mbox_ang) + '\n')
# fw.write('0 ' + str(mbox_cx) + ' ' + str(mbox_cy) + ' ' + str(mbox_w) + ' ' + str(mbox_h) + '\n')
corners = xywhr_to_xyxyxyxy(mbox_cx,mbox_cy,mbox_w,mbox_h,mbox_ang)
print(corners)
x1 = corners[0] / Img_SizeWidth
y1 = corners[1] / Img_SizeHeight
x2 = corners[2] / Img_SizeWidth
y2 = corners[3] /Img_SizeHeight
x3 = corners[4] / Img_SizeWidth
y3 = corners[5] / Img_SizeHeight
x4 = corners[6] / Img_SizeWidth
y4 = corners[7] / Img_SizeHeight
fw.write('0 ' + str(x1) + ' ' + str(y1) + ' ' + str(x2) + ' ' + str(y2) + ' ' + str(x3) + ' ' + str(y3) + ' ' + str(x4) + ' ' + str(y4) + '\n')
fw.close()
except:
pass
更多推荐

所有评论(0)