import torch


def calc_iou(bbox_a, bbox_b):
	"""calculate the iou between two bounding box

	Args:
		bbox_a: (R, 4) contains (y1, x1, y2, x2)
		bbox_b: (R, 4) contains (y1, x1, y2, x2)

	Returns:
		(R, R)
	"""
	assert bbox_a.size(1) == bbox_b.size(1) == 4 and bbox_a.size(0) == bbox_b.size(1)
	i_tl = torch.max(bbox_a[:, None, :2], bbox_b[:, :2])
	i_br = torch.min(bbox_a[:, None, 2:], bbox_b[:, 2:])

	area_i = torch.prod(i_br - i_tl, dim=2) * (i_tl < i_br).all(dim=2)
	area_a = torch.prod(bbox_a[:, 2:] - bbox_a[:, :2], dim=1)
	area_b = torch.prod(bbox_b[:, 2:] - bbox_b[:, :2], dim=1)

	return area_i / (area_a[:, None] + area_b - area_i)