Skip to content

Instantly share code, notes, and snippets.

@senemaktas
Created July 7, 2022 07:41
Show Gist options
  • Save senemaktas/40ceda41d34d8784f0c1b018b6d545bc to your computer and use it in GitHub Desktop.
Save senemaktas/40ceda41d34d8784f0c1b018b6d545bc to your computer and use it in GitHub Desktop.
yolo_to_cv2 and cv2_to_yolo
def yolo_to_cv2(x, y, w, h, dh, dw):
xmin = int((x - w / 2) * dw)
xmax = int((x + w / 2) * dw)
ymin = int((y - h / 2) * dh)
ymax = int((y + h / 2) * dh)
if xmin < 0:
xmin = 0
if xmax > dw - 1:
xmax = dw - 1
if ymax < 0:
ymax = 0
if ymin > dh - 1:
ymin = dh - 1
return xmin, ymin, xmax, ymax
def cv2_to_yolo(label_box, H, W):
# Convert from opencv format to yolo format H,W is the image height and width
yolo_boxes = []
for i in range(len(label_box)):
x, y, bbox_W, bbox_H = label_box[i][0], label_box[i][1], label_box[i][2], label_box[i][3]
bbox_W = label_box[i][2] - label_box[i][0]
bbox_H = label_box[i][3] - label_box[i][1]
center_bbox_x = x + (bbox_W / 2)
center_bbox_y = y + (bbox_H / 2)
yolo_bbox = [center_bbox_x / W, center_bbox_y / H, bbox_W / W, bbox_H / H]
yolo_boxes.append(yolo_bbox)
return yolo_boxes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment