50

PILImage.transformには8タプルのデータを必要とするパースペクティブモードがありますが、たとえば30度の右傾斜をそのタプルに変換する方法がわかりません。

誰かがそれを説明できますか?

4

4 に答える 4

93

透視変換を適用するには、最初に、平面Bの4つの点にマッピングされる平面Aの4つの点を知る必要があります。これらの点を使用して、同形異義語変換を導出できます。これを行うことにより、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)

ここpbで、は現在の平面のpa4つの頂点であり、結果の平面に4つの頂点が含まれています。

したがって、次のように画像を変換するとします。

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])

上記のコードを使用した入力と出力のサンプルを次に示します。

ここに画像の説明を入力してください ここに画像の説明を入力してください

最後のコードを続行し、パースペクティブ変換を実行してシアーを元に戻すことができます。

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])

その結果:

ここに画像の説明を入力してください

目的地のポイントを楽しむこともできます。

ここに画像の説明を入力してください ここに画像の説明を入力してください

于 2013-01-06T02:35:35.790 に答える
12

この質問は、Pythonでの遠近法変換に関するGoogleでの唯一のものであるため、ほんの少しだけハイジャックします。上記に基づいて、パースペクティブ変換行列を作成し、任意のポイントでその変換を実行する関数を生成する、もう少し一般的なコードを次に示します。

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
于 2014-06-06T18:33:00.933 に答える
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つの係数は、一般に、平面上の4つの点がどのように変換されるかを定義する8つの(線形)方程式(2Dの4つの点-> 8つの方程式)を解くことから見つけることができます。これを解くコードについては、mmgpによる回答を参照してください。行を変更する方が少し正確です

res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B)

res = numpy.linalg.solve(A, B)

つまり、方程式を解くために、実際に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])

また、一般に、アフィン変換は(g、h)がゼロに等しくなければなりません。お役に立てば幸いです。

于 2017-06-01T10:45:22.383 に答える
7

これは、変換係数を生成する純粋なPythonバージョンです(これはいくつかの人から要求されたものです)。PyDrawの純粋なPython画像描画パッケージを作成して使用しました。

独自のプロジェクトで使用する場合は、計算にいくつかの高度な行列演算が必要であることに注意してください。つまり、この関数には、matfunc元々Raymond Hettingerによって作成された、別の幸運な純粋なPythonの行列ライブラリが必要であり、ここまたはここからダウンロードできます。

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
于 2014-09-23T21:05:48.180 に答える