MONAI icon indicating copy to clipboard operation
MONAI copied to clipboard

Update the SaveImage transform to support saving input-output mapping.

Open binliunls opened this issue 1 year ago • 1 comments

Is your feature request related to a problem? Please describe. When I run a segmentation bundle like spleen segmentation, I would like to have a new json/yaml/csv file to explicitly show the input-output mapping between images and labels. For example if the input and output folders are like:

--input
   --input_0.nii.gz
   --input_1.nii.gz
   -- ...
   --input_n.nii.gz

--output
   --input_0/input_0_seg.nii.gz
   --input_1/input_1_seg.nii.gz
   --...
   --input_n/input_n_seg.nii.gz

Describe the solution you'd like A json file with content shown below should be generated if the parameter is specified:

[
    {image: ["/path/to/image/input/input_0.nii.gz"], label: ["/path/to/seg/output/input_0/input_0_seg.nii.gz"]},
    {image: ["/path/to/image/input/input_1.nii.gz"], label: ["/path/to/seg/output/input_1/input_1_seg.nii.gz"]},
    ...,
    {image: ["/path/to/image/input/input_n.nii.gz"], label: ["/path/to/seg/output/input_n/input_n_seg.nii.gz"]},
]

The image and label parameters are set to lists in case there are multiple inputs/outputs.

binliunls avatar Mar 18 '24 07:03 binliunls

Hi @binliunls , as you mentioned, creating a mapping JSON file indeed helps in examining data correspondences. Therefore, I tried to implement a function to assist in creating this JSON file, which includes the paths for images and labels. This function is expected to be integrated into image_reader.py and image_writer.py.

The function is as follows:

def update_json(self, input_file=None, output_file=None):
        record_path = "img-label.json"

        if not os.path.exists(record_path) or os.stat(record_path).st_size == 0:
            with open(record_path, 'w') as f:
                json.dump([], f)

        with open(record_path, 'r+') as f:
            records = json.load(f)
            if input_file:
                new_record = {"image": input_file, "label": []}
                records.append(new_record)
            elif output_file and records:
                records[-1]["label"].append(output_file)

            f.seek(0)
            json.dump(records, f, indent=4)

And here is the result:

{
        "image": [
            "sampledata/imagesTs/s0037.nii.gz"
        ],
        "label": [
            "eval/s0037/s0037_trans.nii.gz"
        ]
}

Please let me know if you think this is feasible.

staydelight avatar May 13 '24 10:05 staydelight