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+
import numpy as np
|
| 4 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def draw_findings_on_image(image, findings):
|
| 8 |
+
"""
|
| 9 |
+
Add annotations to X-ray image based on findings
|
| 10 |
+
|
| 11 |
+
Args:
|
| 12 |
+
image (PIL.Image): Original X-ray image
|
| 13 |
+
findings (dict): Analysis findings with probabilities
|
| 14 |
+
|
| 15 |
+
Returns:
|
| 16 |
+
PIL.Image: Annotated image
|
| 17 |
+
"""
|
| 18 |
+
# Create a copy of the image to draw on
|
| 19 |
+
img = image.copy()
|
| 20 |
+
draw = ImageDraw.Draw(img)
|
| 21 |
+
|
| 22 |
+
# Get image dimensions
|
| 23 |
+
width, height = img.size
|
| 24 |
+
|
| 25 |
+
# Try to use a nice font, fall back to default if not available
|
| 26 |
+
try:
|
| 27 |
+
font = ImageFont.truetype("arial.ttf", 20)
|
| 28 |
+
small_font = ImageFont.truetype("arial.ttf", 16)
|
| 29 |
+
except IOError:
|
| 30 |
+
font = ImageFont.load_default()
|
| 31 |
+
small_font = ImageFont.load_default()
|
| 32 |
+
|
| 33 |
+
# Add findings at the top
|
| 34 |
+
y_position = 10
|
| 35 |
+
for finding, probability in findings.items():
|
| 36 |
+
if isinstance(probability, float):
|
| 37 |
+
text = f"{finding}: {probability:.2f}"
|
| 38 |
+
# Color code based on probability and finding type
|
| 39 |
+
if finding == "No findings":
|
| 40 |
+
color = (0, 128, 0) # Green for no findings
|
| 41 |
+
elif probability > 0.5:
|
| 42 |
+
color = (255, 0, 0) # Red for high probability issues
|
| 43 |
+
else:
|
| 44 |
+
color = (255, 165, 0) # Orange for lower probability issues
|
| 45 |
+
|
| 46 |
+
draw.text((10, y_position), text, fill=color, font=small_font)
|
| 47 |
+
y_position += 25
|
| 48 |
+
|
| 49 |
+
return img
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def create_combined_visualization(image, image_results, text_results, combined_results):
|
| 53 |
+
"""
|
| 54 |
+
Create a comprehensive visualization of all analysis results
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
image (PIL.Image): Original X-ray image
|
| 58 |
+
image_results (dict): Image analysis results
|
| 59 |
+
text_results (dict): Text analysis results
|
| 60 |
+
combined_results (dict): Combined multimodal results
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
PIL.Image: Visualization image
|
| 64 |
+
"""
|
| 65 |
+
# Create a copy of the image to draw on
|
| 66 |
+
img = image.copy()
|
| 67 |
+
|
| 68 |
+
# Create a header with the recommendation
|
| 69 |
+
recommendation = combined_results.get("Recommendation", "No recommendation")
|
| 70 |
+
confidence = combined_results.get("Confidence", "N/A")
|
| 71 |
+
|
| 72 |
+
# Create a white background for the header
|
| 73 |
+
header_height = 60
|
| 74 |
+
header_img = Image.new("RGB", (img.width, header_height), color=(255, 255, 255))
|
| 75 |
+
header_draw = ImageDraw.Draw(header_img)
|
| 76 |
+
|
| 77 |
+
# Try to use a nice font, fall back to default if not available
|
| 78 |
+
try:
|
| 79 |
+
font = ImageFont.truetype("arial.ttf", 18)
|
| 80 |
+
small_font = ImageFont.truetype("arial.ttf", 14)
|
| 81 |
+
except IOError:
|
| 82 |
+
font = ImageFont.load_default()
|
| 83 |
+
small_font = ImageFont.load_default()
|
| 84 |
+
|
| 85 |
+
# Add recommendation text
|
| 86 |
+
header_draw.text((10, 5), recommendation, fill=(0, 0, 0), font=font)
|
| 87 |
+
header_draw.text(
|
| 88 |
+
(10, 35), f"Confidence: {confidence}", fill=(100, 100, 100), font=small_font
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Combine the header and image
|
| 92 |
+
combined_img = Image.new("RGB", (img.width, img.height + header_height))
|
| 93 |
+
combined_img.paste(header_img, (0, 0))
|
| 94 |
+
combined_img.paste(img, (0, header_height))
|
| 95 |
+
|
| 96 |
+
return combined_img
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def generate_report_plot(image_findings, text_findings):
|
| 100 |
+
"""
|
| 101 |
+
Generate a comparison plot of image and text findings
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
image_findings (dict): Image analysis results
|
| 105 |
+
text_findings (dict): Text analysis results
|
| 106 |
+
|
| 107 |
+
Returns:
|
| 108 |
+
bytes: PNG image data as bytes
|
| 109 |
+
"""
|
| 110 |
+
# Create figure
|
| 111 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
|
| 112 |
+
|
| 113 |
+
# Plot image findings
|
| 114 |
+
image_labels = []
|
| 115 |
+
image_values = []
|
| 116 |
+
for k, v in image_findings.items():
|
| 117 |
+
if isinstance(v, float):
|
| 118 |
+
image_labels.append(k)
|
| 119 |
+
image_values.append(v)
|
| 120 |
+
|
| 121 |
+
# Sort by value for better visualization
|
| 122 |
+
sorted_indices = np.argsort(image_values)[::-1] # Descending order
|
| 123 |
+
image_labels = [image_labels[i] for i in sorted_indices]
|
| 124 |
+
image_values = [image_values[i] for i in sorted_indices]
|
| 125 |
+
|
| 126 |
+
# Plot bars for image findings
|
| 127 |
+
ax1.barh(image_labels, image_values, color="skyblue")
|
| 128 |
+
ax1.set_xlim(0, 1)
|
| 129 |
+
ax1.set_title("X-ray Analysis")
|
| 130 |
+
ax1.set_xlabel("Probability")
|
| 131 |
+
|
| 132 |
+
# Plot text findings (assuming text_findings has a structure to visualize)
|
| 133 |
+
ax2.axis("off") # Turn off axis
|
| 134 |
+
ax2.text(0.1, 0.9, "Text Analysis Results:", fontweight="bold")
|
| 135 |
+
y_pos = 0.8
|
| 136 |
+
for key, value in text_findings.items():
|
| 137 |
+
if key != "Entities":
|
| 138 |
+
ax2.text(0.1, y_pos, f"{key}: {value}")
|
| 139 |
+
y_pos -= 0.1
|
| 140 |
+
|
| 141 |
+
# Adjust layout
|
| 142 |
+
plt.tight_layout()
|
| 143 |
+
|
| 144 |
+
# Convert to image bytes
|
| 145 |
+
buf = io.BytesIO()
|
| 146 |
+
plt.savefig(buf, format="png")
|
| 147 |
+
buf.seek(0)
|
| 148 |
+
|
| 149 |
+
# Close the plot to avoid memory leaks
|
| 150 |
+
plt.close(fig)
|
| 151 |
+
|
| 152 |
+
return buf.getvalue()
|