How to convert bounding box (x1, y1, x2, y2) to YOLO Style (X, Y, W, H)

Ahmed Fayez picture Ahmed Fayez · May 13, 2019 · Viewed 7.9k times · Source

I'm training a YOLO model, I have the bounding boxes in this format:-

x1, y1, x2, y2 => ex (100, 100, 200, 200)

I need to convert it to YOLO format to be something like:-

X, Y, W, H => 0.436262 0.474010 0.383663 0.178218

I already calculated the center point X, Y, the height H, and the weight W. But still need a away to convert them to floating numbers as mentioned.

Answer

gameon67 picture gameon67 · May 14, 2019

Here's code snipet in python to convert x,y coordinates to yolo format

def convert(size, box):
    dw = 1./size[0]
    dh = 1./size[1]
    x = (box[0] + box[1])/2.0
    y = (box[2] + box[3])/2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x*dw
    w = w*dw
    y = y*dh
    h = h*dh
    return (x,y,w,h)

im=Image.open(img_path)
w= int(im.size[0])
h= int(im.size[1])


print(xmin, xmax, ymin, ymax) #define your x,y coordinates
b = (xmin, xmax, ymin, ymax)
bb = convert((w,h), b)

Check my sample program to convert from LabelMe annotation tool format to Yolo format https://github.com/ivder/LabelMeYoloConverter