本文整理汇总了Python中skimage.transform.warp函数的典型用法代码示例。如果您正苦于以下问题:Python warp函数的具体用法?Python warp怎么用?Python warp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了warp函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: random_trans_single_output
def random_trans_single_output(pic_array):
# randomly transform the pic_array, which is a numpy nd array
# flipping
do_hori_flip = np.random.binomial(1, 0.5)
if do_hori_flip:
pic_array = np.fliplr(pic_array)
do_vert_flip = np.random.binomial(1, 0.5)
if do_vert_flip:
pic_array = np.flipud(pic_array)
# rotation
pic_array = rotate(pic_array, np.random.random_integers(0, 360),
mode='constant', cval=1)
# scaling
scale_ratio = log(np.random.uniform(2.5, 4.5))
afine_tf = tf.AffineTransform(scale=(scale_ratio, scale_ratio))
pic_array = tf.warp(pic_array, afine_tf, mode='constant', cval=1)
# translation
trans_length = np.random.random_integers(-6, 6, 2)
trans_length = (trans_length[0], trans_length[1])
afine_tf = tf.AffineTransform(translation=trans_length)
pic_array = tf.warp(pic_array, afine_tf, mode='constant', cval=1)
return pic_array
开发者ID:Chris19920210,项目名称:machine_learning,代码行数:27,代码来源:sample_enlarge.py
示例2: test
def test():
img = skimage.img_as_float(data.lena())
img_size = img.shape[:2]
trans = get_transform(20,15,1.05, 0.02, img_size)
img_transformed = transform.warp(img, trans)
obj_func = lambda x: transform_and_compare(img_transformed, img, x)
x0 = np.array([0,0,1, 0])
results = optimize.fmin_bfgs(obj_func, x0)
transform_estimated = get_simple_transform(results)
transform_optimal = transform.AffineTransform(np.linalg.inv(trans._matrix))
params_optimal = np.concatenate([transform_optimal.translation,
transform_optimal.scale[0:1],
[transform_optimal.rotation]])
img_registered = transform.warp(img_transformed,
transform_estimated)
err_original = mean_sq_diff(img_transformed, img)
err_optimal = transform_and_compare(img_transformed, img, params_optimal)
err_actual = transform_and_compare(img_transformed, img, results)
err_relative = err_optimal/err_original
print "Params optimal:", params_optimal
print "Params estimated:", results
print "Error without registration:", err_original
print "Error of optimal registration:", err_optimal
print "Error of estimated transformation %f (%.2f %% of intial)" % (err_actual,
err_relative*100.)
plt.figure()
plt.subplot(121)
plt.imshow(img_transformed)
plt.subplot(122)
plt.imshow(img_registered)
开发者ID:btel,项目名称:imageregistration,代码行数:34,代码来源:registration.py
示例3: random_translate_images
def random_translate_images(self, data, xtrans_r=None, ytrans_r=None):
if xtrans_r is None:
if self.xtrans_bound is None:
xtrans_r = [-5, 5]
else:
xtrans_r = self.xtrans_bound
if ytrans_r is None:
if self.ytrans_bound is None:
ytrans_r = [-5, 5]
else:
ytrans_r = self.ytrans_bound
if data.ndim == 3:
for i in xrange(data[0].shape[0]):
xtrans = self.rng.random_integers(xtrans_r[0], xtrans_r[1])
ytrans = self.rng.random_integers(ytrans_r[0], ytrans_r[1])
map_args = {
"xtranslate": xtrans,
"ytranslate": ytrans,
}
data[i] = st.warp(data, translate, map_args=map_args)
else:
xtrans = self.rng.random_integers(xtrans_r[0], xtrans_r[1])
ytrans = self.rng.random_integers(ytrans_r[0], ytrans_r[1])
map_args = {
"xtranslate": xtrans,
"ytranslate": ytrans,
}
data = st.warp(data, translate, map_args=map_args)
return data
开发者ID:caglar,项目名称:ift6266-project,代码行数:31,代码来源:rnd_transformations.py
示例4: gen_data
def gen_data(name):
reftracker = scio.loadmat('data/images_tracker.00047.mat')
desttracker = scio.loadmat('data/images_tracker/'+name+'.mat')
refpos = np.floor(np.mean(reftracker, 0))
xxc, yyc = np.meshgrid(np.arange(1, 1801, dtype=np.int), np.arange(1, 2001, dtype=np.int))
#normalize x and y channels
xxc = (xxc - 600 - refpos[0]) * 1.0 / 600
yyc = (yyc - 600 - refpos[1]) * 1.0 / 600
maskimg = Image.open('data/meanask.png')
maskc = np.array(maskimg, dtype=np.float)
maskc = np.pad(maskc, (600, 600), 'minimum')
tform = transform.ProjectiveTransform()
tform.estimate(reftracker + 600, desttracker + 600)
img_data = skio.imread('data/images_data/'+name+'.jpg')
# save org mat
warpedxx = transform.warp(img_data, tform, output_shape=xxc.shape)
warpedyy = transform.warp(img_data, tform, output_shape=xxc.shape)
warpedmask = transform.warp(img_data, tform, output_shape=xxc.shape)
warpedxx = warpedxx[600:1400, 600:1200, :]
warpedyy = warpedyy[600:1400, 600:1200, :]
warpedmask = warpedmask[600:1400, 600:1200, :]
img_h, img_w, _ = img_data.shape
mat = np.zeros((img_h, img_w, 6), dtype=np.float)
mat[:, :, 0] = (img_data[2] * 1.0 - 104.008) / 255
mat[:, :, 1] = (img_data[1] * 1.0 - 116.669) / 255
mat[:, :, 2] = (img_data[0] * 1.0 - 122.675) / 255
scio.savemat('portraitFCN_data/' + name + '.mat', {'img':mat})
mat_plus = np.zeros((img_h, img_w, 6), dtype=np.float)
mat_plus[:, :, 0:3] = mat
mat_plus[:, :, 3] = warpedxx
mat_plus[:, :, 4] = warpedyy
mat_plus[:, :, 5] = warpedmask
开发者ID:GirishaGarg,项目名称:AutoPortraitMatting,代码行数:33,代码来源:preprocess.py
示例5: generate_transformations
def generate_transformations(image, fileName):
MAX_IMAGE_PIXEL = 96
transformed_images = [image]
# ======================
# Scale 1 original image
# ======================
similarity_transform = SimilarityTransform(scale=0.75)
image_scaled = warp(image, similarity_transform, mode='wrap')
transformed_images.append(image_scaled)
# sc.misc.imsave(folder + '/' + fileName.split('.')[0] + '/' + fileName.split('.')[0] + '_scale1.jpg', image_scaled)
# ======================
# Scale 2 original image
# ======================
similarity_transform = SimilarityTransform(scale=1.25)
image_scaled = warp(image, similarity_transform, mode='wrap')
transformed_images.append(image_scaled)
# sc.misc.imsave(folder + '/' + fileName.split('.')[0] + '/' + fileName.split('.')[0] + '_scale2.jpg', image_scaled)
# =======================================
# Rotate image by intervals of 45 degrees
# =======================================
result = (generate_tranformations_for_rotated_image(image,fileName, degrees) for degrees in [45, 90, 135, 180, 225, 270, 315])
transformed_images.extend(flatten(result))
return transformed_images
开发者ID:Coderx7,项目名称:Apollo,代码行数:26,代码来源:predict_augmented.py
示例6: find_alpha
def find_alpha(base_img, img, model_robust):
# what type of interpolation
# 0: nearest-neighbor
# 1: bi-linear
warp_order = 1
output_shape, corner_min = find_output_shape(base_img, model_robust, channel)
#print("output_shape", output_shape, corner_min)
#print(model_robust.scale, model_robust.translation, model_robust.rotation)
# This in-plane offset is the only necessary transformation for the base image
offset = SimilarityTransform(translation= -corner_min)
base_warped = warp(base_img[:,:,channel], offset.inverse, order=warp_order,
output_shape = output_shape, cval=-1)
base_color = warp(base_img, offset.inverse, order=warp_order,
output_shape = output_shape, cval=-1)
# warp image corners to new position in mosaic
transform = (model_robust + offset).inverse
#img_warped = warp(img[:,:,channel], transform, order=warp_order,
# output_shape=output_shape, cval=-1)
img_color = warp(img, transform, order=warp_order,
output_shape=output_shape, cval=-1)
#base_mask = (base_warped != -1)
#base_warped[~base_mask] = 0
img_mask = (img_warped != -1)
#img_warped[~img_mask] = 0
#convert to rgb
base_alpha = add_alpha(base_color, base_mask)
img_alpha = np.dstack((img_color, img_mask))
#base_alpha = np.dstack((base_color, base_mask))
#plt.imsave(tmp_base, base_alpha )
#plt.imsave(tmp_img, img_alpha )
#cmd = [path_to_enblend, tmp_base, tmp_img, '-o', tmp_out]
#p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
#output, err = p.communicate(b"input data that is passed to subprocess' stdin")
#rc = p.returncode
# remove alpha channel
if os.path.exists(tmp_out):
out = imread(tmp_out)[:,:,:3]
else:
print("couldnt find out image")
print(rc, output, err)
plt.figure()
plt.imshow(base_alpha)
plt.figure()#
plt.imshow(img_alpha)
plt.show()
out = base_alpha[:,:,:3]
#if you don't have enblend, you can use one of these
#merged_img = simple_merge(base_warped, img_warped, base_mask, img_mask)
#merged_img = minimum_cost_merge(base_warped, img_warped, base_mask, img_mask)
#merged_edges = remove_empty_edges(merged_img)
return tmp_alpha
开发者ID:johannah,项目名称:iceview,代码行数:60,代码来源:mask.py
示例7: test_slow_warp_nonint_oshape
def test_slow_warp_nonint_oshape():
image = np.random.rand(5, 5)
assert_raises(ValueError, warp, image, lambda xy: xy,
output_shape=(13.1, 19.5))
warp(image, lambda xy: xy, output_shape=(13.0001, 19.9999))
开发者ID:benlongo,项目名称:scikit-image,代码行数:7,代码来源:test_warps.py
示例8: test_slow_warp_nonint_oshape
def test_slow_warp_nonint_oshape():
image = np.random.rand(5, 5)
with testing.raises(ValueError):
warp(image, lambda xy: xy,
output_shape=(13.1, 19.5))
warp(image, lambda xy: xy, output_shape=(13.0001, 19.9999))
开发者ID:Cadair,项目名称:scikit-image,代码行数:8,代码来源:test_warps.py
示例9: find_mask
def find_mask(base_name, base_img, img_name, img, model_robust, channel):
# what type of interpolation
# 0: nearest-neighbor
# 1: bi-linear
warp_order = 1
output_shape, corner_min = find_output_shape(base_img, model_robust, channel)
# This in-plane offset is the only necessary transformation for the base image
offset = SimilarityTransform(translation= -corner_min)
base_warped = warp(base_img[:,:,channel], offset.inverse, order=warp_order,
output_shape = output_shape, cval=-1)
base_color = warp(base_img, offset.inverse, order=warp_order,
output_shape = output_shape, cval=-1)
# warp image corners to new position in mosaic
transform = (model_robust + offset).inverse
img_warped = warp(img[:,:,channel], transform, order=warp_order,
output_shape=output_shape, cval=-1)
img_color = warp(img, transform, order=warp_order,
output_shape=output_shape, cval=-1)
base_mask = (base_warped != -1)
base_warped[~base_mask] = 0
img_mask = (img_warped != -1)
img_warped[~img_mask] = 0
plt.imsave("img_mask.jpg", img_mask)
#convert to rgb
img_alpha = np.dstack((img_color, img_mask))
base_alpha = np.dstack((base_color, base_mask))
td = config.tmp_dir
tmp_base = os.path.join(td, 'tmp_' + '.'.join(base_name.split('.')[:-1]) + '.png')
tmp_img = os.path.join(td, 'tmp_' + '.'.join(img_name.split('.')[:-1]) + '.png')
tmp_out = os.path.join(td, 'tmp_out_' + '.'.join(base_name.split('.')[:-1]) + '.png')
plt.imsave(tmp_base, base_alpha)
plt.imsave(tmp_img, img_alpha)
cmd = ['enblend', tmp_base, tmp_img, '-o', tmp_out]
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode
#if you don't have enblend, you can use one of these
#merged_img = simple_merge(base_warped, img_warped, base_mask, img_mask)
#merged_img = minimum_cost_merge(base_warped, img_warped, base_mask, img_mask)
#merged_edges = remove_empty_edges(merged_img)
# remove alpha channel
if os.path.exists(tmp_out):
out = imread(tmp_out)
oute = remove_empty_alpha(out)
os.remove(tmp_base)
os.remove(tmp_img)
os.remove(tmp_out)
return oute[:,:,:3]
else:
print("Could not find out", tmp_out, rc)
raise Exception("failed cmd %s" %cmd)
开发者ID:johannah,项目名称:iceview,代码行数:58,代码来源:mask.py
示例10: test_warp_clip
def test_warp_clip():
x = 2 * np.ones((5, 5), dtype=np.double)
matrix = np.eye(3)
outx = warp(x, matrix, order=0, clip=False)
assert_array_almost_equal(x, outx)
outx = warp(x, matrix, order=0, clip=True)
assert_array_almost_equal(x / 2, outx)
开发者ID:Rapternmn,项目名称:scikit-image,代码行数:9,代码来源:test_warps.py
示例11: test_warp_tform
def test_warp_tform():
x = np.zeros((5, 5), dtype=np.double)
x[2, 2] = 1
theta = - np.pi / 2
tform = SimilarityTransform(scale=1, rotation=theta, translation=(0, 4))
x90 = warp(x, tform, order=1)
assert_almost_equal(x90, np.rot90(x))
x90 = warp(x, tform.inverse, order=1)
assert_almost_equal(x90, np.rot90(x))
开发者ID:andreydung,项目名称:scikit-image,代码行数:11,代码来源:test_warps.py
示例12: translate_images
def translate_images(self, data, xtrans=0, ytrans=0):
map_args = {
"xtrans": xtrans,
"ytrans": ytrans,
}
if data.ndim == 3:
for i in xrange(data[0].shape[0]):
data[i] = st.warp(data, translate, map_args=map_args)
else:
data = st.warp(data, translate, map_args=map_args)
return data
开发者ID:caglar,项目名称:ift6266-project,代码行数:11,代码来源:rnd_transformations.py
示例13: align_stack
def align_stack(im, alignNs=r_[0:100], print_status=True, do_plot=False):
"""Realign a stack to an image -- default to mean image from near the start
Args:
im
alignNs: frameNs to average to give the alignment reference image
print_status: give updates for long calcs to terminal
do_plot: show a plot with alignment calculations
Returns:
aligned stack, same size as input stack, padded with zeros where shifted
"""
# run alignment calculations, saving result in a dataframe
aligntarg = im[:100,:,:].mean(axis=0)
tL = []
nfrdo = im.shape[0]
if print_status: print('Computing offsets ({} frames)... '.format(nfrdo), end='')
for iF in range(nfrdo):
tL.append(feature.register_translation(aligntarg, im[iF,:,:]))
regDf = pd.DataFrame(tL, columns=('coords','err','phasediff'))
regDf['row'] = [x[0][0] for x in tL]
regDf['col'] = [x[0][1] for x in tL]
if do_plot:
gs = mpl.gridspec.GridSpec(2,2)
fig = plt.figure()
plt.subplot(gs[0,0])
plt.plot(regDf.err)
plt.title('translation-independent error')
plt.ylabel('RMS error')
plt.subplot(gs[0,1])
plt.plot(regDf.col)
plt.plot(regDf.row)
plt.title('row and col pixel offsets')
plt.legend(['col','row'])
# do the shifts
regim = im.copy()*0
maxv = im.max()
if print_status: print('Aligning frames... ', end='')
for iF in range(nfrdo): #debug range(nframes):
regim[iF,:,:] = transform.warp(im[iF,:,:]*1.0/maxv, \
transform.SimilarityTransform(translation=(-1*regDf.col[iF],-regDf.row[iF]))) * maxv
t = transform.warp(im[iF,:,:]*1.0/maxv, \
transform.SimilarityTransform(translation=(-1*regDf.col[iF],-regDf.row[iF]))) * maxv
if print_status and iF % 500 == 0:
print('%d (%d,%d)'%(iF,-regDf.col[iF],-regDf.row[iF]), end=' ')
if print_status: print('Done.')
return regim
开发者ID:histed,项目名称:PyToolsMH,代码行数:53,代码来源:image.py
示例14: test_warp
def test_warp():
x = np.zeros((5, 5), dtype=np.uint8)
x[2, 2] = 255
x = img_as_float(x)
theta = - np.pi / 2
tform = SimilarityTransform(scale=1, rotation=theta, translation=(0, 4))
x90 = warp(x, tform, order=1)
assert_array_almost_equal(x90, np.rot90(x))
x90 = warp(x, tform.inverse, order=1)
assert_array_almost_equal(x90, np.rot90(x))
开发者ID:aeweiwi,项目名称:scikit-image,代码行数:12,代码来源:test_warps.py
示例15: test_warp_identity
def test_warp_identity():
img = img_as_float(rgb2gray(data.astronaut()))
assert len(img.shape) == 2
assert np.allclose(img, warp(img, AffineTransform(rotation=0)))
assert not np.allclose(img, warp(img, AffineTransform(rotation=0.1)))
rgb_img = np.transpose(np.asarray([img, np.zeros_like(img), img]),
(1, 2, 0))
warped_rgb_img = warp(rgb_img, AffineTransform(rotation=0.1))
assert np.allclose(rgb_img, warp(rgb_img, AffineTransform(rotation=0)))
assert not np.allclose(rgb_img, warped_rgb_img)
# assert no cross-talk between bands
assert np.all(0 == warped_rgb_img[:, :, 1])
开发者ID:andreydung,项目名称:scikit-image,代码行数:12,代码来源:test_warps.py
示例16: test_warp_identity
def test_warp_identity():
lena = img_as_float(rgb2gray(data.lena()))
assert len(lena.shape) == 2
assert np.allclose(lena, warp(lena, AffineTransform(rotation=0)))
assert not np.allclose(lena, warp(lena, AffineTransform(rotation=0.1)))
rgb_lena = np.transpose(np.asarray([lena, np.zeros_like(lena), lena]),
(1, 2, 0))
warped_rgb_lena = warp(rgb_lena, AffineTransform(rotation=0.1))
assert np.allclose(rgb_lena, warp(rgb_lena, AffineTransform(rotation=0)))
assert not np.allclose(rgb_lena, warped_rgb_lena)
# assert no cross-talk between bands
assert np.all(0 == warped_rgb_lena[:, :, 1])
开发者ID:aeweiwi,项目名称:scikit-image,代码行数:12,代码来源:test_warps.py
示例17: random_transformation
def random_transformation(img1, img2):
shape_x, shape_y = img1.shape
rot = (random.random() - 0.5) * math.pi / 4
trans_x = int((random.random() - 0.5) * shape_x / 8)
trans_y = int((random.random() - 0.5) * shape_y / 8)
scale = 1. / 1.1 + random.random() * (1.1 - 1. / 1.1)
pixel_scale = 1. / 1.1 + random.random() * (1.1 - 1. / 1.1)
trans = transform.SimilarityTransform(
scale=scale, rotation=rot, translation=(trans_x, trans_y))
return \
(pixel_scale * transform.warp(img1.astype(float), trans, mode='nearest')), \
(transform.warp(img2.astype(float), trans, mode='nearest'))
开发者ID:1nadequacy,项目名称:kaggle_ds2,代码行数:13,代码来源:create_db.py
示例18: test_warp_matrix
def test_warp_matrix():
x = np.zeros((5, 5), dtype=np.double)
x[2, 2] = 1
refx = np.zeros((5, 5), dtype=np.double)
refx[1, 1] = 1
matrix = np.array([[1, 0, 1], [0, 1, 1], [0, 0, 1]])
# _warp_fast
outx = warp(x, matrix, order=1)
assert_almost_equal(outx, refx)
# check for ndimage.map_coordinates
outx = warp(x, matrix, order=5)
开发者ID:andreydung,项目名称:scikit-image,代码行数:13,代码来源:test_warps.py
示例19: warp_image_by_corner_points_projection
def warp_image_by_corner_points_projection(corner_points, image):
"""Given corner points of a Sudoku, warps original selection to a square image.
:param corner_points:
:type: corner_points: list
:param image:
:type image:
:return:
:rtype:
"""
# Clarify by storing in named variables.
top_left, top_right, bottom_left, bottom_right = np.array(corner_points)
top_edge = np.linalg.norm(top_right - top_left)
bottom_edge = np.linalg.norm(bottom_right - bottom_left)
left_edge = np.linalg.norm(top_left - bottom_left)
right_edge = np.linalg.norm(top_right - bottom_right)
L = int(np.ceil(max([top_edge, bottom_edge, left_edge, right_edge])))
src = np.array([top_left, top_right, bottom_left, bottom_right])
dst = np.array([[0, 0], [L - 1, 0], [0, L - 1], [L - 1, L - 1]])
tr = ProjectiveTransform()
tr.estimate(dst, src)
warped_image = warp(image, tr, output_shape=(L, L))
out = resize(warped_image, (500, 500))
return out
开发者ID:Hu1-Li,项目名称:sudokuextract,代码行数:29,代码来源:geometry.py
示例20: run3
def run3(self):
""" Cette fonction test des alternatives à SIFT et ORB. Ne fonctionne pas."""
for x in xrange(len(self.stack)-1):
print('Traitement image ' + str(x+1))
im1,im2 = 255.*gaussian_filter(self.stack[x,...], sqrt(self.initial_sigma**2 - 0.25)), 255.*gaussian_filter(self.stack[x+1,...], sqrt(self.initial_sigma**2 - 0.25))
im1,im2 = enhance_contrast(normaliser(im1), square(3)), enhance_contrast(normaliser(im2), square(3))
im1, im2 = normaliser(im1), normaliser(im2)
b = cv2.BRISK()
#b.create("Feature2D.BRISK")
k1,d1 = b.detectAndCompute(im1,None)
k2,d2 = b.detectAndCompute(im2,None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING)
matches = bf.match(d1,d2)
g1,g2 = [],[]
for i in matches:
g1.append(k1[i.queryIdx].pt)
g2.append(k2[i.trainIdx].pt)
model, inliers = ransac((np.array(g1), np.array(g2)), AffineTransform, min_samples=3, residual_threshold=self.min_epsilon, max_trials=self.max_trials, stop_residuals_sum=self.min_inlier_ratio)
self.stack[x+1,...] = warp(self.stack[x+1,...], AffineTransform(rotation=model.rotation, translation=model.translation), output_shape=self.stack[x+1].shape)
self.stack = self.stack.astype(np.uint8)
开发者ID:atbd,项目名称:PythonUtile,代码行数:27,代码来源:align.py
注:本文中的skimage.transform.warp函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论