本文整理匯總了Python中numpy.dstack方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.dstack方法的具體用法?Python numpy.dstack怎麽用?Python numpy.dstack使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.dstack方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: merge
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def merge(self, tiles: List[np.ndarray], dtype=np.float32):
if len(tiles) != len(self.crops):
raise ValueError
channels = 1 if len(tiles[0].shape) == 2 else tiles[0].shape[2]
target_shape = self.image_height + self.margin_bottom + self.margin_top, self.image_width + self.margin_right + self.margin_left, channels
image = np.zeros(target_shape, dtype=np.float64)
norm_mask = np.zeros(target_shape, dtype=np.float64)
w = np.dstack([self.weight] * channels)
for tile, (x, y, tile_width, tile_height) in zip(tiles, self.crops):
# print(x, y, tile_width, tile_height, image.shape)
image[y:y + tile_height, x:x + tile_width] += tile * w
norm_mask[y:y + tile_height, x:x + tile_width] += w
# print(norm_mask.min(), norm_mask.max())
norm_mask = np.clip(norm_mask, a_min=np.finfo(norm_mask.dtype).eps, a_max=None)
normalized = np.divide(image, norm_mask).astype(dtype)
crop = self.crop_to_orignal_size(normalized)
return crop
示例2: mapping
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def mapping(img):
return 255.0 * (img - np.min(img)) / (np.max(img) - np.min(img))
# def read_data(path, batch_size):
# filenames = os.listdir(path)
# filenames_len = filenames.__len__()
# rand_select = np.random.randint(0, filenames_len, [batch_size])
# batch_data = np.zeros([batch_size, 256, 256, 3])
# for i in range(batch_size):
# img = np.array(Image.open(path + filenames[rand_select[i]]).resize([256, 256]))
# try:
# if img.shape.__len__() == 3:
# batch_data[i, :, :, :] = img[:256, :256, :3]
# else:
# batch_data[i, :, :, :] = np.dstack((img, img, img))[:256, :256, :]
# except:
# img = np.array(Image.open(path + filenames[0]))
# batch_data[i, :, :, :] = img[:256, :256, :3]
# return batch_data
示例3: train
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def train(self):
list = os.listdir(self.path)
nums_file = list.__len__()
saver = tf.train.Saver()
for i in range(10000):
rand_select = np.random.randint(0, nums_file, [self.batch_size])
INPUTS = np.zeros([self.batch_size, self.img_h, self.img_w, 3])
INPUTS_CONDITION = np.zeros([self.batch_size, self.img_h, self.img_w, 3])
for j in range(self.batch_size):
img = np.array(Image.open(self.path + list[rand_select[j]]))
img_h, img_w = img.shape[0], img.shape[1]
INPUT_CON = misc.imresize(img[:, :img_w//2], [self.img_h, self.img_w]) / 127.5 - 1.0
INPUTS_CONDITION[j] = np.dstack((INPUT_CON, INPUT_CON, INPUT_CON))
INPUT = misc.imresize(img[:, img_w//2:], [self.img_h, self.img_w]) / 127.5 - 1.0
INPUTS[j] = np.dstack((INPUT, INPUT, INPUT))
self.sess.run(self.opt_dis, feed_dict={self.inputs: INPUTS, self.inputs_condition: INPUTS_CONDITION})
self.sess.run(self.opt_gen, feed_dict={self.inputs: INPUTS, self.inputs_condition: INPUTS_CONDITION})
if i % 10 == 0:
[G_LOSS, D_LOSS] = self.sess.run([self.g_loss, self.d_loss], feed_dict={self.inputs: INPUTS, self.inputs_condition: INPUTS_CONDITION})
print("Iteration: %d, d_loss: %f, g_loss: %f"%(i, D_LOSS, G_LOSS))
if i % 100 == 0:
saver.save(self.sess, "./save_para//model.ckpt")
示例4: thin_plate_transform
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def thin_plate_transform(x,y,offw,offh,imshape,shift_l=-0.05,shift_r=0.05,num_points=5,offsetMatrix=False):
rand_p=np.random.choice(x.size,num_points,replace=False)
movingPoints=np.zeros((1,num_points,2),dtype='float32')
fixedPoints=np.zeros((1,num_points,2),dtype='float32')
movingPoints[:,:,0]=x[rand_p]
movingPoints[:,:,1]=y[rand_p]
fixedPoints[:,:,0]=movingPoints[:,:,0]+offw*(np.random.rand(num_points)*(shift_r-shift_l)+shift_l)
fixedPoints[:,:,1]=movingPoints[:,:,1]+offh*(np.random.rand(num_points)*(shift_r-shift_l)+shift_l)
tps=cv2.createThinPlateSplineShapeTransformer()
good_matches=[cv2.DMatch(i,i,0) for i in range(num_points)]
tps.estimateTransformation(movingPoints,fixedPoints,good_matches)
imh,imw=imshape
x,y=np.meshgrid(np.arange(imw),np.arange(imh))
x,y=x.astype('float32'),y.astype('float32')
newxy=tps.applyTransformation(np.dstack((x.ravel(),y.ravel())))[1]
newxy=newxy.reshape([imh,imw,2])
if offsetMatrix:
return newxy,newxy-np.dstack((x,y))
else:
return newxy
示例5: _GetTrainingInputsAndLabels
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def _GetTrainingInputsAndLabels(self, config):
"""Generates training inputs and labels.
Args:
config: Dictionary with config for this unit test.
Returns:
Tuple `(training_inputs, training_labels, raw_training_inputs)` where
`training_inputs` and `training_labels` are data for training and
`raw_training_inputs` are representation of training_inputs for
visualisation.
"""
raw_training_inputs = config["x_generator"](
num_points=config["num_training_records"],
lattice_sizes=config["lattice_sizes"])
if isinstance(raw_training_inputs, tuple):
# This means that raw inputs are 2-d mesh grid. Convert them into list of
# 2-d points.
training_inputs = list(np.dstack(raw_training_inputs).reshape((-1, 2)))
else:
training_inputs = raw_training_inputs
training_labels = [config["y_function"](x) for x in training_inputs]
return training_inputs, training_labels, raw_training_inputs
示例6: color_grid_thresh
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def color_grid_thresh(img, s_thresh=(170,255), sx_thresh=(20, 100)):
img = np.copy(img)
# Convert to HLS color space and separate the V channel
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
l_channel = hls[:,:,1]
s_channel = hls[:,:,2]
# Sobel x
sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivateive in x
abs_sobelx = np.absolute(sobelx) # Absolute x derivateive to accentuate lines
scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))
# Threshold x gradient
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1
# Threshold color channel
s_binary = np.zeros_like(s_channel)
s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1
# combine the two binary
binary = sxbinary | s_binary
# Stack each channel (for visual check the pixal sourse)
# color_binary = np.dstack((np.zeros_like(sxbinary), sxbinary,s_binary)) * 255
return binary
示例7: draw_lane_fit
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def draw_lane_fit(undist, warped ,Minv, left_fitx, right_fitx, ploty):
# Drawing
# Create an image to draw the lines on
warp_zero = np.zeros_like(warped).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# Recast the x and y points into usable format for cv2.fillPoly()
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image
cv2.fillPoly(color_warp, np.int_([pts]), (0,255,0))
# Warp the blank back to original image space using inverse perspective matrix(Minv)
newwarp = cv2.warpPerspective(color_warp, Minv, (undist.shape[1], undist.shape[0]))
# Combine the result with the original image
result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)
return result
示例8: _symmetrize_correlograms
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def _symmetrize_correlograms(correlograms):
"""Return the symmetrized version of the CCG arrays."""
n_clusters, _, n_bins = correlograms.shape
assert n_clusters == _
# We symmetrize c[i, j, 0].
# This is necessary because the algorithm in correlograms()
# is sensitive to the order of identical spikes.
correlograms[..., 0] = np.maximum(
correlograms[..., 0], correlograms[..., 0].T)
sym = correlograms[..., 1:][..., ::-1]
sym = np.transpose(sym, (1, 0, 2))
return np.dstack((sym, correlograms))
示例9: test_concat
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def test_concat(make_data):
"""Test concatenation layer."""
x, _, X = make_data
# This replicates the input layer behaviour
f = ab.InputLayer('X', n_samples=3)
g = ab.InputLayer('Y', n_samples=3)
catlayer = ab.Concat(f, g)
F, KL = catlayer(X=x, Y=x)
tc = tf.test.TestCase()
with tc.test_session():
forked = F.eval()
orig = X.eval()
assert forked.shape == orig.shape[0:2] + (2 * orig.shape[2],)
assert np.all(forked == np.dstack((orig, orig)))
assert KL.eval() == 0.0
示例10: plot_cost_to_go_mountain_car
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def plot_cost_to_go_mountain_car(env, estimator, num_tiles=20):
x = np.linspace(env.observation_space.low[0], env.observation_space.high[0], num=num_tiles)
y = np.linspace(env.observation_space.low[1], env.observation_space.high[1], num=num_tiles)
X, Y = np.meshgrid(x, y)
Z = np.apply_along_axis(lambda _: -np.max(estimator.predict(_)), 2, np.dstack([X, Y]))
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
cmap=matplotlib.cm.coolwarm, vmin=-1.0, vmax=1.0)
ax.set_xlabel('Position')
ax.set_ylabel('Velocity')
ax.set_zlabel('Value')
ax.set_title("Mountain \"Cost To Go\" Function")
fig.colorbar(surf)
plt.show()
示例11: testDStackExecution
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def testDStackExecution(self):
a_data = np.random.rand(10)
b_data = np.random.rand(10)
a = tensor(a_data, chunk_size=4)
b = tensor(b_data, chunk_size=4)
c = dstack([a, b])
res = self.executor.execute_tensor(c, concat=True)[0]
expected = np.dstack([a_data, b_data])
self.assertTrue(np.array_equal(res, expected))
a_data = np.random.rand(10, 20)
b_data = np.random.rand(10, 20)
a = tensor(a_data, chunk_size=3)
b = tensor(b_data, chunk_size=4)
c = dstack([a, b])
res = self.executor.execute_tensor(c, concat=True)[0]
expected = np.dstack([a_data, b_data])
self.assertTrue(np.array_equal(res, expected))
示例12: depth_im_to_dist_im
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def depth_im_to_dist_im(depth_im, K):
"""Converts a depth image to a distance image.
:param depth_im: hxw ndarray with the input depth image, where depth_im[y, x]
is the Z coordinate of the 3D point [X, Y, Z] that projects to pixel [x, y],
or 0 if there is no such 3D point (this is a typical output of the
Kinect-like sensors).
:param K: 3x3 ndarray with an intrinsic camera matrix.
:return: hxw ndarray with the distance image, where dist_im[y, x] is the
distance from the camera center to the 3D point [X, Y, Z] that projects to
pixel [x, y], or 0 if there is no such 3D point.
"""
xs, ys = np.meshgrid(
np.arange(depth_im.shape[1]), np.arange(depth_im.shape[0]))
Xs = np.multiply(xs - K[0, 2], depth_im) * (1.0 / K[0, 0])
Ys = np.multiply(ys - K[1, 2], depth_im) * (1.0 / K[1, 1])
dist_im = np.sqrt(
Xs.astype(np.float64)**2 +
Ys.astype(np.float64)**2 +
depth_im.astype(np.float64)**2)
# dist_im = np.linalg.norm(np.dstack((Xs, Ys, depth_im)), axis=2) # Slower.
return dist_im
示例13: compute_history_3d
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def compute_history_3d(self, pos_history):
"""Compute a 3D position matrix
The first two columns are the 2D position in the x and y axes
respectively, while the third column is the fitness on that given
position.
Parameters
----------
pos_history : numpy.ndarray
Two-dimensional position matrix history of shape
:code:`(iterations, n_particles, 2)`
Returns
-------
numpy.ndarray
3D position matrix of shape :code:`(iterations, n_particles, 3)`
"""
fitness = np.array(list(map(self.func, pos_history)))
return np.dstack((pos_history, fitness))
示例14: test_luminance
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def test_luminance():
source = sn.load('tests/sobel_input.png')[:,:,:3]
L = rgb2gray(source)
skresult = np.dstack([L, L, L])
small_skresult = sn.resize(skresult, width=256)
L = sn.rgb_to_luminance(source)
snresult = np.dstack([L, L, L])
small_snresult = sn.resize(snresult, width=256)
L = skimage_sobel(source)
sksobel = np.dstack([L, L, L])
small_sksobel = sn.resize(sksobel, width=256)
L = sn.rgb_to_luminance(source)
L = sn.compute_sobel(L)
snsobel = np.dstack([L, L, L])
small_snsobel = sn.resize(snsobel, width=256)
sn.show(np.hstack([
small_skresult,
small_snresult,
small_sksobel,
small_snsobel]))
示例15: elastic_transform
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import dstack [as 別名]
def elastic_transform(image,elastic_value_x ,elastic_value_y):
"""Elastic deformation of images as described in [Simard2003]_ (with modifications JUST in Y-DIRECTION).
.. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for
Convolutional Neural Networks applied to Visual Document Analysis", in
Proc. of the International Conference on Document Analysis and
Recognition, 2003.
Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5
"""
shape = image.shape
random_state = np.random.RandomState(None)
nY = shape[0] // 25
nX = shape[1] // 25
sigma = min(shape[1], shape[0]) * 0.0025
alpha_X = elastic_value_x * min(shape[0], shape[1])
alpha_Y = elastic_value_y * min(shape[0], shape[1])
dx = gaussian_filter((random_state.rand(nY, nX) * 2 - 1), sigma)
dy = gaussian_filter((random_state.rand(nY, nX) * 2 - 1), sigma)
x, y, z = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]), np.arange(shape[2]))
dx = misc.imresize(dx, [shape[0], shape[1]], interp='bicubic')
dy = misc.imresize(dy, [shape[0], shape[1]], interp='bicubic')
# plt.imshow(dx, cmap=plt.cm.gray)
# plt.show()
dxT = []
dyT = []
for dummy in range(shape[2]):
dxT.append(dx)
dyT.append(dy)
dx = np.dstack(dxT)
dy = np.dstack(dyT)
dx = dx * alpha_X
dy = dy * alpha_Y
indices = np.reshape(y + dy, (-1, 1)), np.reshape(x + dx, (-1, 1)), np.reshape(z, (-1, 1))
image = map_coordinates(image, indices, order=1).reshape(shape)
return image