def make_phi_overlay(shape, phi): """Render PHI ONCE onto a canvas. Returns (overlay_array, overlays_meta).""" h, w = shape canvas = Image.new("L", (w, h), 0) # blank canvas draw = ImageDraw.Draw(canvas) overlays, x, y = [], BURN_REGION_X, BURN_REGION_Y for entry in _phi_text_block(phi): x0, y0, x1, y1 = draw.textbbox((x, y), entry["line"], font=FONT) tw, th = x1 - x0, y1 - y0 if x + tw > w or y + th > h: raise ValueError( f"rendered PHI overflows image: '{entry['line']}' " f"at ({x},{y}) size ({tw}x{th}), image {w}x{h}" ) draw.text((x, y), entry["line"], font=FONT, fill=TEXT_COLOR) overlays.append({ "phi_category": entry["phi_category"], "rendered_text": entry["line"], "phi_value": entry["value"], "bbox": [x, y, tw, th], "dicom_tag": entry["dicom_tag"], }) y += th + LINE_GAP return np.array(canvas), overlays