|
| 1 | +import json |
| 2 | +from typing import Dict, Text |
| 3 | + |
| 4 | +import torch |
| 5 | + |
| 6 | +import monai.deploy.core as md |
| 7 | +from monai.data import DataLoader, Dataset |
| 8 | +from monai.deploy.core import ExecutionContext, Image, InputContext, IOType, Operator, OutputContext |
| 9 | +from monai.deploy.operators.monai_seg_inference_operator import InMemImageReader |
| 10 | +from monai.transforms import ( |
| 11 | + Activations, |
| 12 | + Compose, |
| 13 | + EnsureChannelFirst, |
| 14 | + EnsureType, |
| 15 | + LoadImage, |
| 16 | + NormalizeIntensity, |
| 17 | + RepeatChannel, |
| 18 | + Resize, |
| 19 | + SqueezeDim, |
| 20 | +) |
| 21 | + |
| 22 | + |
| 23 | +@md.input("image", Image, IOType.IN_MEMORY) |
| 24 | +@md.output("result_text", Text, IOType.IN_MEMORY) |
| 25 | +class ClassifierOperator(Operator): |
| 26 | + def __init__(self): |
| 27 | + super().__init__() |
| 28 | + self._input_dataset_key = "image" |
| 29 | + self._pred_dataset_key = "pred" |
| 30 | + |
| 31 | + def _convert_dicom_metadata_datatype(self, metadata: Dict): |
| 32 | + if not metadata: |
| 33 | + return metadata |
| 34 | + |
| 35 | + # Try to convert data type for the well knowned attributes. Add more as needed. |
| 36 | + if metadata.get("SeriesInstanceUID", None): |
| 37 | + try: |
| 38 | + metadata["SeriesInstanceUID"] = str(metadata["SeriesInstanceUID"]) |
| 39 | + except Exception: |
| 40 | + pass |
| 41 | + if metadata.get("row_pixel_spacing", None): |
| 42 | + try: |
| 43 | + metadata["row_pixel_spacing"] = float(metadata["row_pixel_spacing"]) |
| 44 | + except Exception: |
| 45 | + pass |
| 46 | + if metadata.get("col_pixel_spacing", None): |
| 47 | + try: |
| 48 | + metadata["col_pixel_spacing"] = float(metadata["col_pixel_spacing"]) |
| 49 | + except Exception: |
| 50 | + pass |
| 51 | + |
| 52 | + print("Converted Image object metadata:") |
| 53 | + for k, v in metadata.items(): |
| 54 | + print(f"{k}: {v}, type {type(v)}") |
| 55 | + |
| 56 | + return metadata |
| 57 | + |
| 58 | + def compute(self, op_input: InputContext, op_output: OutputContext, context: ExecutionContext): |
| 59 | + input_image = op_input.get("image") |
| 60 | + _reader = InMemImageReader(input_image) |
| 61 | + input_img_metadata = self._convert_dicom_metadata_datatype(input_image.metadata()) |
| 62 | + img_name = str(input_img_metadata.get("SeriesInstanceUID", "Img_in_context")) |
| 63 | + |
| 64 | + output_path = context.output.get().path |
| 65 | + |
| 66 | + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 67 | + model = context.models.get() |
| 68 | + |
| 69 | + pre_transforms = self.pre_process(_reader) |
| 70 | + post_transforms = self.post_process() |
| 71 | + |
| 72 | + dataset = Dataset(data=[{self._input_dataset_key: img_name}], transform=pre_transforms) |
| 73 | + dataloader = DataLoader(dataset, batch_size=10, shuffle=False, num_workers=0) |
| 74 | + |
| 75 | + with torch.no_grad(): |
| 76 | + for d in dataloader: |
| 77 | + image = d[0].to(device) |
| 78 | + outputs = model(image) |
| 79 | + out = post_transforms(outputs).data.cpu().numpy()[0] |
| 80 | + print(out) |
| 81 | + |
| 82 | + result_dict = ( |
| 83 | + "A " + ":" + str(out[0]) + " B " + ":" + str(out[1]) + " C " + ":" + str(out[2]) + " D " + ":" + str(out[3]) |
| 84 | + ) |
| 85 | + result_dict_out = {"A": str(out[0]), "B": str(out[1]), "C": str(out[2]), "D": str(out[3])} |
| 86 | + output_folder = context.output.get().path |
| 87 | + output_folder.mkdir(parents=True, exist_ok=True) |
| 88 | + |
| 89 | + output_path = output_folder / "output.json" |
| 90 | + with open(output_path, "w") as fp: |
| 91 | + json.dump(result_dict, fp) |
| 92 | + |
| 93 | + op_output.set(result_dict, "result_text") |
| 94 | + |
| 95 | + def pre_process(self, image_reader) -> Compose: |
| 96 | + return Compose( |
| 97 | + [ |
| 98 | + LoadImage(reader=image_reader, image_only=True), |
| 99 | + EnsureChannelFirst(), |
| 100 | + SqueezeDim(dim=3), |
| 101 | + NormalizeIntensity(), |
| 102 | + Resize(spatial_size=(299, 299)), |
| 103 | + RepeatChannel(repeats=3), |
| 104 | + EnsureChannelFirst(), |
| 105 | + ] |
| 106 | + ) |
| 107 | + |
| 108 | + def post_process(self) -> Compose: |
| 109 | + return Compose([EnsureType(), Activations(sigmoid=True)]) |
0 commit comments