Skip to content

Instantly share code, notes, and snippets.

@Riyasharma-in
Last active March 31, 2023 17:05
Show Gist options
  • Select an option

  • Save Riyasharma-in/68a8553670b25c3be2ee2daf108aa690 to your computer and use it in GitHub Desktop.

Select an option

Save Riyasharma-in/68a8553670b25c3be2ee2daf108aa690 to your computer and use it in GitHub Desktop.
Sorting and Automate Adjustment
def adjust_boxes(boxes):
for i in range(len(boxes)):
for j in range(i+1, len(boxes)):
if j >= len(boxes):
break
# Check if the boxes intersect
if intersect(boxes[i], boxes[j]):
# Determine the overlap distance
dx = min(boxes[i][2], boxes[j][2]) - max(boxes[i][0], boxes[j][0])
dy = min(boxes[i][3], boxes[j][3]) - max(boxes[i][1], boxes[j][1])
# Calculate intersection over union for boxes[i]
# box1_area = (boxes[i][2] - boxes[i][0]) * (boxes[i][3] - boxes[i][1])
# intersection_area = max(0, dx) * max(0, dy)
# iou1 = intersection_area / (box1_area + (boxes[j][2]-boxes[j][0])*(boxes[j][3]-boxes[j][1]) - intersection_area)
xmin1, ymin1, xmax1, ymax1 = boxes[i]
xmin2, ymin2, xmax2, ymax2 = boxes[j]
intersection_area = max(0, min(xmax1, xmax2) - max(xmin1, xmin2)) * max(0, min(ymax1, ymax2) - max(ymin1, ymin2))
box1_area = (xmax1 - xmin1) * (ymax1 - ymin1)
box2_area = (xmax2 - xmin2) * (ymax2 - ymin2)
iou1 = intersection_area / box2_area
iou2 = intersection_area / box1_area
print(iou1,iou2)
# Check if boxes[i] needs adjustment
if iou1 < 0.8:
if iou2 < 0.8:
print("ok")
# Determine which dimension to adjust (height or width)
if dx < dy:
# Adjust the width
w = dx / 2
boxes[i][2] -= w
boxes[j][0] += w
else:
# Adjust the height
h = dy / 2
boxes[i][3] -= h
boxes[j][1] += h
else:
# Merge the boxes
xmin = min(boxes[i][0], boxes[j][0])
ymin = min(boxes[i][1], boxes[j][1])
xmax = max(boxes[i][2], boxes[j][2])
ymax = max(boxes[i][3], boxes[j][3])
boxes[i] = [xmin, ymin, xmax, ymax]
boxes.pop(j)
j -= 1
else:
# Merge the boxes
xmin = min(boxes[i][0], boxes[j][0])
ymin = min(boxes[i][1], boxes[j][1])
xmax = max(boxes[i][2], boxes[j][2])
ymax = max(boxes[i][3], boxes[j][3])
boxes[i] = [xmin, ymin, xmax, ymax]
boxes.pop(j)
j -= 1
return boxes
def intersect(box1, box2):
# Check if the boxes intersect
return (box1[2] > box2[0] and box1[0] < box2[2] and
box1[3] > box2[1] and box1[1] < box2[3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment