本文整理汇总了Python中numpy.flip方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.flip方法的具体用法?Python numpy.flip怎么用?Python numpy.flip使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.flip方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: randomized_argsort
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def randomized_argsort(A, method="numpy", order='ascending'):
if method == "numpy":
P = np.random.permutation(len(A))
I = np.argsort(A[P], kind='quicksort')
I = P[I]
elif method == "quicksort":
I = quicksort(A)
else:
raise Exception("Randomized sort method not known.")
if order == 'ascending':
return I
elif order == 'descending':
return np.flip(I, axis=0)
else:
raise Exception("Unknown sorting order: ascending or descending.")
示例2: BuildAdjacency
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def BuildAdjacency(CMat, K):
CMat = CMat.astype(float)
CKSym = None
N, _ = CMat.shape
CAbs = np.absolute(CMat).astype(float)
for i in range(0, N):
c = CAbs[:, i]
PInd = np.flip(np.argsort(c), 0)
CAbs[:, i] = CAbs[:, i] / float(np.absolute(c[PInd[0]]))
CSym = np.add(CAbs, CAbs.T).astype(float)
if K != 0:
Ind = np.flip(np.argsort(CSym, axis=0), 0)
CK = np.zeros([N, N]).astype(float)
for i in range(0, N):
for j in range(0, K):
CK[Ind[j, i], i] = CSym[Ind[j, i], i] / float(np.absolute(CSym[Ind[0, i], i]))
CKSym = np.add(CK, CK.T)
else:
CKSym = CSym
return CKSym
示例3: equirect_facetype
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def equirect_facetype(h, w):
'''
0F 1R 2B 3L 4U 5D
'''
tp = np.roll(np.arange(4).repeat(w // 4)[None, :].repeat(h, 0), 3 * w // 8, 1)
# Prepare ceil mask
mask = np.zeros((h, w // 4), np.bool)
idx = np.linspace(-np.pi, np.pi, w // 4) / 4
idx = h // 2 - np.round(np.arctan(np.cos(idx)) * h / np.pi).astype(int)
for i, j in enumerate(idx):
mask[:j, i] = 1
mask = np.roll(np.concatenate([mask] * 4, 1), 3 * w // 8, 1)
tp[mask] = 4
tp[np.flip(mask, 0)] = 5
return tp.astype(np.int32)
示例4: time_align_visualize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def time_align_visualize(alignments, time, y, namespace='time_align'):
plt.figure()
heat = np.flip(alignments + alignments.T +
np.eye(alignments.shape[0]), axis=0)
sns.heatmap(heat, cmap="YlGnBu", vmin=0, vmax=1)
plt.savefig(namespace + '_heatmap.svg')
G = nx.from_numpy_matrix(alignments)
G = nx.maximum_spanning_tree(G)
pos = {}
for i in range(len(G.nodes)):
pos[i] = np.array([time[i], y[i]])
mst_edges = set(nx.maximum_spanning_tree(G).edges())
weights = [ G[u][v]['weight'] if (not (u, v) in mst_edges) else 8
for u, v in G.edges() ]
plt.figure()
nx.draw(G, pos, edges=G.edges(), width=10)
plt.ylim([-1, 1])
plt.savefig(namespace + '.svg')
示例5: draw_outputs
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def draw_outputs(img, outputs, class_names=None):
boxes, objectness, classes = outputs
#boxes, objectness, classes = boxes[0], objectness[0], classes[0]
wh = np.flip(img.shape[0:2])
if img.ndim == 2 or img.shape[2] == 1:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
min_wh = np.amin(wh)
if min_wh <= 100:
font_size = 0.5
else:
font_size = 1
for i in range(classes.shape[0]):
x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
img = cv2.putText(img, '{}'.format(int(classes[i])), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
(0, 0, 255), 1)
return img
示例6: draw_labels
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def draw_labels(x, y, class_names=None):
img = x.numpy()
if img.ndim == 2 or img.shape[2] == 1:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
boxes, classes = tf.split(y, (4, 1), axis=-1)
classes = classes[..., 0]
wh = np.flip(img.shape[0:2])
min_wh = np.amin(wh)
if min_wh <= 100:
font_size = 0.5
else:
font_size = 1
for i in range(len(boxes)):
x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
if class_names:
img = cv2.putText(img, class_names[classes[i]], x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
(0, 0, 255), 1)
else:
img = cv2.putText(img, str(classes[i]), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
return img
示例7: augment_undo
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def augment_undo(x_imgs_augmented, aug_type):
x_imgs_augmented = x_imgs_augmented.cpu().numpy()
sz = x_imgs_augmented.shape[0] // len(aug_type)
x_imgs = []
for i, aug in enumerate(aug_type):
x_img = x_imgs_augmented[i*sz : (i+1)*sz]
if aug == 'flip':
x_imgs.append(np.flip(x_img, axis=-1))
elif aug.startswith('rotate'):
shift = int(aug.split()[-1])
x_imgs.append(np.roll(x_img, -shift, axis=-1))
elif aug == '':
x_imgs.append(x_img)
else:
raise NotImplementedError()
return np.array(x_imgs)
示例8: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def __init__(self, root_dir,
flip=False, rotate=False, gamma=False, stretch=False,
p_base=0.96, max_stretch=2.0,
normcor=False, return_cor=False, return_path=False):
self.img_dir = os.path.join(root_dir, 'img')
self.cor_dir = os.path.join(root_dir, 'label_cor')
self.img_fnames = sorted([
fname for fname in os.listdir(self.img_dir)
if fname.endswith('.jpg') or fname.endswith('.png')
])
self.txt_fnames = ['%s.txt' % fname[:-4] for fname in self.img_fnames]
self.flip = flip
self.rotate = rotate
self.gamma = gamma
self.stretch = stretch
self.p_base = p_base
self.max_stretch = max_stretch
self.normcor = normcor
self.return_cor = return_cor
self.return_path = return_path
self._check_dataset()
示例9: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def __init__(self, steps = 1, lr = 0.0001, decay = 0.00001, silent = True):
self.GAN = GAN(steps = steps, lr = lr, decay = decay)
self.DisModel = self.GAN.DisModel()
self.AdModel = self.GAN.AdModel()
self.lastblip = time.clock()
self.noise_level = 0
self.im = dataGenerator(directory, suffix = suff, flip = True)
self.silent = silent
#Train Generator to be in the middle, not all the way at real. Apparently works better??
self.ones = np.ones((BATCH_SIZE, 1), dtype=np.float32)
self.zeros = np.zeros((BATCH_SIZE, 1), dtype=np.float32)
self.nones = -self.ones
示例10: test_multiple_axes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def test_multiple_axes(self):
a = np.array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
assert_equal(np.flip(a, axis=()), a)
b = np.array([[[5, 4],
[7, 6]],
[[1, 0],
[3, 2]]])
assert_equal(np.flip(a, axis=(0, 2)), b)
c = np.array([[[3, 2],
[1, 0]],
[[7, 6],
[5, 4]]])
assert_equal(np.flip(a, axis=(1, 2)), c)
示例11: crop
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def crop(img, crop_size, crop_loc=4, crop_grid=(3, 3)):
if isinstance(crop_loc, list):
imgs = np.zeros((img.shape[0], len(crop_loc), crop_size, crop_size, 3),
np.float32)
for (i, loc) in enumerate(crop_loc):
r, c = crop_idx(img.shape[1:3], crop_size, loc, crop_grid)
imgs[:, i] = img[:, r:r+crop_size, c:c+crop_size, :]
return imgs
elif crop_loc == np.prod(crop_grid) + 1:
imgs = np.zeros((img.shape[0], crop_loc, crop_size, crop_size, 3),
np.float32)
r, c = crop_idx(img.shape[1:3], crop_size, 4, crop_grid)
imgs[:, 0] = img[:, r:r+crop_size, c:c+crop_size, :]
imgs[:, 1] = img[:, 0:crop_size, 0:crop_size, :]
imgs[:, 2] = img[:, 0:crop_size, -crop_size:, :]
imgs[:, 3] = img[:, -crop_size:, 0:crop_size, :]
imgs[:, 4] = img[:, -crop_size:, -crop_size:, :]
imgs[:, 5:] = np.flip(imgs[:, :5], axis=3)
return imgs
else:
r, c = crop_idx(img.shape[1:3], crop_size, crop_loc, crop_grid)
return img[:, r:r+crop_size, c:c+crop_size, :]
示例12: select
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def select(self):
"""
This method selects the best arm chosen by Thompsom Sampling.
:return: Return selected arm number.
Arm number returned is (n_arm - 1).
Returns a list of arms by importance.
The chosen arm is the index 0 of this list.
"""
rewards_0 = self.n_impressions - self.n_rewards
rewards_0[rewards_0 <= 0] = 1
theta_value = np.random.beta(self.n_rewards, rewards_0)
ranked_arms = np.flip(np.argsort(theta_value), axis=0)
chosen_arm = ranked_arms[0]
self.n_impressions[chosen_arm] += 1
return chosen_arm, ranked_arms
示例13: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def __init__(self, folder, im_size, mss = (1024 ** 3), flip = True, verbose = True):
self.folder = folder
self.im_size = im_size
self.segment_length = mss // (im_size * im_size * 3)
self.flip = flip
self.verbose = verbose
self.segments = []
self.images = []
self.update = 0
if self.verbose:
print("Importing images...")
print("Maximum Segment Size: ", self.segment_length)
try:
os.mkdir("data/" + self.folder + "-npy-" + str(self.im_size))
except:
self.load_from_npy(folder)
return
self.folder_to_npy(self.folder)
self.load_from_npy(self.folder)
示例14: get_batch
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def get_batch(self, num):
if self.update > self.images.shape[0]:
self.load_from_npy(self.folder)
self.update = self.update + num
idx = np.random.randint(0, self.images.shape[0] - 1, num)
out = []
for i in idx:
out.append(self.images[i])
if self.flip and random.random() < 0.5:
out[-1] = np.flip(out[-1], 1)
return np.array(out).astype('float32') / 255.0
示例15: show_2d
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flip [as 别名]
def show_2d(array_2d, title="weights_layer", colormap=rainbow, flip=True):
#print("weights_layer.shape = ",weights_layer.shape)
if len(array_2d.shape) < 2:
return
img = np.clip(array_2d*255 ,-255,255).astype(np.uint8) # scale
if flip:
img = np.flip(np.transpose(img))
img = np.repeat(img[:,:,np.newaxis],3,axis=2) # add color channels
img = cv2.applyColorMap(img, colormap) # rainbow: blue=low, red=high
# see if it exists
new_window = not check_window_exists(title)
window = cv2.namedWindow(title,cv2.WINDOW_NORMAL)
cv2.imshow(title, img)
if new_window:
cv2.resizeWindow(title, img.shape[1], img.shape[0]) # show what we've got
#aspect = img.shape[0] / img.shape[1]
#if aspect > 3:
# cv2.resizeWindow(title, 200, 1024) # zoom in/out (can use two-finger-scroll to zoom in)
#print(f"size for {title} = 1024, {int(1024/aspect*img.shape[0])}")
#else:
# cv2.resizeWindow(title, int(imWidth/2),int(imWidth/2)) # zoom in/out (can use two-finger-scroll to zoom in)
# draw weights for all layers using model state dict