def mandelbrot(h, w, maxit):
"""
Returns an image of the Mandelbrot fractal of size (h,w).
"""
y, x = np.ogrid[-1.4:1.4:h * 1j, -2:0.8:w * 1j]
c = x + y * 1j
z = c
divtime = maxit + np.zeros(z.shape, dtype=int)
for i in range(maxit):
z = z ** 2 + c
diverge = z * np.conj(z) > 2 ** 2
div_now = diverge & (divtime == maxit)
divtime[div_now] = i + 100
z[diverge] = 2
logger.debug("Updating divtime")
recorder.record('divtime', divtime)
return divtime
python类ogrid()的实例源码
def make_3d_mask(img_shape, center, radius, shape='sphere'):
mask = np.zeros(img_shape)
radius = np.rint(radius)
center = np.rint(center)
sz = np.arange(int(max(center[0] - radius, 0)), int(max(min(center[0] + radius + 1, img_shape[0]), 0)))
sy = np.arange(int(max(center[1] - radius, 0)), int(max(min(center[1] + radius + 1, img_shape[1]), 0)))
sx = np.arange(int(max(center[2] - radius, 0)), int(max(min(center[2] + radius + 1, img_shape[2]), 0)))
sz, sy, sx = np.meshgrid(sz, sy, sx)
if shape == 'cube':
mask[sz, sy, sx] = 1.
elif shape == 'sphere':
distance2 = ((center[0] - sz) ** 2
+ (center[1] - sy) ** 2
+ (center[2] - sx) ** 2)
distance_matrix = np.ones_like(mask) * np.inf
distance_matrix[sz, sy, sx] = distance2
mask[(distance_matrix <= radius ** 2)] = 1
elif shape == 'gauss':
z, y, x = np.ogrid[:mask.shape[0], :mask.shape[1], :mask.shape[2]]
distance = ((z - center[0]) ** 2 + (y - center[1]) ** 2 + (x - center[2]) ** 2)
mask = np.exp(- 1. * distance / (2 * radius ** 2))
mask[(distance > 3 * radius ** 2)] = 0
return mask
def make_2d_gaussian(self, center=(0, 0)):
'''Makes a 2D Gaussian filter with arbitary mean and variance.
Args:
center (tuple): The coordinates of the center of the Gaussian,
specified as :data:`(row, col)`. The center of the image is
:data:`(0, 0)`.
Returns:
numpy array: The Gaussian mask.
'''
sigma = self.sigma
n_rows = (self.patch_size - 1.) / 2.
n_cols = (self.patch_size - 1.) / 2.
y, x = np.ogrid[-n_rows: n_rows + 1, -n_cols: n_cols + 1]
y0, x0 = center[1], center[0]
gaussian_mask = np.exp(-((x - x0) ** 2 + (y - y0) ** 2) /
(2. * sigma ** 2))
gaussian_mask[gaussian_mask <
np.finfo(gaussian_mask.dtype).eps *
gaussian_mask.max()] = 0
gaussian_mask = 1. / gaussian_mask.max() * gaussian_mask
return gaussian_mask
def create_disk_mask(x_size, y_size, x_center, y_center, radius):
"""
This function ...
:param x_size:
:param y_size:
:param x_center:
:param y_center:
:param radius:
:return:
"""
# Calculate which pixels should be masked
y,x = np.ogrid[-y_center:y_size-y_center, -x_center:x_size-x_center]
mask = x*x + y*y <= radius*radius
# Return the mask
return mask
# -----------------------------------------------------------------
#def union(*args): # i wanted to do it this way, but didn't succeed ...
def create_disk_mask(x_size, y_size, x_center, y_center, radius):
"""
This function ...
:param x_size:
:param y_size:
:param x_center:
:param y_center:
:param radius:
:return:
"""
# Calculate which pixels should be masked
y,x = np.ogrid[-y_center:y_size-y_center, -x_center:x_size-x_center]
mask = x*x + y*y <= radius*radius
# Return the mask
return mask
# -----------------------------------------------------------------
#def union(*args): # i wanted to do it this way, but didn't succeed ...
def fspecialgauss2D(shape=(3,3),sigma=0.5):
"""
2D gaussian mask - should give the same result as MATLAB's
fspecial('gaussian',[shape],[sigma])
"""
m,n = [(ss-1.)/2. for ss in shape]
y,x = np.ogrid[-m:m+1,-n:n+1]
h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )
## The statement below determines the machine
## epsilon - if gaussian is smaller than that
## set to 0.
h[ h < np.finfo(h.dtype).eps*h.max() ] = 0
sumh = h.sum()
## This notation states that it takes the input
## h and then it divides by the sum and returns h
if sumh != 0:
h /= sumh
return h
def matlab_style_gauss2d(shape=(3, 3), sigma=0.5):
"""
2D gaussian mask - should give the same result as MATLAB's
fspecial('gaussian',[shape],[sigma])
"""
m, n = [(ss-1.)/2. for ss in shape]
y, x = np.ogrid[-m:m+1, -n:n+1]
h = np.exp(-(x*x + y*y)/(2.*sigma*sigma))
h[h < np.finfo(h.dtype).eps*h.max()] = 0
sumh = h.sum()
if sumh != 0:
h /= sumh
return h
# returns the surrounding N-rectangular neighborhood of matrix m, centered
# at pixel (x,y), (odd valued N)
def main(imgsize):
y, x = np.ogrid[6: -6: imgsize*2j, -6: 6: imgsize*2j]
z = x + y*1j
z = RiemannSphere(Klein(Mobius(Klein(z))))
# define colors in hsv space
H = np.sin(z[0]*np.pi)**2
S = np.cos(z[1]*np.pi)**2
V = abs(np.sin(z[2]*np.pi) * np.cos(z[2]*np.pi))**0.2
HSV = np.dstack((H, S, V))
# transform to rgb space
img = hsv_to_rgb(HSV)
fig = plt.figure(figsize=(imgsize/100.0, imgsize/100.0), dpi=100)
ax = fig.add_axes([0, 0, 1, 1], aspect=1)
ax.axis('off')
ax.imshow(img)
fig.savefig('kaleidoscope.png')
def apply(self):
sc = self.scene
org = self.original
factor = self.factor
sx, sy = sc.displacement.shape
gx, gy = num.ogrid[0:sx, 0:sy]
regions = sy/factor * (gx/factor) + gy/factor
indices = num.arange(regions.max() + 1)
def block_downsample(arr):
res = ndimage.mean(
arr,
labels=regions,
index=indices)
res.shape = (sx/factor, sy/factor)
return res
sc.displacement = block_downsample(sc.displacement)
sc.theta = block_downsample(sc.theta)
sc.phi = block_downsample(sc.phi)
sc.frame.dLat = org['frame.dLat'] * self.factor
sc.frame.dLon = org['frame.dLat'] * self.factor
functions.py 文件源码
项目:Semantic-Segmentation-using-Adversarial-Networks
作者: oyam
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def bilinear_interpolation_kernel(in_channels, out_channels, ksize):
"""calculate a bilinear interpolation kernel
Args:
in_channels (int): Number of channels of input arrays. If ``None``,
parameter initialization will be deferred until the first forward
data pass at which time the size will be determined.
out_channels (int): Number of channels of output arrays.
ksize (int): Size of filters (a.k.a. kernels).
"""
factor = (ksize + 1) / 2
if ksize % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:ksize, :ksize]
k = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
W = np.zeros((in_channels, out_channels, ksize, ksize)).astype(np.float32)
W[range(in_channels), range(out_channels), :, :] = k
return W
def gen_aperture(imgsize,ypos,xpos,radius,pixval=1,showaperture=False,verbose=True):
"""
Generating an aperture image
--- INPUT ---
imgsize The dimensions of the array to return. Expects [y-size,x-size].
The aperture will be positioned in the center of a (+/-x-size/2., +/-y-size/2) sized array
ypos Pixel position in the y direction
xpos Pixel position in the x direction
radius Radius of aperture in pixels
showaperture Display image of generated aperture
verbose Toggle verbosity
--- EXAMPLE OF USE ---
import tdose_utilities as tu
apertureimg = tu.gen_aperture([20,40],10,5,10,showaperture=True)
apertureimg = tu.gen_aperture([2000,4000],900,1700,150,showaperture=True)
"""
if verbose: print ' - Generating aperture in image (2D array)'
y , x = np.ogrid[-ypos:imgsize[0]-ypos, -xpos:imgsize[1]-xpos]
mask = x*x + y*y <= radius**2.
aperture = np.zeros(imgsize)
if verbose: print ' - Assigning pixel value '+str(pixval)+' to aperture'
aperture[mask] = pixval
if showaperture:
if verbose: print ' - Displaying resulting image of aperture'
plt.imshow(aperture,interpolation='none')
plt.title('Generated aperture')
plt.show()
return aperture
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
def get_local_mesh(self):
"""Returns the local decomposed physical mesh"""
X = np.ogrid[self.rank*self.Np[0]:(self.rank+1)*self.Np[0],
:self.N[1], :self.N[2]]
X[0] = (X[0]*self.L[0]/self.N[0]).astype(self.float)
X[1] = (X[1]*self.L[1]/self.N[1]).astype(self.float)
X[2] = (X[2]*self.L[2]/self.N[2]).astype(self.float)
X = [np.broadcast_to(x, self.real_shape()) for x in X]
return X
def get_local_mesh(self):
xzrank = self.comm0.Get_rank() # Local rank in xz-plane
xyrank = self.comm1.Get_rank() # Local rank in xy-plane
# Create the physical mesh
x1 = slice(xzrank * self.N1[0], (xzrank+1) * self.N1[0], 1)
x2 = slice(xyrank * self.N2[1], (xyrank+1) * self.N2[1], 1)
X = np.ogrid[x1, x2, :self.N[2]]
X[0] = (X[0]*self.L[0]/self.N[0]).astype(self.float)
X[1] = (X[1]*self.L[1]/self.N[1]).astype(self.float)
X[2] = (X[2]*self.L[2]/self.N[2]).astype(self.float)
X = [np.broadcast_to(x, self.real_shape()) for x in X]
return X
CRFCNNImageSegmentation.py 文件源码
项目:CRF-image-segmentation
作者: therealnidhin
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def upsample_filt(size):
"""
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
def get_upsample_filter(size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
filter = (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
return torch.from_numpy(filter).float()
def plottimestream(array, ax, xtick='time', **kwargs):
"""Plot timestream data.
Args:
array (xarray.DataArray): Array which the timestream data are included.
ax (matplotlib.axes): Axis you want to plot on.
xtick (str): Type of x axis.
'time': Time.
'index': Time index.
kwargs (optional): Plot options passed to ax.plot().
"""
logger = getLogger('decode.plot.plottimestream')
kidtpdict = {0: 'wideband', 1: 'filter', 2: 'blind'}
if xtick == 'time':
ax.plot(array.time, array, **kwargs)
elif xtick == 'index':
ax.plot(np.ogrid[:len(array.time)], array, **kwargs)
ax.set_xlabel('{}'.format(xtick), fontsize=20, color='grey')
# for label in ax.get_xticklabels():
# label.set_rotation(45)
ax.set_ylabel(str(array.datatype.values), fontsize=20, color='grey')
ax.legend()
kidid = int(array.kidid)
try:
kidtp = kidtpdict[int(array.kidtp)]
except KeyError:
kidtp = 'filter'
ax.set_title('ch #{} ({})'.format(kidid, kidtp), fontsize=20, color='grey')
logger.info('timestream data (ch={}) has been plotted.'.format(kidid))
def _upsample_filt(size):
'''
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
'''
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
def upsample_filt(size):
"""
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
def _get_upsampling_filter(size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
filter = (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
return filter
def upsample_filt(size):
"""
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
def upsample_filt(size):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
# set parameters s.t. deconvolutional layers compute bilinear interpolation
# N.B. this is for deconvolution without groups
def upsample_filt(size):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
# set parameters s.t. deconvolutional layers compute bilinear interpolation
# N.B. this is for deconvolution without groups
def get_binary_mask(diameter):
d = diameter
_map = np.zeros((d, d), dtype = np.float32)
r = d / 2
s = int(d / 2)
y, x = np.ogrid[-s:d - s, -s:d - s]
mask = x * x + y * y <= r * r
_map[mask] = 1.0
return _map
def upsample_filt(size):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
# set parameters s.t. deconvolutional layers compute bilinear interpolation
# N.B. this is for deconvolution without groups
def upsample_filt(size):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
def upsample_filt(size):
"""
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
def sort_volumes_per_voxel(input_volumes, sort_matrix):
"""Sort the given volumes per voxel using the sort index in the given matrix.
What this essentially does is to look per voxel from which map we should take the first value. Then we place that
value in the first volume and we repeat for the next value and finally for the next voxel.
If the length of the 4th dimension is > 1 we shift the 4th dimension to the 5th dimension and sort
the array as if the 4th dimension values where a single value. This is useful for sorting (eigen)vector matrices.
Args:
input_volumes (:class:`list`): list of 4d ndarray
sort_matrix (ndarray): 4d ndarray with for every voxel the sort index
Returns:
:class:`list`: the same input volumes but then with every voxel sorted according to the given sort index.
"""
def load_maps(map_list):
tmp = []
for data in map_list:
if isinstance(data, string_types):
data = load_nifti(data).get_data()
if len(data.shape) < 4:
data = data[..., None]
tmp.append(data)
return tmp
input_volumes = load_maps(input_volumes)
if input_volumes[0].shape[3] > 1:
volume = np.concatenate([np.reshape(m, m.shape[0:3] + (1,) + (m.shape[3],)) for m in input_volumes], axis=3)
grid = np.ogrid[[slice(x) for x in volume.shape]]
sorted_volume = volume[list(grid[:-2]) + [np.reshape(sort_matrix, sort_matrix.shape + (1,))] + list(grid[-1])]
return [sorted_volume[..., ind, :] for ind in range(len(input_volumes))]
else:
volume = np.concatenate([m for m in input_volumes], axis=3)
sorted_volume = volume[list(np.ogrid[[slice(x) for x in volume.shape]][:-1])+[sort_matrix]]
return [np.reshape(sorted_volume[..., ind], sorted_volume.shape[0:3] + (1,))
for ind in range(len(input_volumes))]
def upsample_filt(size):
"""
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
def upsample_filt(size):
"""
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
def upsample_filt(size):
"""
Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.
"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)