【问题标题】:Perspective transform with Python PIL using src / target coordinates使用 src / 目标坐标使用 Python PIL 进行透视变换
【发布时间】:2018-10-28 13:55:37
【问题描述】:

我偶然发现了this question,并正在尝试使用 Python Pillow 执行透视变换。

这就是我正在尝试做的事情以及结果的样子:

这是我曾经尝试过的代码:

from PIL import Image
import numpy

# function copy-pasted from https://stackoverflow.com/a/14178717/744230
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)

# test.png is a 256x256 white square
img = Image.open("./images/test.png")

coeffs = find_coeffs(
    [(0, 0), (256, 0), (256, 256), (0, 256)],
    [(15, 115), (140, 20), (140, 340), (15, 250)])

img.transform((300, 400), Image.PERSPECTIVE, coeffs,
              Image.BICUBIC).show()

我不确定转换是如何工作的,但似乎这些点向相反的方向移动(例如,我需要做 (-15, 115) 以使 A 点向右移动。但是,它也赢了'不是移动 15 个像素,而是 5)。

如何确定目标点的确切坐标以正确倾斜图像?

【问题讨论】:

    标签: python image-processing python-imaging-library coordinate-transformation


    【解决方案1】:

    答案很简单:只需交换源坐标和目标坐标即可。但这不是你的错:链接答案的作者特别容易混淆,因为 target, source 是(在这种情况下)函数参数的混乱顺序,因为函数参数没有有用的名称,并且因为示例确实剪切的反向变换。

    除了交换源坐标和目标坐标之外,您还可以交换find_coeffs 函数的参数。更好的是,也可以重命名它们,比如

    def find_coeffs(source_coords, target_coords):
        matrix = []
        for s, t in zip(source_coords, target_coords):
            matrix.append([t[0], t[1], 1, 0, 0, 0, -s[0]*t[0], -s[0]*t[1]])
            matrix.append([0, 0, 0, t[0], t[1], 1, -s[1]*t[0], -s[1]*t[1]])
        A = numpy.matrix(matrix, dtype=numpy.float)
        B = numpy.array(source_coords).reshape(8)
        res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B)
        return numpy.array(res).reshape(8)
    

    让你的其余代码保持不变,只使用不同的图像,我得到了这个转换:

       ⇒   

    【讨论】:

    • 尽管您的测试图像很经典,但我认为是时候让其他东西取代它了。在我自己的答案中,我尝试使用自己拍摄的照片。
    • 我不同意,但不想在这里讨论这个问题,所以我将图像替换为我自己的图像(由我儿子拍摄)
    • stupidme 刚刚意识到我在原来的 SO 答案中没有看到where pb is the four vertices in the current plane, and pa contains four vertices in the resulting plane,所以我认为 pb 是生成的飞机,而 pa 是当前的飞机。我想知道为什么没有其他人遇到该代码的问题,但我显然无法阅读:) 谢谢!
    • 不客气!但是,正如我所写,恕我直言,这不是你的错。顺便说一句,我对find_coeffs() 在第三行中交换循环变量进行了一些改进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多