Example #1
0
 def test_save_segmentation(self, tmpdir, data_test_dir):
     seg = LoadROIImage.load(
         [os.path.join(data_test_dir, "test_nucleus_1_1.seg")], metadata={"default_spacing": (1, 1, 1)}
     )
     SaveROI.save(os.path.join(tmpdir, "segmentation.seg"), seg, {"relative_path": False})
     assert os.path.exists(os.path.join(tmpdir, "segmentation.seg"))
     os.makedirs(os.path.join(tmpdir, "seg_save"))
     save_components(
         seg.image,
         seg.selected_components,
         os.path.join(tmpdir, "seg_save"),
         seg.roi_info,
         SaveComponents.get_default_values(),
     )
     assert os.path.isdir(os.path.join(tmpdir, "seg_save"))
     assert len(glob(os.path.join(tmpdir, "seg_save", "*"))) == 4
     seg2 = LoadROI.load([os.path.join(tmpdir, "segmentation.seg")])
     assert seg2 is not None
     save_components(
         seg.image,
         [],
         os.path.join(tmpdir, "seg_save2"),
         seg.roi_info,
         SaveComponents.get_default_values(),
     )
     assert os.path.isdir(os.path.join(tmpdir, "seg_save2"))
     assert len(glob(os.path.join(tmpdir, "seg_save2", "*"))) == 8
Example #2
0
def napari_write_labels(path: str, data: Any, meta: dict) -> Optional[str]:
    if not isinstance(data, numpy.ndarray):
        return
    ext = os.path.splitext(path)[1]
    if ext in SaveROI.get_extensions():
        project = MaskProjectTuple(file_path="", image=None, roi=data)
        SaveROI.save(path, project, parameters={})
        return path
Example #3
0
 def test_save_segmentation_without_image(self, tmpdir, data_test_dir):
     seg = LoadROIImage.load(
         [os.path.join(data_test_dir, "test_nucleus_1_1.seg")], metadata={"default_spacing": (1, 1, 1)}
     )
     seg_clean = dataclasses.replace(seg, image=None, roi=reduce_array(seg.roi))
     SaveROI.save(os.path.join(tmpdir, "segmentation.seg"), seg_clean, {"relative_path": False})
     SaveROI.save(
         os.path.join(tmpdir, "segmentation1.seg"),
         seg_clean,
         {"relative_path": False, "spacing": (210 * 10 ** -6, 70 * 10 ** -6, 70 * 10 ** -6)},
     )
Example #4
0
 def test_save_project_with_history(self, tmp_path, stack_segmentation1, mask_property):
     SaveROI.save(tmp_path / "test1.seg", stack_segmentation1, {"relative_path": False})
     seg2 = dataclasses.replace(
         stack_segmentation1,
         history=[create_history_element_from_segmentation_tuple(stack_segmentation1, mask_property)],
         selected_components=[1],
         mask=stack_segmentation1.roi,
     )
     SaveROI.save(tmp_path / "test1.seg", seg2, {"relative_path": False})
     with tarfile.open(tmp_path / "test1.seg", "r") as tf:
         tf.getmember("mask.tif")
         tf.getmember("segmentation.tif")
         tf.getmember("history/history.json")
         tf.getmember("history/arrays_0.npz")
Example #5
0
 def run_calculation(self):
     while not self.queue.empty():
         task: BatchTask = self.queue.get()
         if isinstance(task.data, str):
             file_path = task.data
             if path.splitext(task.data)[1] == ".seg":
                 project_tuple = LoadROIImage.load([task.data])
             else:
                 project_tuple = LoadStackImage.load([task.data])
         elif isinstance(task.data, MaskProjectTuple):
             project_tuple: MaskProjectTuple = task.data
             file_path = project_tuple.image.file_path
         else:
             continue
         try:
             name = path.basename(file_path)
             blank = get_mask(project_tuple.roi, project_tuple.mask, project_tuple.selected_components)
             algorithm: StackAlgorithm = mask_algorithm_dict[task.parameters.algorithm]()
             algorithm.set_image(project_tuple.image)
             algorithm.set_mask(blank)
             algorithm.set_parameters(**task.parameters.values)
             if isinstance(task.save_prefix, tuple):
                 self.range_signal.emit(0, algorithm.get_steps_num() + 1)
             else:
                 self.range_signal.emit(0, algorithm.get_steps_num())
             # noinspection PyTypeChecker
             segmentation = algorithm.calculation_run(partial(self.progress_info, name))
             state2 = StackSettings.transform_state(
                 project_tuple, segmentation.roi_info, defaultdict(lambda: segmentation.parameters), []
             )
             if isinstance(task.save_prefix, tuple):
                 self.progress_info(name, "saving", algorithm.get_steps_num())
                 name = path.splitext(path.basename(file_path))[0] + ".seg"
                 re_end = re.compile(r"(.*_version)(\d+)\.seg$")
                 while path.exists(path.join(task.save_prefix[0], name)):
                     match = re_end.match(name)
                     if match:
                         num = int(match.group(2)) + 1
                         name = match.group(1) + str(num) + ".seg"
                     else:
                         name = path.splitext(path.basename(file_path))[0] + "_version1.seg"
                 SaveROI.save(path.join(task.save_prefix[0], name), state2, parameters=task.save_prefix[1])
             else:
                 self.multiple_result.emit(state2)
         except Exception as e:  # pylint: disable=W0703
             self.error_signal.emit(f"Exception occurred during proceed {file_path}. Exception info {e}")
         self.index += 1
     self.index = 0
     self.execution_done.emit()
Example #6
0
def napari_write_labels(path: str, data: Any, meta: dict) -> Optional[str]:
    if not isinstance(data, numpy.ndarray):
        return
    ext = os.path.splitext(path)[1]
    if ext in SaveROI.get_extensions():
        project = MaskProjectTuple(file_path="",
                                   image=None,
                                   roi_info=ROIInfo(data))
        SaveROI.save(path,
                     project,
                     parameters={
                         "spacing":
                         numpy.divide(meta["scale"], DEFAULT_SCALE_FACTOR)[-3:]
                     })
        return path
Example #7
0
    def test_loading_new_segmentation(self, tmpdir, data_test_dir):
        image_data = LoadStackImage.load([os.path.join(data_test_dir, "test_nucleus.tif")])
        algorithm = ThresholdAlgorithm()
        algorithm.set_image(image_data.image)
        param = algorithm.get_default_values()
        param["channel"] = 0
        algorithm.set_parameters(**param)
        res = algorithm.calculation_run(lambda x, y: None)
        num = np.max(res.roi) + 1
        data_dict = {str(i): deepcopy(res.parameters) for i in range(1, num)}

        to_save = MaskProjectTuple(
            image_data.image.file_path, image_data.image, None, res.roi, list(range(1, num)), data_dict
        )

        SaveROI.save(os.path.join(tmpdir, "segmentation2.seg"), to_save, {"relative_path": False})
        seg2 = LoadSegmentation.load([os.path.join(tmpdir, "segmentation2.seg")])
        assert seg2 is not None
Example #8
0
 def test_load_project_with_history(self, tmp_path, stack_segmentation1, mask_property):
     image_location = tmp_path / "test1.tif"
     SaveAsTiff.save(image_location, stack_segmentation1)
     seg2 = dataclasses.replace(
         stack_segmentation1,
         history=[create_history_element_from_segmentation_tuple(stack_segmentation1, mask_property)],
         selected_components=[1],
         mask=stack_segmentation1.roi,
         image=stack_segmentation1.image.substitute(file_path=image_location),
         file_path=image_location,
     )
     SaveROI.save(tmp_path / "test1.seg", seg2, {"relative_path": False})
     res = LoadSegmentation.load([tmp_path / "test1.seg"])
     assert res.image == str(image_location)
     assert res.mask is not None
     assert len(res.history) == 1
     assert res.history[0].mask_property == mask_property
     cmp_dict = {str(k): v for k, v in stack_segmentation1.roi_extraction_parameters.items()}
     assert str(res.history[0].segmentation_parameters["parameters"]) == str(cmp_dict)