在Python中手动编写warpAffine代码

问题描述 投票:0回答:2

我想不使用库函数来实现仿射变换。 我有一个名为“transformed”的图像,我想应用逆变换来获取“img_org”图像。现在,我正在使用自己的基本 GetBilinearPixel 函数来设置强度值。但是,图像没有正确转换。这就是我想到的。 :

这是图像(“transformed.png”):

enter image description here

这是图片(“img_org.png”):

enter image description here

但我的目标是产生这样的图像: enter image description here

您可以在这里看到变换矩阵:

pts1 = np.float32( [[693,349] , [605,331] , [445,59]] )
pts2 = np.float32 ( [[1379,895] , [1213,970] ,[684,428]] )
Mat = cv2.getAffineTransform(pts2,pts1)
B=Mat

代码:

img_org=np.zeros(shape=(780,1050))
img_size=np.zeros(shape=(780,1050))

def GetBilinearPixel(imArr, posX, posY):
return imArr[posX][posY]

for i in range(1,img.shape[0]-1):
    for j in range(1,img.shape[1]-1):
        pos=np.array([[i],[j],[1]],np.float32)
        #print pos
        pos=np.matmul(B,pos)
        r=int(pos[0][0])
        c=int(pos[1][0])
        #print r,c
        if(c<=1024 and r<=768 and c>=0 and r>=0):
            img_size[r][c]=img_size[r][c]+1
            img_org[r][c] += GetBilinearPixel(img, i, j)

for i in range(0,img_org.shape[0]):
    for j in range(0,img_org.shape[1]):
        if(img_size[i][j]>0):
            img_org[i][j] = img_org[i][j]/img_size[i][j]

我的逻辑有问题吗?我知道我应用了非常低效的算法。 我是否缺少任何见解? 或者你能给我任何其他可以正常工作的算法吗?

(请求)。我不想使用 warpAffine 函数。

python image opencv image-processing opencv3.0
2个回答
5
投票

所以我对代码进行了向量化,并且该方法有效——我找不到您的实现的确切问题,但这也许会带来一些启发(而且速度更快)。

矢量化的设置是创建一个包含图像中每个点的线性(同质)数组。我们想要一个看起来像这样的数组

x0 x1 ... xN   x0 x1 ... xN   .....   x0 x1 ... xN
y0 y0 ... y0   y1 y1 ... y1   .....   yM yM ... yM
 1  1 ...  1    1  1 ...  1   .....    1  1 ...  1

这样每个点

(xi, yi, 1)
都包含在内。那么变换只是与变换矩阵和该数组的单个矩阵乘法。

为了简化问题(部分是因为你的图像命名约定让我感到困惑),我会说原始起始图像是“目的地”或

dst
,因为我们想转换回“源”或
src
图像。记住这一点,创建这个线性同质数组可能看起来像这样:

dst = cv2.imread('img.jpg', 0)
h, w = dst.shape[:2]
dst_y, dst_x = np.indices((h, w))  # similar to meshgrid/mgrid
dst_lin_homg_pts = np.stack((dst_x.ravel(), dst_y.ravel(), np.ones(dst_y.size)))

然后,要变换点,只需创建变换矩阵并相乘即可。我将对变换后的像素位置进行四舍五入,因为我将它们用作索引而不用担心插值:

src_pts = np.float32([[693, 349], [605, 331], [445, 59]])
dst_pts = np.float32([[1379, 895], [1213, 970], [684, 428]])
transf = cv2.getAffineTransform(dst_pts, src_pts)
src_lin_pts = np.round(transf.dot(dst_lin_homg_pts)).astype(int)

现在这个转换会将一些像素发送到负索引,如果我们用这些索引,它会环绕图像——可能不是我们想要做的。当然,在 OpenCV 实现中,它只是完全切断这些像素。但是我们可以移动所有变换后的像素,以便所有位置都是正的,并且我们不会切断任何位置(您当然可以在这方面做任何您想做的事情):

min_x, min_y = np.amin(src_lin_pts, axis=1)
src_lin_pts -= np.array([[min_x], [min_y]])

然后我们需要创建变换映射到的源图像

src
。我将使用灰色背景创建它,以便我们可以从
dst
图像中看到黑色的范围。

trans_max_x, trans_max_y = np.amax(src_lin_pts, axis=1)
src = np.ones((trans_max_y+1, trans_max_x+1), dtype=np.uint8)*127

现在我们要做的就是将目标图像中的一些相应像素放入源图像中。由于我没有切断任何像素,并且两个线性点数组中的像素数量相同,因此我可以将转换后的像素分配为原始图像中的颜色。

src[src_lin_pts[1], src_lin_pts[0]] = dst.ravel()

当然,现在这不是在图像上进行插值。但是 OpenCV 中没有用于插值的内置函数(有其他方法可以使用的后端 C 函数,但您不能在 Python 中访问)。但是,您有重要的部分——目标图像映射到原始图像的位置,因此您可以使用任意数量的库来插入到该网格上。或者自己实现线性插值,因为它并不太困难。当然,在此之前您可能需要取消弯曲的像素位置。

cv2.imshow('src', src)
cv2.waitKey()

Source image

编辑:同样的方法也适用于

warpPerspective
,尽管你得到的矩阵乘法将给出一个三行(同质)向量,并且你需要将前两行除以第三行以将它们设置回来进入笛卡尔世界。除此之外,其他一切都保持不变。


0
投票

我稍微改编了alkasm的答案,因为我有些错误。

我还更改了符号如下:

  • image1
    为仿射变换前的图像;
  • image2
    是仿射变换后的图像。
import cv2
import numpy as np
from arena import display_frame

def warp_affine(image1, transf, no_wrap=True):
    rows1, cols1 = np.indices(image1.shape[:2])
    pixels1 = np.vstack((
        cols1.ravel(),
        rows1.ravel(),
        np.ones(rows1.size, dtype=np.int64)
    ))
    pixels2 = np.round(transf.dot(pixels1)).astype(int)
    if no_wrap:
        min_col2, min_row2 = np.amin(pixels2, axis=1)
        pixels2 -= np.array([[min_col2], [min_row2]])
    max_col2, max_row2 = np.amax(pixels2, axis=1) + 1
    image2 = np.ones(
        (max_row2, max_col2, image1.shape[2]),
        dtype=np.uint8
    )
    image2 *= 127
    image2[pixels2[1], pixels2[0]] = image1[pixels1[1], pixels1[0]]
    return image2

def test_warp_affine():
    image1 = cv2.imread("image.jpg")
    points2 = np.float32([[693, 349], [605, 331], [445, 59]])
    points1 = np.float32([[1379, 895], [1213, 970], [684, 428]])
    transf = cv2.getAffineTransform(points1, points2)
    image2 = warp_affine(image1, transf)
    cv2.imshow(image2)

test_warp_affine()
© www.soinside.com 2019 - 2024. All rights reserved.