1. YOLO数据格式介绍
YOLO标签的数据是一个相对值,而不是绝对值。
YOLO标签数据为原始图像对应的txt文件,每一张图像对应一个txt,其中包含了多条标签信息。
数据格式表示为:
1:[目标类别]
2:[目标中心点横坐标与图像宽度比值]
3:[目标中心点纵坐标与图像高度比值]
4:[目标框与图像宽度比值]
5:[目标框与图像高度比值]
2. 代码
将bbox的绝对值转化为YOLO数据格式,此处以xywh为例:
import cv2
def xywh_to_yolo(img_path, x, y, w, h):
# img_path: 原始图像路径
img = cv2.imread(img_path)
img_w, img_h = img.shape[1], img.shape[0]
dw = 1./img_w
dh = 1./img_h
cx = (x + (x+w))/2.0
cy = (y + (y+h))/2.0
x = cx*dw
y = cy*dh
w = w*dw
h = h*dh
return (x, y, w, h)
YOLO标注格式转化为XYWH标注格式
def yolo_to_xywh(img, x, y, w, h):
img_w, img_h = img.shape[1], img.shape[0]
x_t = x*img_w
y_t = y*img_h
w_t = w*img_w
h_t = h*img_h
top_left_x = int(x_t - w_t / 2)
top_left_y = int(y_t - h_t / 2)
bottom_right_x = int(x_t + w_t / 2)
bottom_right_y = int(y_t + h_t / 2)
ww = bottom_right_x-top_left_x
hh = bottom_right_y-top_left_y
return (top_left_x, top_left_y, ww, hh)