[英]Perspective transform with Python PIL using src / target coordinates
我偶然發現了這個問題,並嘗試使用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)。
如何確定目標點的精確坐標以正確傾斜圖像?
答案很簡單:只需交換源坐標和目標坐標。 但這不是你的錯:鏈接答案的作者特別容易混淆,因為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)
讓剩下的代碼保持不變,只使用不同的圖像,我得到了這個轉換:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.