def inner_extract(self,B,signature):
w,h =B.shape[:2]
LL,(HL,LH,HH) = pywt.dwt2(B[:32*(w//32),:32*(h//32)],'haar')
LL_1,(HL_1,LH_1,HH_1) = pywt.dwt2(LL,'haar')
LL_2,(HL_2,LH_2,HH_2) = pywt.dwt2(LL_1,'haar')
LL_3,(HL_3,LH_3,HH_3) = pywt.dwt2(LL_2,'haar')
LL_4,(HL_4,LH_4,HH_4) = pywt.dwt2(LL_3,'haar')
_,_,_,ori_sig = self._gene_embed_space(HH_3)
ext_sigs=[]
ext_sigs.extend(self._extract_sig(ori_sig,len(signature)))
ext_sigs.extend(self._extract_sig(np.rot90(ori_sig,1),len(signature)))
ext_sigs.extend(self._extract_sig(np.rot90(ori_sig,2),len(signature)))
ext_sigs.extend(self._extract_sig(np.rot90(ori_sig,3),len(signature)))
return ext_sigs
python类rot90()的实例源码
def mk_rotations(img):
#
# DESCRIPTION
# This function create 8 roatation image fro an input image 4 rotation from the raw image and 4 rotation form the transposed
#
# INPUTS
# img np.array
#
# OUTPUTS
# rotated_image_img, img90, img180, img270, imgT, imgT90, imgT180,imgT270
#
#
img90 = np.rot90(img)
img180 = np.rot90(img,k=2)
img270 = np.rot90(img,k=3)
imgT = np.zeros(img.shape)
if np.size(img.shape)>2:
for i in range(3):
imgT[:,:,i] =img[:,:,i].T
else:
imgT = img.T
imgT90 = np.rot90(imgT)
imgT180 = np.rot90(imgT, k=2)
imgT270 = np.rot90(imgT, k=3)
return img, img90, img180, img270, imgT, imgT90, imgT180,imgT270
def unrotate(rot0, rot1, rot2, rot3, rot4, rot5, rot6, rot7):
#
# DESCRIPTION
# Functions that merges the 8 mapped images as described in the beginning of the file back to the original format
# Uses element wise product
#
#
unrot = np.copy(rot0)
unrot*=np.rot90((rot1),k=3)
unrot*=np.rot90((rot2),k=2)
unrot*=np.rot90((rot3),k=1)
unrot*=(rot4.T)
unrot*=np.rot90((rot5),k=3).T
unrot*=np.rot90((rot6),k=2).T
unrot*=np.rot90((rot7),k=1).T
return unrot
## ##
## ##
## EXECUTION ##
## ##
## ##
def mk_rotations(img):
##INPUT:
## img: a 3D RGB array
##OUTPUT
## 8 rotated and transposed versions of img
img90 = np.rot90(img)
img180 = np.rot90(img,k=2)
img270 = np.rot90(img,k=3)
imgT = np.zeros(img.shape)
if np.size(img.shape)>2:
for i in range(3):
imgT[:,:,i] =img[:,:,i].T
else:
imgT = img.T
imgT90 = np.rot90(imgT)
imgT180 = np.rot90(imgT, k=2)
imgT270 = np.rot90(imgT, k=3)
return img, img90, img180, img270, imgT, imgT90, imgT180,imgT270
## Formats an image to save format
def getMagSpec(sig, rate, winlen, winstep, NFFT):
#get frames
winfunc = lambda x:np.ones((x,))
frames = psf.sigproc.framesig(sig, winlen*rate, winstep*rate, winfunc)
#Magnitude Spectrogram
magspec = np.rot90(psf.sigproc.magspec(frames, NFFT))
return magspec
#Split signal into five-second chunks with overlap of 4 and minimum length of 3 seconds
#Use these settings for other chunk lengths:
#winlen, winstep, seconds
#0.05, 0.0097, 5s
#0.05, 0.0195, 10s
#0.05, 0.0585, 30s
def getMagSpec(sig, rate, winlen, winstep, NFFT):
#get frames
winfunc = lambda x:np.ones((x,))
frames = psf.sigproc.framesig(sig, winlen*rate, winstep*rate, winfunc)
#Magnitude Spectrogram
magspec = np.rot90(psf.sigproc.magspec(frames, NFFT))
return magspec
#Split signal into five-second chunks with overlap of 4 and minimum length of 1 second
#Use these settings for other chunk lengths:
#winlen, winstep, seconds
#0.05, 0.0097, 5s
#0.05, 0.0195, 10s
#0.05, 0.0585, 30s
def test_discrete_phantom_uniform():
"""The uniform discrete phantom is the same after rotating 90 degrees."""
d0 = discrete_phantom(p, 100, ratio=10, prop='mass_atten')
p.rotate(theta=np.pi/2, point=Point([0.5, 0.5]))
d1 = np.rot90(discrete_phantom(p, 100, ratio=10, prop='mass_atten'))
# plot rotated phantom
plot_phantom(p)
# plot the error
plt.figure()
plt.imshow(d1-d0, interpolation=None)
plt.colorbar()
# plt.show(block=True)
# assert_allclose(d0, d1)
def load_dotted_image(self, train_id, scale=1, border=0, circled=False):
img = self._load_image('dotted', train_id, scale, border)
if train_id in self.extra_masks:
for row, col, radius in self.extra_masks[train_id]:
rr, cc = skimage.draw.circle(row, col, radius, shape = img.shape)
img = np.copy(img)
img[rr, cc] = (0, 0, 0)
# When dotted image is rotated relative to train, apply hot patch. (kudos: @authman)
if train_id in self.dotted_rotate:
rot = self.dotted_rotate[train_id]
img = np.rot90(img, rot)
if circled:
assert scale == 1
assert border == 0
img = np.copy(img)
img = self.draw_circles(np.copy(img), self.tid_coords[train_id])
return img
def get_lateral(self, resolution=0.5):
if hasattr(self, "lateral") and resolution == resolution:
return self.lateral
max_dist = self.get_max_dist()
dim = np.ceil(np.absolute(max_dist / resolution))
max_dist = dim * resolution
self.resolution = resolution
a = np.meshgrid(np.linspace(0, max_dist, dim), np.linspace(0, max_dist, dim))
r = (a[0]**2 + a[1]**2)**0.5
sigma = self.sigma / ((8 * log(2))**0.5)
lateral = 1 / ((2 * pi * sigma**2)**0.5) * np.exp(-(r**2) / (2 * sigma**2))
tot_lat = np.zeros((2 * dim - 1, 2 * dim - 1))
tot_lat[dim - 1:2 * dim - 1, dim - 1:2 * dim - 1] = lateral
tot_lat[dim - 1:2 * dim - 1, 0:dim - 1] = np.rot90(lateral, 3)[:, 0:dim - 1]
tot_lat[0:dim - 1, 0:dim - 1] = np.rot90(lateral, 2)[0:dim - 1, 0:dim - 1]
tot_lat[0:dim - 1, dim - 1:2 * dim - 1] = np.rot90(lateral)[0:dim - 1, :]
self.lateral = tot_lat
return self.lateral
def _apply_transformations(plot_config, data_slice):
"""Rotate, flip and zoom the data slice.
Depending on the plot configuration, this will apply some transformations to the given data slice.
Args:
plot_config (mdt.visualization.maps.base.MapPlotConfig): the plot configuration
data_slice (ndarray): the 2d slice of data to transform
Returns:
ndarray: the transformed 2d slice of data
"""
if plot_config.rotate:
data_slice = np.rot90(data_slice, plot_config.rotate // 90)
if not plot_config.flipud:
# by default we flipud to correct for matplotlib lower origin. If the user
# sets flipud, we do not need to to it
data_slice = np.flipud(data_slice)
data_slice = plot_config.zoom.apply(data_slice)
return data_slice
def _augment_chunks(self, chunks):
if self.choices_augmentation is None:
return chunks
chunks_new = []
choice = np.random.choice(self.choices_augmentation)
for chunk in chunks:
chunk_new = chunk
if choice in [1, 3, 5, 7]:
chunk_new = np.flip(chunk_new, axis=1)
if choice in [2, 3]:
chunk_new = np.rot90(chunk_new, 1, axes=(1, 2))
elif choice in [4, 5]:
chunk_new = np.rot90(chunk_new, 2, axes=(1, 2))
elif choice in [6, 7]:
chunk_new = np.rot90(chunk_new, 3, axes=(1, 2))
chunks_new.append(chunk_new)
return chunks_new
def random_augment_image(image, row):
# start0_max, end0_max, start1_max, end1_max = get_bounding_boxes_positions(image, row)
# image = cv2.rectangle(image, (int(start1_max), int(start0_max)), (int(end1_max), int(end0_max)), (0, 0, 255), thickness=5)
if random.randint(0, 1) == 0:
image = return_random_crop(image, row)
else:
image = return_random_perspective(image, row)
image = random_rotate(image)
# all possible mirroring and flips (in total there are only 8 possible configurations)
mirror = random.randint(0, 1)
if mirror != 0:
image = image[::-1, :, :]
angle = random.randint(0, 3)
if angle != 0:
image = np.rot90(image, k=angle)
image = lightning_change(image)
image = blur_image(image)
return image
def rot(self):
for i in range(len(self.Q)):
Q = self.Q[i]
ans = self.ans[i]
refArea = self.area[i]
refMask = self.mask[i]
for rotate in range(3):
self.Q.append(Q)
self.ans.append(ans)
refArea = np.rot90(refArea)
refMask = np.rot90(refMask)
self.area.append(refArea)
self.mask.append(refMask)
return self
def rot90(img):
'''
rotate one or multiple grayscale or color images 90 degrees
'''
s = img.shape
if len(s) == 3:
if s[2] in (3, 4): # color image
out = np.empty((s[1], s[0], s[2]), dtype=img.dtype)
for i in range(s[2]):
out[:, :, i] = np.rot90(img[:, :, i])
else: # mutliple grayscale
out = np.empty((s[0], s[2], s[1]), dtype=img.dtype)
for i in range(s[0]):
out[i] = np.rot90(img[i])
elif len(s) == 2: # one grayscale
out = np.rot90(img)
elif len(s) == 4 and s[3] in (3, 4): # multiple color
out = np.empty((s[0], s[2], s[1], s[3]), dtype=img.dtype)
for i in range(s[0]): # for each img
for j in range(s[3]): # for each channel
out[i, :, :, j] = np.rot90(img[i, :, :, j])
else:
NotImplemented
return out
def shot_heatmap(df,sigma = 1,log=False,player_pic=True,ax=None,cmap='jet'):
'''
This function plots a heatmap based on the shot chart.
input - dataframe with x and y coordinates.
optional - log (default false) plots heatmap in log scale.
player (default true) adds player's picture and name if true
sigma - the sigma of the Gaussian kernel. In feet (default=1)
'''
n,_,_ = np.histogram2d( 0.1*df['LOC_X'].values, 0.1*df['LOC_Y'].values,bins = [500, 500],range = [[-25,25],[-5.25,44.75]])
KDE = ndimage.filters.gaussian_filter(n,10.0*sigma)
N = 1.0*KDE/np.sum(KDE)
if ax is None:
ax = plt.gca(xlim = [30,-30],ylim = [-7,43],xticks=[],yticks=[],aspect=1.0)
court(ax,outer_lines=True,color='black',lw=2.0,direction='down')
ax.axis('off')
if log:
ax.imshow(np.rot90(np.log10(N+1)),cmap=cmap,extent=[25.0, -25.0, -5.25, 44.75])
else:
ax.imshow(np.rot90(N),cmap=cmap,extent=[25.0, -25.0, -5.25, 44.75])
if player_pic:
player_id = df.PLAYER_ID.values[0]
pic = players_picture(player_id)
ax.imshow(pic,extent=[15,25,30,37.8261])
ax.text(0,-7,'By: Doingthedishes',color='white',horizontalalignment='center',fontsize=20,fontweight='bold')
def rot90(self, turns=1):
"""
Rotates the blocks in the counter-clockwise direction. (As numpy
does it.)
"""
# Rotate the individual Y-layer matrices
new_blocks = np.array([np.rot90(by, turns) for by in self.blocks])
new_data = np.array([np.rot90(dy, turns) for dy in self.data])
new_mask = np.array([np.rot90(my, turns) for my in self.mask])
# Rotate the data (if applicable)
for y in xrange(new_data.shape[0]):
for z in xrange(new_data.shape[1]):
for x in xrange(new_data.shape[2]):
b = new_blocks[y, z, x]
d = new_data[y, z, x]
new_data[y, z, x] = self.data_rot90(b, d, turns)
return MaskedSubChunk(new_blocks, new_data, new_mask)
def data_rot90(self, block, data, turns):
"""
Specially rotate this block, which has an orientation that depends on
the data value.
"""
blockname = blocks.block_names[block]
# Torches (redstone and normal)
torches = ["redstone_torch", "unlit_redstone_torch", "torch"]
if blockname in torches:
return blocks.Torch.rot90(data, turns)
# Repeaters
repeaters = ["unpowered_repeater", "powered_repeater"]
if blockname in repeaters:
return blocks.Repeater.rot90(data, turns)
# Comparators
comparators = ["unpowered_comparator", "powered_comparator"]
if blockname in comparators:
return blocks.Comparator.rot90(data, turns)
return data
def _display_pixels(x, y, counts, pixelsize):
"""
Display pixels at coordinates (x, y) coloured with "counts".
This routine is fast but not fully general as it assumes the spaxels
are on a regular grid. This needs not be the case for Voronoi binning.
"""
xmin, xmax = np.min(x), np.max(x)
ymin, ymax = np.min(y), np.max(y)
nx = int(round((xmax - xmin)/pixelsize) + 1)
ny = int(round((ymax - ymin)/pixelsize) + 1)
img = np.full((nx, ny), np.nan) # use nan for missing data
j = np.round((x - xmin)/pixelsize).astype(int)
k = np.round((y - ymin)/pixelsize).astype(int)
img[j, k] = counts
plt.imshow(np.rot90(img), interpolation='nearest', cmap='prism',
extent=[xmin - pixelsize/2, xmax + pixelsize/2,
ymin - pixelsize/2, ymax + pixelsize/2])
#----------------------------------------------------------------------
def visualize2D(fig, ax, xs, ys, bins=200,
xlabel='x', ylabel='y',
xlim=None, ylim=None):
H, xedges, yedges = numpy.histogram2d(xs, ys, bins)
H = numpy.rot90(H)
H = numpy.flipud(H)
Hmasked = numpy.ma.masked_where(H == 0, H)
ax.pcolormesh(xedges, yedges, Hmasked)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if xlim is None:
xlim = (min(xs), max(xs))
if ylim is None:
ylim = (min(ys), max(ys))
ax.set_xlim(*xlim)
ax.set_ylim(*ylim)
fig.colorbar(pyplot.contourf(Hmasked))
def rot180(images):
"""
????180??
??HW/CHW/NCHW?????images?
"""
out = np.empty(shape=images.shape, dtype=images.dtype)
if images.ndim == 2:
out = np.rot90(images, k=2)
elif images.ndim == 3:
for c in xrange(images.shape[0]):
out[c] = np.rot90(images[c], k=2)
elif images.ndim == 4:
for n in xrange(images.shape[0]):
for c in xrange(images.shape[1]):
out[n][c] = np.rot90(images[n][c], k=2)
else:
raise Exception('Invalid ndim: ' + str(images.ndim) +
', only support ndim between 2 and 4.')
return out
# ????f????x???f???df???x???
def grad_magnitude(img):
"""Calculate the gradient magnitude of an image.
Args:
img The image
Returns:
gradient image"""
img = img / 255.0
sobel_y = np.array([
[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]
])
sobel_x = np.rot90(sobel_y) # rotates counter-clockwise
# apply x/y sobel filter to get x/y gradients
imgx = signal.correlate(img, sobel_x, mode="same")
imgy = signal.correlate(img, sobel_y, mode="same")
imgmag = np.sqrt(imgx**2 + imgy**2)
return imgmag
def main():
"""Load image, apply filter, plot."""
img = data.camera()
# just like sobel, but no -2/+2 in the middle
prewitt_y = np.array([
[-1, -1, -1],
[0, 0, 0],
[1, 1, 1]
])
prewitt_x = np.rot90(prewitt_y) # rotates counter-clockwise
img_sx = signal.correlate(img, prewitt_x, mode="same")
img_sy = signal.correlate(img, prewitt_y, mode="same")
g_magnitude = np.sqrt(img_sx**2 + img_sy**2)
ground_truth = skifilters.prewitt(data.camera())
util.plot_images_grayscale(
[img, img_sx, img_sy, g_magnitude, ground_truth],
["Image", "Prewitt (x)", "Prewitt (y)", "Prewitt (both/magnitude)",
"Prewitt (Ground Truth)"]
)
def augment_image(self, image, i):
if i == 0:
return np.rot90(image)
elif i == 1:
return np.rot90(image,2)
elif i == 2:
return np.rot90(image,3)
elif i == 3:
return image
elif i == 4:
return np.fliplr(image)
elif i == 5:
return np.flipud(image)
elif i == 6:
return image.transpose(1,0,2)
elif i == 7:
return np.fliplr(np.rot90(image))
def augment_image(self, image, i):
if i == 0:
return np.rot90(image)
elif i == 1:
return np.rot90(image,2)
elif i == 2:
return np.rot90(image,3)
elif i == 3:
return image
elif i == 4:
return np.fliplr(image)
elif i == 5:
return np.flipud(image)
elif i == 6:
return image.transpose(1,0,2)
elif i == 7:
return np.fliplr(np.rot90(image))
def test_get_geo_fact():
res = np.array([0.017051023225738, 0.020779123804907, -0.11077204227395,
-0.081155809427821, -0.098900024313067, 0.527229048585517,
-0.124497144079623, -0.151717673241039, 0.808796206796408])
res2 = np.rot90(np.fliplr(res.reshape(3, -1))).ravel()
# EE, MM
ab = [11, 12, 13, 21, 22, 23, 31, 32, 33]
i = 0
for i in range(9):
out = utils.get_geo_fact(ab[i], 13.45, 23.8, 124.3, 5.3, False, False)
assert_allclose(out[0], res[i])
out = utils.get_geo_fact(ab[i], 13.45, 23.8, 124.3, 5.3, True, True)
assert_allclose(out[0], res[i])
i += 1
# ME, EM
ab = [14, 15, 16, 24, 25, 26, 34, 35, 36]
i = 0
for i in range(9):
out = utils.get_geo_fact(ab[i], 13.45, 23.8, 124.3, 5.3, False, True)
assert_allclose(out[0], res2[i])
out = utils.get_geo_fact(ab[i], 13.45, 23.8, 124.3, 5.3, True, False)
assert_allclose(out[0], res[i])
i += 1
def rotate_examples(X, y, files, extent, k=3):
m,n = np.shape(X)
augmentedX = np.ones(((k+1)*m,n))
augmentedy = np.squeeze(np.ones(((k+1)*m,)))
augmented_files = []
for i in range(m):
#print y[i]
print((k+1)*i)
augmentedX[(k+1)*i,:] *= X[i,:]
augmentedy[(k+1)*i] *= y[i]
#print augmentedy[(k+1)*i]
augmented_files.append(files[i])
for j in range(1,k+1):
print(((k+1)*i)+j)
rotatedX = np.rot90(np.reshape(X[i,:], (2*extent,2*extent), order="F"), j)
augmentedX[((k+1)*i)+j,:] *= np.ravel(rotatedX, order="F")
augmentedy[((k+1)*i)+j] *= y[i]
augmented_files.append(files[i])
#print augmentedX[:16,:2]
#print np.shape(augmentedX)
#print len(augmented_files)
return augmentedX, augmentedy, augmented_files
def rotate_examples(X, y, files, extent, k=3):
m,n = np.shape(X)
augmentedX = np.ones(((k+1)*m,n))
augmentedy = np.squeeze(np.ones(((k+1)*m,)))
augmented_files = []
for i in range(m):
#print y[i]
print (k+1)*i
augmentedX[(k+1)*i,:] *= X[i,:]
augmentedy[(k+1)*i] *= y[i]
#print augmentedy[(k+1)*i]
augmented_files.append(files[i])
for j in range(1,k+1):
print ((k+1)*i)+j
rotatedX = np.rot90(np.reshape(X[i,:], (2*extent,2*extent), order="F"), j)
augmentedX[((k+1)*i)+j,:] *= np.ravel(rotatedX, order="F")
augmentedy[((k+1)*i)+j] *= y[i]
augmented_files.append(files[i])
#print augmentedX[:16,:2]
#print np.shape(augmentedX)
#print len(augmented_files)
return augmentedX, augmentedy, augmented_files
def transform_to_2d(data, max_axis):
"""
Projects 3d data cube along one axis using maximum intensity with
preservation of the signs. Adapted from nilearn.
"""
import numpy as np
# get the shape of the array we are projecting to
new_shape = list(data.shape)
del new_shape[max_axis]
# generate a 3D indexing array that points to max abs value in the
# current projection
a1, a2 = np.indices(new_shape)
inds = [a1, a2]
inds.insert(max_axis, np.abs(data).argmax(axis=max_axis))
# take the values where the absolute value of the projection
# is the highest
maximum_intensity_data = data[inds]
return np.rot90(maximum_intensity_data)
def bp_sensitivity_map(self, sensitivity_array, activator):
expanded_array = self.expand_sensitivity_map(sensitivity_array)
expanded_width = expanded_array.shape[2]
zp = (self.input_width + self.filter_width - 1 - expanded_width) / 2
padded_array = padding(expanded_array, zp)
self.delta_array = self.create_delta_array()
for f in range(self.filter_number):
filter = self.filters[f]
flipped_weights = np.array(map(lambda i: np.rot90(i, 2), filter.get_weights()))
delta_array = self.create_delta_array()
for d in range(delta_array.shape[0]):
conv(padded_array[f], flipped_weights[d], delta_array[d], 1, 0)
self.delta_array += delta_array
derivative_array = np.array(self.input_array)
element_wise_op(derivative_array, activator.backward)
self.delta_array *= derivative_array
def makeImgPatchPrototype(D, compID):
''' Create image patch prototype for specific component
Returns
--------
Xprototype : sqrt(D) x sqrt(D) matrix
'''
# Create a "prototype" image patch of PxP pixels
P = np.sqrt(D)
Xprototype = np.zeros((P, P))
if compID % 4 == 0:
Xprototype[:P / 2] = 1.0
Xprototype = np.rot90(Xprototype, compID / 4)
if compID % 4 == 1:
Xprototype[np.tril_indices(P)] = 1
Xprototype = np.rot90(Xprototype, (compID - 1) / 4)
if compID % 4 == 2:
Xprototype[np.tril_indices(P, 2)] = 1
Xprototype = np.rot90(Xprototype, (compID - 2) / 4)
if compID % 4 == 3:
Xprototype[np.tril_indices(P, -2)] = 1
Xprototype = np.rot90(Xprototype, (compID - 3) / 4)
return Xprototype