Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _py_star_dist3D(img, rays, grid=(1,1,1)):
grid = _normalize_grid(grid,3)
img = img.astype(np.uint16, copy=False)
dst_shape = tuple(s // a for a, s in zip(grid, img.shape)) + (len(rays),)
dst = np.empty(dst_shape, np.float32)
dzs, dys, dxs = rays.vertices.T
for i in range(dst_shape[0]):
for j in range(dst_shape[1]):
for k in range(dst_shape[2]):
value = img[i * grid[0], j * grid[1], k * grid[2]]
if value == 0:
dst[i, j, k] = 0
else:
for n, (dz, dy, dx) in enumerate(zip(dzs, dys, dxs)):
x, y, z = np.float32(0), np.float32(0), np.float32(0)
def __init__(self, axes='YX', n_rays=32, n_channel_in=1, grid=(1,1), backbone='unet', **kwargs):
"""See class docstring."""
super().__init__(axes=axes, n_channel_in=n_channel_in, n_channel_out=1+n_rays)
# directly set by parameters
self.n_rays = int(n_rays)
self.grid = _normalize_grid(grid,2)
self.backbone = str(backbone).lower()
# default config (can be overwritten by kwargs below)
if self.backbone == 'unet':
self.unet_n_depth = 3
self.unet_kernel_size = 3,3
self.unet_n_filter_base = 32
self.unet_n_conv_per_depth = 2
self.unet_pool = 2,2
self.unet_activation = 'relu'
self.unet_last_activation = 'relu'
self.unet_batch_norm = False
self.unet_dropout = 0.0
self.unet_prefix = ''
self.net_conv_after_unet = 128
else:
if rays is None:
if 'rays_json' in kwargs:
rays = rays_from_json(kwargs['rays_json'])
elif 'n_rays' in kwargs:
rays = Rays_GoldenSpiral(kwargs['n_rays'])
else:
rays = Rays_GoldenSpiral(96)
elif np.isscalar(rays):
rays = Rays_GoldenSpiral(rays)
super().__init__(axes=axes, n_channel_in=n_channel_in, n_channel_out=1+len(rays))
# directly set by parameters
self.n_rays = len(rays)
self.grid = _normalize_grid(grid,3)
self.anisotropy = anisotropy if anisotropy is None else tuple(anisotropy)
self.backbone = str(backbone).lower()
self.rays_json = rays.to_json()
if 'anisotropy' in self.rays_json['kwargs']:
if self.rays_json['kwargs']['anisotropy'] is None and self.anisotropy is not None:
self.rays_json['kwargs']['anisotropy'] = self.anisotropy
print("Changing 'anisotropy' of rays to %s" % str(anisotropy))
elif self.rays_json['kwargs']['anisotropy'] != self.anisotropy:
warnings.warn("Mismatch of 'anisotropy' of rays and 'anisotropy'.")
# default config (can be overwritten by kwargs below)
if self.backbone == 'unet':
self.unet_n_depth = 2
self.unet_kernel_size = 3,3,3
self.unet_n_filter_base = 32
def _cpp_star_dist3D(lbl, rays, grid=(1,1,1)):
dz, dy, dx = rays.vertices.T
grid = _normalize_grid(grid,3)
return c_star_dist3d(lbl.astype(np.uint16, copy=False),
dz.astype(np.float32, copy=False),
dy.astype(np.float32, copy=False),
dx.astype(np.float32, copy=False),
int(len(rays)), *tuple(int(a) for a in grid))
def _ocl_star_dist3D(lbl, rays, grid=(1,1,1)):
from gputools import OCLProgram, OCLArray, OCLImage
grid = _normalize_grid(grid,3)
# if not all(g==1 for g in grid):
# raise NotImplementedError("grid not yet implemented for OpenCL version of star_dist3D()...")
res_shape = tuple(s//g for s, g in zip(lbl.shape, grid))
lbl_g = OCLImage.from_array(lbl.astype(np.uint16, copy=False))
dist_g = OCLArray.empty(res_shape + (len(rays),), dtype=np.float32)
rays_g = OCLArray.from_array(rays.vertices.astype(np.float32, copy=False))
program = OCLProgram(path_absolute("kernels/stardist3d.cl"), build_options=['-D', 'N_RAYS=%d' % len(rays)])
program.run_kernel('stardist3d', res_shape[::-1], None,
lbl_g, rays_g.data, dist_g.data,
np.int32(grid[0]),np.int32(grid[1]),np.int32(grid[2]))
return dist_g.get()
def non_maximum_suppression_3d(dist, prob, rays, grid=(1,1,1), b=2, nms_thresh=0.5, prob_thresh=0.5, verbose=False):
"""Non-Maximum-Supression of 3D polyhedra
Retains only polyhedra whose overlap is smaller than nms_thresh
dist.shape = (Nz,Ny,Nx, n_rays)
prob.shape = (Nz,Ny,Nx)
"""
# TODO: using b>0 with grid>1 can suppress small/cropped objects at the image boundary
assert prob.ndim == 3 and dist.ndim == 4 and dist.shape[-1] == len(rays) and prob.shape == dist.shape[:3]
grid = _normalize_grid(grid,3)
verbose and print("predicting instances with prob_thresh = {prob_thresh} and nms_thresh = {nms_thresh}".format(prob_thresh=prob_thresh, nms_thresh=nms_thresh), flush=True)
ind_thresh = prob > prob_thresh
if b is not None and b > 0:
_ind_thresh = np.zeros_like(ind_thresh)
_ind_thresh[b:-b,b:-b,b:-b] = True
ind_thresh &= _ind_thresh
points = np.stack(np.where(ind_thresh), axis=1)
verbose and print("found %s candidates"%len(points))
probi = prob[ind_thresh]
disti = dist[ind_thresh]
_sorted = np.argsort(probi)[::-1]
probi = probi[_sorted]
def dist_to_coord(rhos, grid=(1,1)):
"""convert from polar to cartesian coordinates for a single image (3-D array) or multiple images (4-D array)"""
grid = _normalize_grid(grid,2)
is_single_image = rhos.ndim == 3
if is_single_image:
rhos = np.expand_dims(rhos,0)
assert rhos.ndim == 4
n_images,h,w,n_rays = rhos.shape
coord = np.empty((n_images,h,w,2,n_rays),dtype=rhos.dtype)
start = np.indices((h,w))
for i in range(2):
coord[...,i,:] = grid[i] * np.broadcast_to(start[i].reshape(1,h,w,1), (n_images,h,w,n_rays))
phis = ray_angles(n_rays).reshape(1,1,1,n_rays)
coord[...,0,:] += rhos * np.sin(phis) # row coordinate
coord[...,1,:] += rhos * np.cos(phis) # col coordinate