Skip to content

Instantly share code, notes, and snippets.

@juliussin
Last active October 22, 2023 19:02
Show Gist options
  • Save juliussin/b021d0ae74f6b4700009636335e48755 to your computer and use it in GitHub Desktop.
Save juliussin/b021d0ae74f6b4700009636335e48755 to your computer and use it in GitHub Desktop.
Convert XYXY format (x,y top left and x,y bottom right) to XYWH format (x,y center point and width, height) and vice versa.
import cv2
import numpy as np
def xyxy_to_xywh(xyxy):
"""
Convert XYXY format (x,y top left and x,y bottom right) to XYWH format (x,y center point and width, height).
:param xyxy: [X1, Y1, X2, Y2]
:return: [X, Y, W, H]
"""
if np.array(xyxy).ndim > 1 or len(xyxy) > 4:
raise ValueError('xyxy format: [x1, y1, x2, y2]')
x_temp = (xyxy[0] + xyxy[2]) / 2
y_temp = (xyxy[1] + xyxy[3]) / 2
w_temp = abs(xyxy[0] - xyxy[2])
h_temp = abs(xyxy[1] - xyxy[3])
return np.array([int(x_temp), int(y_temp), int(w_temp), int(h_temp)])
def xywh_to_xyxy(xywh):
"""
Convert XYWH format (x,y center point and width, height) to XYXY format (x,y top left and x,y bottom right).
:param xywh: [X, Y, W, H]
:return: [X1, Y1, X2, Y2]
"""
if np.array(xywh).ndim > 1 or len(xywh) > 4:
raise ValueError('xywh format: [x1, y1, width, height]')
x1 = xywh[0] - xywh[2] / 2
y1 = xywh[1] - xywh[3] / 2
x2 = xywh[0] + xywh[2] / 2
y2 = xywh[1] + xywh[3] / 2
return np.array([int(x1), int(y1), int(x2), int(y2)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment