透视变换如何在PIL中发挥作用?

Hed*_*dge 40 python perspective python-imaging-library

PIL的变换功能有一个透视模式,需要一个8-tupel的数据,但我无法弄清楚如何转换让我们说这是一个正确的倾斜30度到该tupel.

有人能解释一下吗?

这是它的文档:http://effbot.org/imagingbook/image.htm

mmg*_*mgp 69

要应用透视变换,首先必须知道平面A中的四个点,这四个点将映射到平面B中的四个点.使用这些点,您可以导出单应变换.通过这样做,您可以获得8个系数,并且可以进行转换.

该网站http://xenia.media.mit.edu/~cwren/interpolator/(镜:WebArchive),以及许多其他的文本,描述了这些系数如何才能确定.为了简单起见,这里是根据上述链接的直接实现:

import numpy

def find_coeffs(pa, pb):
    matrix = []
    for p1, p2 in zip(pa, pb):
        matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
        matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])

    A = numpy.matrix(matrix, dtype=numpy.float)
    B = numpy.array(pb).reshape(8)

    res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B)
    return numpy.array(res).reshape(8)
Run Code Online (Sandbox Code Playgroud)

其中pb是当前平面pa中的四个顶点,并在结果平面中包含四个顶点.

因此,假设我们将图像转换为:

import sys
from PIL import Image

img = Image.open(sys.argv[1])
width, height = img.size
m = -0.5
xshift = abs(m) * width
new_width = width + int(round(xshift))
img = img.transform((new_width, height), Image.AFFINE,
        (1, m, -xshift if m > 0 else 0, 0, 1, 0), Image.BICUBIC)
img.save(sys.argv[2])
Run Code Online (Sandbox Code Playgroud)

以下是使用上面代码的示例输入和输出:

在此输入图像描述 在此输入图像描述

我们可以继续使用最后一个代码并执行透视转换以恢复剪切:

coeffs = find_coeffs(
        [(0, 0), (256, 0), (256, 256), (0, 256)],
        [(0, 0), (256, 0), (new_width, height), (xshift, height)])

img.transform((width, height), Image.PERSPECTIVE, coeffs,
        Image.BICUBIC).save(sys.argv[3])
Run Code Online (Sandbox Code Playgroud)

导致:

在此输入图像描述

您还可以获得目的地点的乐趣:

在此输入图像描述 在此输入图像描述

  • @mmgp你在答案中提供的链接现在已经破了,给出了403. (2认同)

Dav*_*ver 10

我将稍微劫持这个问题,因为它是Google上与Python中的透视转换有关的唯一内容.下面是一些基于上面的稍微更通用的代码,它创建了一个透视变换矩阵并生成一个函数,该函数将在任意点上运行该变换:

import numpy as np

def create_perspective_transform_matrix(src, dst):
    """ Creates a perspective transformation matrix which transforms points
        in quadrilateral ``src`` to the corresponding points on quadrilateral
        ``dst``.

        Will raise a ``np.linalg.LinAlgError`` on invalid input.
        """
    # See:
    # * http://xenia.media.mit.edu/~cwren/interpolator/
    # * http://stackoverflow.com/a/14178717/71522
    in_matrix = []
    for (x, y), (X, Y) in zip(src, dst):
        in_matrix.extend([
            [x, y, 1, 0, 0, 0, -X * x, -X * y],
            [0, 0, 0, x, y, 1, -Y * x, -Y * y],
        ])

    A = np.matrix(in_matrix, dtype=np.float)
    B = np.array(dst).reshape(8)
    af = np.dot(np.linalg.inv(A.T * A) * A.T, B)
    return np.append(np.array(af).reshape(8), 1).reshape((3, 3))


def create_perspective_transform(src, dst, round=False, splat_args=False):
    """ Returns a function which will transform points in quadrilateral
        ``src`` to the corresponding points on quadrilateral ``dst``::

            >>> transform = create_perspective_transform(
            ...     [(0, 0), (10, 0), (10, 10), (0, 10)],
            ...     [(50, 50), (100, 50), (100, 100), (50, 100)],
            ... )
            >>> transform((5, 5))
            (74.99999999999639, 74.999999999999957)

        If ``round`` is ``True`` then points will be rounded to the nearest
        integer and integer values will be returned.

            >>> transform = create_perspective_transform(
            ...     [(0, 0), (10, 0), (10, 10), (0, 10)],
            ...     [(50, 50), (100, 50), (100, 100), (50, 100)],
            ...     round=True,
            ... )
            >>> transform((5, 5))
            (75, 75)

        If ``splat_args`` is ``True`` the function will accept two arguments
        instead of a tuple.

            >>> transform = create_perspective_transform(
            ...     [(0, 0), (10, 0), (10, 10), (0, 10)],
            ...     [(50, 50), (100, 50), (100, 100), (50, 100)],
            ...     splat_args=True,
            ... )
            >>> transform(5, 5)
            (74.99999999999639, 74.999999999999957)

        If the input values yield an invalid transformation matrix an identity
        function will be returned and the ``error`` attribute will be set to a
        description of the error::

            >>> tranform = create_perspective_transform(
            ...     np.zeros((4, 2)),
            ...     np.zeros((4, 2)),
            ... )
            >>> transform((5, 5))
            (5.0, 5.0)
            >>> transform.error
            'invalid input quads (...): Singular matrix
        """
    try:
        transform_matrix = create_perspective_transform_matrix(src, dst)
        error = None
    except np.linalg.LinAlgError as e:
        transform_matrix = np.identity(3, dtype=np.float)
        error = "invalid input quads (%s and %s): %s" %(src, dst, e)
        error = error.replace("\n", "")

    to_eval = "def perspective_transform(%s):\n" %(
        splat_args and "*pt" or "pt",
    )
    to_eval += "  res = np.dot(transform_matrix, ((pt[0], ), (pt[1], ), (1, )))\n"
    to_eval += "  res = res / res[2]\n"
    if round:
        to_eval += "  return (int(round(res[0][0])), int(round(res[1][0])))\n"
    else:
        to_eval += "  return (res[0][0], res[1][0])\n"
    locals = {
        "transform_matrix": transform_matrix,
    }
    locals.update(globals())
    exec to_eval in locals, locals
    res = locals["perspective_transform"]
    res.matrix = transform_matrix
    res.error = error
    return res
Run Code Online (Sandbox Code Playgroud)


Ami*_*mir 9

8个变换系数(a、b、c、d、e、f、g、h)对应如下变换:

x' = (a x + b y + c) / (g x + h y + 1)
y' = (d x + e y + f) / (g x + h y + 1)

这 8 个系数通常可以从求解 8 个(线性)方程中找到,这些方程定义了平面上的 4 个点如何变换(2D 中的 4 个点 -> 8 个方程),请参阅 mmgp 的答案以获取解决此问题的代码,尽管您可能发现改变线路更准确

res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B)
Run Code Online (Sandbox Code Playgroud)

res = numpy.linalg.solve(A, B)
Run Code Online (Sandbox Code Playgroud)

即,没有真正的理由在那里实际反转 A 矩阵,或者将它乘以它的转置并失去一点精度,以解决方程。

至于你的问题,对于 (x0, y0) 附近的θ度的简单倾斜,你正在寻找的系数是:

def find_rotation_coeffs(theta, x0, y0):
    ct = cos(theta)
    st = sin(theta)
    return np.array([ct, -st, x0*(1-ct) + y0*st, st, ct, y0*(1-ct)-x0*st,0,0])
Run Code Online (Sandbox Code Playgroud)

一般而言,任何仿射变换都必须使 (g, h) 为零。希望有帮助!


Kar*_*gat 6

这是一个生成变换系数的纯Python版本(正如我已经看过几个请求的那样).我制作并用它来制作PyDraw纯Python图像绘制包.

如果将它用于您自己的项目,请注意计算需要几个高级矩阵运算,这意味着此函数需要另一个幸运的纯Python,矩阵库,matfunc最初由Raymond Hettinger编写,您可以在此处此处下载.

import matfunc as mt

def perspective_coefficients(self, oldplane, newplane):
    """
    Calculates and returns the transform coefficients needed for a perspective 
    transform, ie tilting an image in 3D.
    Note: it is not very obvious how to set the oldplane and newplane arguments
    in order to tilt an image the way one wants. Need to make the arguments more
    user-friendly and handle the oldplane/newplane behind the scenes.
    Some hints on how to do that at http://www.cs.utexas.edu/~fussell/courses/cs384g/lectures/lecture20-Z_buffer_pipeline.pdf

    | **option** | **description**
    | --- | --- 
    | oldplane | a list of four old xy coordinate pairs
    | newplane | four points in the new plane corresponding to the old points

    """
    # first find the transform coefficients, thanks to http://stackoverflow.com/questions/14177744/how-does-perspective-transformation-work-in-pil
    pb,pa = oldplane,newplane
    grid = []
    for p1,p2 in zip(pa, pb):
        grid.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
        grid.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])

    # then do some matrix magic
    A = mt.Matrix(grid)
    B = mt.Vec([xory for xy in pb for xory in xy])
    AT = A.tr()
    ATA = AT.mmul(A)
    gridinv = ATA.inverse()
    invAT = gridinv.mmul(AT)
    res = invAT.mmul(B)
    a,b,c,d,e,f,g,h = res.flatten()

    # finito
    return a,b,c,d,e,f,g,h
Run Code Online (Sandbox Code Playgroud)