import gradio as gr import openslide from PIL import Image, ImageDraw from xml.etree import ElementTree as ET # accept slide thumbnail, x, y and annotation def get_mask_from_xml(xml_path, image_size, image_shrinking_factor): tree = ET.parse(xml_path) root = tree.getroot() image = Image.new("L", image_size, "white") draw = ImageDraw.Draw(image) draw.fill = True label2grayscale_color = {"bg": 0, "tissue": 1, "tisuue": 1} for i in root[0]: annotation_type = i.attrib["Type"] annotation_label = i.attrib["PartOfGroup"] # there is roi rectangle if annotation_type not in ["Spline", "Polygon", "Rectangle"]: print(f"Annotation type must be either Spline, Rectangle or Polygon but found: {annotation_type}") continue if annotation_label not in label2grayscale_color: print(f"Annotation label must be either tissue or bg but found: {annotation_label}") continue coordinates = [(i.attrib["X"], i.attrib["Y"]) for i in i[0]] coordinates = [(str2float(x), str2float(y)) for x, y in coordinates] coordinates = [(x*image_shrinking_factor, y*image_shrinking_factor) for x, y in coordinates] if annotation_type in ["Spline", "Polygon"]: draw.polygon(coordinates, fill=label2grayscale_color[annotation_label]) elif annotation_type == "Rectangle": # ^ # | point 1 is bigger than point 3 # | 0 1 # | 3 2 # |-------> draw.rectangle([coordinates[3], coordinates[1]], fill=label2grayscale_color[annotation_label]) # if annotation_type == "Spline": # draw.line(coordinates, fill=label2grayscale_color[annotation_label], width=1) # elif annotation_type == "Polygon": # draw.polygon(coordinates, fill=label2grayscale_color[annotation_label]) return image # output as png or npy def process(x, y, annotation_size, annotation): image_shrinking_factor = annotation_size / min(x, y) # get thumbnail image = get_mask_from_xml(annotation, (annotation_size, annotation_size), image_shrinking_factor) image.save("mask.png") return "mask.png" demo = gr.Interface( fn=process, inputs=[ # gr.File(label="Slide thumbnail", type="file", accept=".png"), gr.Number(label="X", default=10_000), gr.Number(label="Y", default=10_000), gr.Number(label="Thumbnail size", default=500), gr.File(label="ASAP Annotation", type="file", accept=".xml"), ], outputs="image", title="Reverse Text", description="Reverses the text entered by the user", ) demo.launch()