Save an annotated image with action details to the specified folder.
(img_path, output_folder, gt_action_type, gt_action_detail, pd_action_type, pd_action_detail, type_match, exact_match, subset, episode_id, step_id, task_desc)
| 4 | |
| 5 | |
| 6 | def annotate_and_save_image(img_path, output_folder, gt_action_type, gt_action_detail, pd_action_type, pd_action_detail, type_match, exact_match, subset, episode_id, step_id, task_desc): |
| 7 | """Save an annotated image with action details to the specified folder.""" |
| 8 | # Load the image and get its dimensions |
| 9 | image = Image.open(img_path) |
| 10 | draw = ImageDraw.Draw(image) |
| 11 | |
| 12 | # Dynamically compute font size based on image height |
| 13 | base_height = 1080 # Reference height, e.g., 1080p |
| 14 | font_size = max(12, int(image.height / base_height * 20)) # Ensure minimum font size is 12 |
| 15 | |
| 16 | current_file_path = os.path.abspath(__file__) |
| 17 | current_dir = os.path.dirname(current_file_path) |
| 18 | try: |
| 19 | font = ImageFont.truetype(os.path.join(current_dir, './SimHei.ttf'), font_size) |
| 20 | except IOError: |
| 21 | # If the specified font file does not exist, use the default font |
| 22 | font = ImageFont.load_default() |
| 23 | |
| 24 | w, h = image.width, image.height |
| 25 | |
| 26 | # Create annotation text |
| 27 | annotation_text = ( |
| 28 | f"taskDesc: {task_desc}\n" |
| 29 | f"taskID: {subset}{episode_id}_{step_id}\n" |
| 30 | f"GT action: {gt_action_type}\n" |
| 31 | f"GT detail: {gt_action_detail}\n" |
| 32 | f"PD action: {pd_action_type}\n" |
| 33 | f"PD detail: {pd_action_detail}\n" |
| 34 | f"type_match: {'Yes' if type_match else 'No'}\n" |
| 35 | f"exac_match: {'Yes' if exact_match else 'No'}" |
| 36 | ) |
| 37 | |
| 38 | # Calculate text size and wrap lines if necessary |
| 39 | max_width = w - 20 # Max width for the text |
| 40 | lines = [] |
| 41 | for line in annotation_text.split('\n'): |
| 42 | # Split line by words to check width |
| 43 | words = line.split() |
| 44 | current_line = "" |
| 45 | for word in words: |
| 46 | # Check width after adding a word |
| 47 | test_line = current_line + " " + word if current_line else word |
| 48 | if draw.textlength(test_line, font=font) > max_width: |
| 49 | # If line is too long, start a new line |
| 50 | lines.append(current_line) |
| 51 | current_line = word |
| 52 | else: |
| 53 | current_line = test_line |
| 54 | lines.append(current_line) # Add the final line |
| 55 | |
| 56 | # Draw each line on the image |
| 57 | y_text = 10 |
| 58 | line_spacing = int(font_size * 1.2) # Line spacing is 1.2 times the font size |
| 59 | for line in lines: |
| 60 | draw.text((10, y_text), line, font=font, fill='red') |
| 61 | y_text += line_spacing # Move to next line position |
| 62 | |
| 63 | # Draw rectangle and point based on conditions |