| import re | |
| from PIL import Image, ImageDraw | |
| def get_boxed_image(image, sub_text, alpha=0.3): | |
| ''' | |
| image: Image.Image. | |
| sub_text: String like "(x1, y1), (x2, y2), (x3, y3), (x4, y4)", or it's illegal. | |
| alpha: The transparency of the box. | |
| ''' | |
| bbox_list = [(int(x), int(y)) for x, y in re.findall(r'\((\d+),(\d+)\)', sub_text)] | |
| if len(bbox_list) % 2 != 0: | |
| print(f"The coordinate string {sub_text} is illegal, as we extract {len(bbox_list)} coordinates from it!") | |
| return None | |
| image = Image.open(image) | |
| width, height = image.size | |
| image = image.convert("RGBA") | |
| overlay = Image.new("RGBA", image.size, (255, 0, 0, 0)) | |
| draw = ImageDraw.Draw(overlay) | |
| red_color = (255, 0, 0, int(255 * alpha)) | |
| border_width = max(1, int(min(image.size) * 0.005)) | |
| for i in range(0, len(bbox_list), 2): | |
| x1, y1 = bbox_list[i] | |
| x2, y2 = bbox_list[i + 1] | |
| x1, y1, x2, y2 = int(x1/999 * width), int(y1/999 * height), int(x2/999 * width), int(y2/999 * height) | |
| x1 = max(0, min(x1, width)) | |
| y1 = max(0, min(y1, height)) | |
| x2 = max(0, min(x2, width)) | |
| y2 = max(0, min(y2, height)) | |
| if x2 <= x1 or y2 <= y1: | |
| print(f"The uniformed coordinates ({x1}, {y1}), ({x2}, {y2}) are illegal, as the positions of them are wrong!") | |
| return None | |
| for i in range(border_width): | |
| draw.rectangle( | |
| [x1 - i, y1 - i, x2 + i, y2 + i], | |
| outline=red_color | |
| ) | |
| return Image.alpha_composite(image, overlay).convert("RGB") | |
| id = 1673 | |
| image = f'public_eval/bbox_step_300/MathVerse_MINI/20250418/images/{id}.png' | |
| text = '''<think>This table presents information about a point A in relation to a reference point O, including its true bearing and compass direction.\n\nStep 1. Identify the column 'True Bearing'(190,269),(388,935), which contains the true bearing of point A from point O.\nStep 2. Locate the value in the column 'True Bearing': 32°.\nStep 3. Conclude that the true bearing of A from O is 32°.</think>\n<answer>32°</answer>''' | |
| box_image = get_boxed_image(image=image, sub_text=text) | |
| if box_image: | |
| box_image.show() | |
| box_image.save(image.replace('.png', '_bbox.png')) | |