【问题标题】:Vectorize Image Projection with Numpy使用 Numpy 向量化图像投影
【发布时间】:2022-10-05 04:48:25
【问题描述】:

为了提高效率,我想使用 numpy 对以下内容进行矢量化,但我发现很难考虑,我不知道如何开始。

import numpy as np

imageA = np.random.randint(10, size=(4, 5)) # Some image
imageB = np.random.randint(10, size=(4, 5)) # Some other image
transformation = np.random.randint(10, size=(3, 3)) # Some transformation matrix

out_image = imageB.copy()
for y in range(imageB.shape[0]):
    for x in range(imageB.shape[1]):
        u, v, w = transformation @ np.array([x, y, 1])
        x_p, y_p = u/w, v/w

        if x_p >= 0 and x_p < imageA.shape[1] and y_p >= 0 and y_p < imageA.shape[0]:
            out_image[y, x] = imageA[int(y_p), int(x_p)]

【问题讨论】:

标签: python numpy vectorization projection


【解决方案1】:

虽然不完整,但我能够在这方面取得一些进展。对我帮助最大的是熟悉 numpy 的 broadcasting 规则,它指定了这些操作的维度必须如何匹配。如果有人有任何提示或改进,我很想听听。

import numpy as np

imageA = np.random.randint(10, size=(4, 5)) # Some image
imageB = np.random.randint(10, size=(4, 5)) # Some other image
transformation = np.random.randint(10, size=(3, 3)) # Some transformation matrix

# Create matrix of indexes
x, y = np.meshgrid(np.arange(imageB.shape[1]), np.arange(imageB.shape[0]), indexing='xy')
indexes = np.append(x[:,:, np.newaxis], y[:, :, np.newaxis], axis=2)

# Create homogeneous x, y coordinates
trans_indexes = np.append(indexes, np.ones((indexes.shape[0], indexes.shape[1], 1)), axis=2)

# Transform homogeneous coordinates
uvw = np.matmul(transformation, trans_indexes[:, :, :, np.newaxis]).reshape(trans_indexes.shape)
uv = uvw[:, :, :2] / uvw[:, :, 2, np.newaxis]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    相关资源
    最近更新 更多