背景:我正在尝试将一张脸变形为另一张形状的脸。

为了使一个图像变形为另一个图像,我使用了面部轮廓的delaunay三角剖分,并将一个肖像的三角形扭曲为第二个肖像的相应三角形。我使用重心坐标系将三角形内的点映射到另一个三角形上其对应的变形位置。

我的第一种方法是用逆乘法解决系统Ax = b的问题,其中A由三角形的三个角组成,b代表当前点,x代表该点的重心坐标(alpha,beta和gamma )。我找到每个三角形一次的矩阵A的逆,然后通过找到A ^ -1与点b的点积,为该三角形内的每个点计算重心坐标。我发现这非常慢(该功能需要36秒才能完成)。

根据其他职位的建议,我尝试使用最小二乘解来提高此过程的效率。但是,当我使用numpy的lsq方法时,时间增加到了154秒。我认为这是由于以下事实:每次运行内部循环时都会对A矩阵进行分解,而在两次循环开始之前,我只能一次找到逆矩阵。

我的问题是,如何提高此功能的效率?有没有一种方法可以存储A的因式分解,以便每次为一个新点计算最小二乘解时,都不会重复相同的工作?

此函数的伪代码:

# Iterate through each triangle (and get corresponding warp triangle)
for triangle in triangulation:

    # Extract corners of the unwarped triangle
    a = firstCornerUW
    b = secondCornerUW
    c = thirdCornerUW

    # Extract corners of the warp triangle
    a_prime = firstCornerW
    b_prime = secondCornerW
    c_prime = thirdCornerW

    # This matrix will be the same for all points within the triangle
    triMatrix = matrix of a, b, and c

    # Bounding box of the triangle
    xleft = min(ax, bx, cx)
    xright = max(ax, bx, cx)
    ytop = min(ay, by, cy)
    ybottom = max(ay, by, cy)

    for x in range(xleft, xright):

        for y in range(ytop, ybottom):

            # Store the current point as a matrix
            p = np.array([[x], [y], [1]])

            # Solve for least squares solution to get barycentric coordinates
            barycoor = np.linalg.lstsq(triMatrix, p)

            # Pull individual coordinates from the array
            alpha = barycoor[0]
            beta = barycoor[1]
            gamma = barycoor[2]

            # If any of these conditions are not met, the point is not inside the triangle
            if alpha, beta, gamma > 0 and alpha + beta + gamma <= 1:

                # Now calculate the warped point by multiplying by alpha, beta, and gamma
                # Warp the point from image to warped image

最佳答案

这是我的建议,以您的伪代码表示。请注意,对三角形上的循环进行矢量化也不会很困难。

# Iterate through each triangle (and get corresponding warp triangle)
for triangle in triangulation:

    # Extract corners of the unwarped triangle
    a = firstCornerUW
    b = secondCornerUW
    c = thirdCornerUW

    # Bounding box of the triangle
    xleft = min(ax, bx, cx)
    xright = max(ax, bx, cx)
    ytop = min(ay, by, cy)
    ybottom = max(ay, by, cy)

    barytransform = np.linalg.inv([[ax,bx,cx], [ay,by,cy], [1,1,1]])

    grid = np.mgrid[xleft:xright, ytop:ybottom].reshape(2,-1)
    grid = np.vstack((grid, np.ones((1, grid.shape[1]))))

    barycoords = np.dot(barytransform, grid)
    barycoords = barycoords[:,np.all(barycoords>=0, axis=0)]

09-06 10:34