从头开始实现 cv2.warpPerspective()

Ale*_*roS 5 python opencv image-processing computer-vision homography

当我决定从头开始编码以更好地理解其管道时,我正在对 OpenCV 函数cv2.warpPerspective进行一些实验。尽管我(希望)遵循了每一个理论步骤,但似乎我仍然遗漏了一些东西,并且我正在努力理解什么。请你帮助我好吗?

SRC 图像(左)和 True DST 图像(右)

cv2.warpPerspective 的输出与真实 DST 重叠

# Invert the homography SRC->DST to DST->SRC
hinv = np.linalg.inv(h)
src = gray1
dst = np.zeros(gray2.shape)
h, w = src.shape

# Remap back and check the domain
for ox in range(h):
    for oy in range(w):

        # Backproject from DST to SRC
        xw, yw, w = hinv.dot(np.array([ox, oy, 1]).T)

        # cv2.INTER_NEAREST
        x, y = int(xw/w), int(yw/w)

        # Check if it falls in the src domain
        c1 = x >= 0 and y < h
        c2 = y >= 0 and y < w

        if c1 and c2:
            dst[x, y] = src[ox, oy]

cv2.imshow(dst + gray2//2)
Run Code Online (Sandbox Code Playgroud)

我的代码的输出

PS:输出图像是估计夏令时和真实夏令时的重叠,以更好地突出差异。

Chr*_*itz 3

你的问题相当于一个打字错误。您混淆了坐标的命名。单应性假定(x,y,1)顺序,这对应于(j,i,1)

只需(x, y, 1)在计算和(xw, yw, w)结果中使用(然后x,y = xw/w, yw/w)。当正确表述时,该w因素反映了数学。

避免索引到.shape. 指数不会“说话”。只需做(height, width) = src.shape[:2]并使用它们即可。

我建议修复命名方案,或在注释中将其定义在顶部。我建议坚持使用x,y而不是 i,j,u,v,然后用前缀/后缀扩展它们所在的空间(“src/dst/in/out”)。也许类似于ox,oy迭代,只是xw,yw,w为了单应性结果,它变成x,y通过除法,以及ix,iy整数化)用于输入中的采样?然后你可以使用dst[oy, ox] = src[iy, ix]