Created
May 1, 2024 14:27
-
-
Save dhuynh95/311aed424d1baaad42379326e4f4eba7 to your computer and use it in GitHub Desktop.
LaVague evaluation functions with Intersection over Union
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def compute_box(element): | |
location = element.location | |
size = element.size | |
# Coordinates | |
x_coordinate = location['x'] | |
y_coordinate = location['y'] | |
# Size | |
width = size['width'] | |
height = size['height'] | |
box = { | |
"x": x_coordinate, | |
"y": y_coordinate, | |
"width": width, | |
"height": height | |
} | |
return box | |
def print_box(box): | |
from PIL import Image, ImageDraw | |
driver.save_screenshot("page_screenshot.png") | |
image = Image.open("page_screenshot.png") | |
draw = ImageDraw.Draw(image) | |
# Calculate rectangle coordinates | |
left = box['x'] | |
top = box['y'] | |
right = left + box['width'] | |
bottom = top + box['height'] | |
# Draw a rectangle around the element | |
draw.rectangle([left, top, right, bottom], outline="red", width=2) | |
# Save the modified image | |
image.save("highlighted_element.png") | |
from IPython.display import Image, display | |
display(Image(filename="highlighted_element.png")) | |
def calculate_iou(box1, box2): | |
""" | |
Calculate the Intersection over Union (IoU) of two bounding boxes. | |
Parameters: | |
box1, box2: dictionaries containing 'x', 'y', 'width', 'height' of each box | |
Returns: | |
float: the IoU of box1 and box2 | |
""" | |
# Convert boxes from [x, y, width, height] to [xmin, ymin, xmax, ymax] | |
xmin1, ymin1 = box1['x'], box1['y'] | |
xmax1, ymax1 = xmin1 + box1['width'], ymin1 + box1['height'] | |
xmin2, ymin2 = box2['x'], box2['y'] | |
xmax2, ymax2 = xmin2 + box2['width'], ymin2 + box2['height'] | |
# Determine the (x, y)-coordinates of the intersection rectangle | |
x_left = max(xmin1, xmin2) | |
y_top = max(ymin1, ymin2) | |
x_right = min(xmax1, xmax2) | |
y_bottom = min(ymax1, ymax2) | |
# Compute the area of intersection rectangle | |
intersection_area = max(0, x_right - x_left) * max(0, y_bottom - y_top) | |
# Compute the area of both bounding boxes | |
box1_area = (xmax1 - xmin1) * (ymax1 - ymin1) | |
box2_area = (xmax2 - xmin2) * (ymax2 - ymin2) | |
# Compute the union area | |
union_area = box1_area + box2_area - intersection_area | |
# Compute the IoU | |
iou = intersection_area / union_area if union_area != 0 else 0 | |
return iou |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment