簡體   English   中英

插值給定索引python的圖像

[英]Interpolate Image for given indices python

我有一個大約8000x9000大小的圖像作為一個numpy矩陣。 我還有一個numpy 2xn矩陣中的索引列表。 這些指數是分數的,也可能超出圖像大小。 我需要插入圖像並找到給定索引的值。 如果索引落在外面,我需要為它們返回numpy.nan 目前我正在進行for循環,如下所示

def interpolate_image(image: numpy.ndarray, indices: numpy.ndarray) -> numpy.ndarray:
    """

    :param image:
    :param indices: 2xN matrix. 1st row is dim1 (rows) indices, 2nd row is dim2 (cols) indices
    :return:
    """
    # Todo: Vectorize this
    M, N = image.shape
    num_indices = indices.shape[1]
    interpolated_image = numpy.zeros((1, num_indices))
    for i in range(num_indices):
        x, y = indices[:, i]
        if (x < 0 or x > M - 1) or (y < 0 or y > N - 1):
            interpolated_image[0, i] = numpy.nan
        else:
            # Todo: Do Bilinear Interpolation. For now nearest neighbor is implemented
            interpolated_image[0, i] = image[int(round(x)), int(round(y))]
    return interpolated_image

但for循環需要花費大量時間(如預期的那樣)。 我該如何對此進行矢量化? 我找到了scipy.interpolate.interp2d ,但我無法使用它。 有人可以解釋如何使用這個或任何其他方法也沒關系。 我也發現了這一點 ,但又不是根據我的要求。 給定x和y索引,這些生成內插矩陣。 我不希望這樣。 對於給定的索引,我只想要插值,即我需要一個矢量輸出。 不是矩陣。

我試過這樣,但如上所述,它給出了一個矩陣輸出

f = interpolate.interp2d(numpy.arange(image.shape[0]), numpy.arange(image.shape[1]), image, kind='linear')
interp_image_vect = f(indices[:,0], indices[:,1])
RuntimeError: Cannot produce output of size 73156608x73156608 (size too large)

現在,我已經實現了最近鄰插值。 scipy interp2d沒有最近鄰居。 如果庫作為最近鄰居(這樣我可以比較)會很好。 如果沒有,那么也沒關系。

它看起來像scipy.interpolate.RectBivariateSpline將做的伎倆:

from scipy.interpolate import RectBivariateSpline
image = # as given
indices = # as given

spline = RectBivariateSpline(numpy.arange(M), numpy.arange(N), image)

interpolated = spline(indices[0], indices[1], grid=False)

這可以讓你的插值,但它不會給你nan ,你需要它。 你可以where得到:

nans = numpy.zeros(interpolated.shape) + numpy.nan
x_in_bounds = (0 <= indices[0]) & (indices[0] < M)
y_in_bounds = (0 <= indices[1]) & (indices[1] < N)
bounded = numpy.where(x_in_bounds & y_in_bounds, interpolated, nans)

我用2624x2624圖像測試了這一點,並且在indices測試了100,000點,所有這些都告訴它需要不到一秒鍾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM