Ejemplo n.º 1
0
    def load_nodule_vol(self, nodule: LIDCNodule):
        volume = nodule.pylidc_scan.to_volume(verbose=False)

        nodule_vol = extract_cube(
            series_volume=volume,
            spacing=nodule.pylidc_scan.spacings,
            nodule_coords=nodule.centroid,
            cube_voxelsize=self.cube_voxelsize,
            extract_size_mm=self.extract_size_mm,
        )
        sphere_mask = geom.sphere(nodule_vol.shape, nodule_vol.shape[0] // 4)
        if self.masked:
            nodule_vol[~sphere_mask] = -2048
        return nodule_vol
def sampleBall(debug=True):
    # parameters as local variables
    shapeimg, radius, step, slices, zoomfactor, approxorder = setParameters()

    n = slices
    slicelist = ((np.arange(n) - (n - 1) / 2) * (2 * radius / n) +
                 (shapeimg / 2)).astype(int)
    logging.debug("slicelist=%s", str(slicelist))
    disklist = []
    centers = []
    for i in range(n):
        # create high resolution ball randomly shifted
        center = np.random.normal(loc=0.5, scale=step, size=3)
        logging.debug("center=%s", str(center))
        hrBall = rg.sphere(shapeimg, radius, position=center).astype(float)
        lrDisk = zoom(hrBall[slicelist[i], :, :],
                      zoomfactor,
                      order=approxorder)
        disklist.append(lrDisk)
        centers.append(center)
    return (centers, slicelist, np.array(disklist))
Ejemplo n.º 3
0
parser = argparse.ArgumentParser("Simple Stardist Generator for a sphere")
parser.add_argument("--directory",
                    help="Directory to store data in.",
                    type=str,
                    default=".")
parser.add_argument("--max_dist",
                    help="Maximum distance for stardist computation",
                    type=float,
                    default=None)
args = parser.parse_args()
directory = args.directory
max_dist = args.max_dist

# generate a dataset with a binary sphere
sphere = raster_geometry.sphere(200, 70).astype(
    np.uint64)  # image size: 200, radius: 70
sphere2 = raster_geometry.sphere(200, 50).astype(np.uint64)
sphere = (sphere + sphere2 - 1).astype(np.uint64)
f = zarr.open(os.path.join(directory, "sphere.n5"), mode="a")
f.create_dataset(name="sphere",
                 shape=sphere.shape,
                 compressor=numcodecs.GZip(6),
                 dtype=sphere.dtype,
                 chunks=(50, 50, 50),
                 overwrite=True)
f["sphere"].attrs["offset"] = (0, 0, 0)
f["sphere"].attrs["resolution"] = (1, 1, 1)
f["sphere"][:] = sphere

# declare arrays to use
labels = gp.ArrayKey("LABELS")
Ejemplo n.º 4
0
 def nuclei_template(self, radius=2.5e-6):
     scaling = self.info["scaling"][0]
     pixel_radius = int(np.round(radius / scaling))
     template = sphere(pixel_radius * 3, pixel_radius)
     return template / template.sum()
# constants
def setParameters(
        shapeimg=350,  # size of the image
        radius=80,  # radius of HR ball
        step=0.1,  # relative to 1
        slices=7,  # number of 2D samples
        zoomfactor=0.1,
        approxorder=1):
    return (shapeimg, radius, step, slices, zoomfactor, approxorder)


# globals, avoid using them
shapeimg, radius, step, slices, zoomfactor, approxorder = setParameters()

# perfect sphere
ball1 = rg.sphere(shapeimg, radius, position=[0.5, 0.7, 0.7]).astype(float)
ball1.shape

plt.figure()
plt.imshow(ball1[int(shapeimg / 2), :, :])
plt.show()

## Random placement, then downsample
center = np.random.normal(loc=0.5, scale=step, size=3)

ball1 = rg.sphere(shapeimg, radius, position=center).astype(float)
print("center=", center)

from scipy.ndimage.interpolation import zoom
smallball1 = zoom(ball1, zoomfactor, order=1)
plt.figure()
Ejemplo n.º 6
0
def qsm_remove_background_sharp(db0_arr,
                                mask_arr,
                                radius=range(11, 3, -2),
                                threshold=np.spacing(1.0),
                                pad_width=0.3,
                                rel_radius=max):
    """
    Filter out the background component of the phase using SHARP.

    EXPERIMENTAL!

    SHARP is the Sophisticated Harmonic Artifact Reduction for Phase data.

    Assumes that no sources are close to the boundary of the mask.

    Both the original SHARP and the V-SHARP variant is implemented, and
    can be chosen via the `radius` parameter.

    Args:
        db0_arr (np.ndarray): The magnetic field variation in ppb.
        mask_arr (np.ndarray): The inner-volume mask.
        radius (int|float): The radius of the kernel sphere.
            If `rel_radius` is False, the radius is in px.
            If `rel_radius` is True, the radius is relative to the largest
            dimension of `db0_arr`.
        threshold (float): The deconvolution threshold.
        pad_width (float|int|Iterable[float|int]): Size of the padding to use.
            This is useful for mitigating border effects.
            If Iterable, a value for each dim must be specified.
            If not Iterable, all dims will have the same value.
            If int, it is interpreted as absolute size.
            If float, it is interpreted as relative to the maximum size.
        rel_radius (bool|callable): Interpret sizes as relative values.
            Determine the interpretation of `radius` using `shape`.
            Uses `flyingcircus.extra.coord()` internally, see its `is_relative`
            parameter for more details.

    Returns:
        db0i_arr (np.ndarray): The internal magnetic field variation in ppb.

    See Also:
        - Schweser, F., Deistung, A., Lehr, B.W., Reichenbach, J.R.,
          2011. Quantitative imaging of intrinsic magnetic tissue properties
          using MRI signal phase: An approach to in vivo brain iron metabolism?
          NeuroImage 54, 2789–2807. doi:10.1016/j.neuroimage.2010.10.070
        - Schweser, F., Robinson, S.D., de Rochefort, L., Li, W., Bredies, K.,
          2016. An illustrated comparison of processing methods for phase MRI
          and QSM: removal of background field contributions from sources
          outside the region of interest. NMR Biomed. n/a-n/a.
          doi:10.1002/nbm.3604
    """
    db0_arr, mask = fcn.padding(db0_arr, pad_width)
    mask_arr, mask = fcn.padding(mask_arr, pad_width)

    radius = fcn.coord(db0_arr.shape, radius, rel_radius, use_int=False)

    # # generate the spherical kernel
    sphere = raster_geometry.sphere(db0_arr.shape, radius).astype(complex)
    sphere /= np.sum(sphere)
    dirac_delta = raster_geometry.nd_dirac_delta(db0_arr.shape, 0.5, 1.0)
    kernel_k = np.fft.fftn(np.fft.ifftshift(dirac_delta - sphere))

    kernel_mask = np.abs(kernel_k) > threshold
    kernel_k_inv = kernel_mask.astype(complex)
    kernel_k_inv[kernel_mask] = 1.0 / kernel_k[kernel_mask]

    # ft_factor = (2 * np.pi)  # can be neglected because it cancels out
    db0_arr = mask_arr * (
        # ((1j * ft_factor) ** 2) *
        np.fft.ifftn(np.fft.fftn(db0_arr) * kernel_k))
    db0_arr = np.real(
        # ((1j / ft_factor) ** 2) *
        np.fft.ifftn(np.fft.fftn(db0_arr) * kernel_k_inv))

    return db0_arr[mask]