Giter VIP home page Giter VIP logo

Comments (2)

kkhuang1990 avatar kkhuang1990 commented on July 17, 2024

Probably yes. if you can calculate the shortest distance to pixels of GT boundaries for 3D data.

from boundary-loss.

HKervadec avatar HKervadec commented on July 17, 2024

Yes it is very easy to do ; actually the current implementation is somewhat 3d ready. I did the last required part in private ; haven't tested/published that yet.

The surface loss implementation is literally the same ; as we multiply element wise two tensors of same shape [1]

class SurfaceLoss():
    def __init__(self, **kwargs):
        # Self.idc is used to filter out some classes of the target mask. Use fancy indexing
        self.idc: List[int] = kwargs["idc"]
        self.nd: str = kwargs["nd"]  # 'wh' for 2d case, 'whd' for 3d case
        print(f"Initialized {self.__class__.__name__} with {kwargs}")

    def __call__(self, probs: Tensor, dist_maps: Tensor, _: Tensor) -> Tensor:
        assert simplex(probs)
        assert not one_hot(dist_maps)

        pc = probs[:, self.idc, ...].type(torch.float32)
        dc = dist_maps[:, self.idc, ...].type(torch.float32)

        multipled = einsum(f"bk{self.nd},bk{self.nd}->bk{self.nd}", pc, dc)

        loss = multipled.mean()

        return loss

Most of the difference is for the one_hot2dist. Now, we have almost a guarantee that the spatial resolution is different between all axis, so we need to take that into account. The good news is that the function it used internally already handle that case, so it is only a matter of adding an optional parameter:

def one_hot2dist(seg: np.ndarray, resolution: Tuple[float, float, float] = None) -> np.ndarray:
    assert one_hot(torch.tensor(seg), axis=0)
    K: int = len(seg)

    res = np.zeros_like(seg)
    for k in range(K):
        posmask = seg[k].astype(np.bool)

        if posmask.any():
            negmask = ~posmask
            res[k] = distance(negmask, sampling=resolution) * negmask \
                - (distance(posmask, sampling=resolution) - 1) * posmask
        # The idea is to leave blank the negative classes
        # since this is one-hot encoded, another class will supervise that pixel

    return res

At last, I added something in my dataloader to support the different resolution ; there is many ways to do that. I personally had saved the resolution for each 3d volume in a dictionnary (trimmed the loader a lot, you get the idea):

class SliceDataset(Dataset):
    def __init__(self, filenames: List[str], folders: List[Path], are_hots: List[bool],
                 bounds_generators: List[Callable], transforms: List[Callable], debug=False, quiet=False,
                 K=4, in_memory: bool = False, spacing_dict: Dict[str, Tuple[float, ...]] = None,
                 augment: Optional[Callable] = None, ignore_norm: bool = False,
                 dimensions: int = 2, debug_size: int = 10) -> None:
        self.folders: List[Path] = folders
        self.transforms: List[Callable[[Tuple, int], Callable[[D], Tensor]]] = transforms
        assert len(self.transforms) == len(self.folders)

        self.filenames: List[str] = filenames
        self.K: int = K  # Number of classes

        self.spacing_dict: Optional[Dict[str, Tuple[float, ...]]] = spacing_dict
        if self.spacing_dict:
            assert len(self.spacing_dict) == len(self.filenames)
            print(f"> Spacing dictionnary loaded correctly")

    def __getitem__(self, index: int) -> Dict[str, Union[str, Tensor, List[Tensor], List[Tuple[slice, ...]]]]:
        filename: str = self.filenames[index]
        path_name: Path = Path(filename)
        images: List[D]

        if path_name.suffix == ".png":
            images = [Image.open(files[index]) for files in self.files]
        elif path_name.suffix == ".npy":
            images = [np.load(files[index]) for files in self.files]
        else:
            raise ValueError(filename)

        resolution: Tuple[float, ...]
        if self.spacing_dict:
            resolution = self.spacing_dict[path_name.stem]
        else:
            resolution = tuple([1] * self.dimensions)

        # Final transforms and assertions
        assert len(images) == len(self.folders) == len(self.transforms)
        t_tensors: List[Tensor] = [tr(resolution, self.K)(e) for (tr, e) in zip(self.transforms, images)]
        _, *img_shape = t_tensors[0].shape

        final_tensors = t_tensors

        # [...]

        return {'filenames': filename,
                'images': final_tensors[0],
                'gt': final_tensors[1],
                'labels': final_tensors[2:],
                'spacings': torch.tensor(resolution)}

Let me know if something remains unclear, but I believe that going from 2d to 3d is pretty quick ; as long as you already have the 3D CNN obviously.

[1] My code states explicitly the expected number of dimensions with parameters, to explode in case it receives something different. This is my personal philosophy of brittleness on purpose, which allow to easily catch mistakes in the formatting of the data. The default broadcasting rules are so powerful that it often "fails silently", in the sense that it does something (not what you intended to write), but just output non-sense and can take some time to debug.

from boundary-loss.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.