gpt4 book ai didi

python - 加速 NumPy 中许多像素位置的线性插值

转载 作者:太空狗 更新时间:2023-10-29 18:07:20 25 4
gpt4 key购买 nike

我试图重现我的一个程序中的主要瓶颈。

我想得到 linearly (or rather bilinearly) interpolated几个非整数像素值同时的值。 不是每个像素坐标都以相同方式扰动的情况。下面是一个完整/最小的脚本以及演示问题的注释。如何加快 result 的计算速度?

import numpy as np
import time

im = np.random.rand(640,480,3) # my "image"
xx, yy = np.meshgrid(np.arange(im.shape[1]), np.arange(im.shape[0]))
print "Check these are the right indices:",np.sum(im - im[yy,xx,:])

# perturb the indices slightly
# I want to calculate the interpolated
# values of "im" at these locations
xx = xx + np.random.normal(size=im.shape[:2])
yy = yy + np.random.normal(size=im.shape[:2])

# integer value/pixel locations
x_0 = np.int_(np.modf(xx)[1])
y_0 = np.int_(np.modf(yy)[1])
x_1, y_1 = x_0 + 1, y_0 + 1

# the real-valued offsets/coefficients pixels
a = np.modf(xx)[0][:,:,np.newaxis]
b = np.modf(yy)[0][:,:,np.newaxis]

# make sure we don't go out of bounds at edge pixels
np.clip(x_0,0,im.shape[1]-1,out=x_0)
np.clip(x_1,0,im.shape[1]-1,out=x_1)
np.clip(y_0,0,im.shape[0]-1,out=y_0)
np.clip(y_1,0,im.shape[0]-1,out=y_1)

# now perform linear interpolation: THIS IS THE BOTTLENECK!
tic = time.time()
result = ((1-a) * (1-b) * im[y_0, x_0, :] +
a * (1-b) * im[y_1, x_0, :] +
(1-a) * b * im[y_0, x_1, :] +
a * b * im[y_1, x_1, :] )
toc = time.time()

print "interpolation time:",toc-tic

最佳答案

感谢@JoeKington 的建议。这是我使用 scipy.ndimage.map_coordinates

所能想到的最好结果
# rest as before
from scipy import ndimage
tic = time.time()
new_result = np.zeros(im.shape)
coords = np.array([yy,xx,np.zeros(im.shape[:2])])
for d in range(im.shape[2]):
new_result[:,:,d] = ndimage.map_coordinates(im,coords,order=1)
coords[2] += 1
toc = time.time()
print "interpolation time:",toc-tic

更新:添加了评论中建议的调整并尝试了一两件事。这是最快的版本:

tic = time.time()
new_result = np.zeros(im.shape)
coords = np.array([yy,xx])
for d in range(im.shape[2]):
ndimage.map_coordinates(im[:,:,d],
coords,order=1,
prefilter=False,
output=new_result[:,:,d] )
toc = time.time()

print "interpolation time:",toc-tic

示例运行时间:

 original version: 0.463063955307
better version: 0.204537153244
best version: 0.121845006943

关于python - 加速 NumPy 中许多像素位置的线性插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9416934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com