在进行转换时跟踪 PIL 图像中的参考像素

Keep track of reference pixel in PIL imgage while doing transformations

我想在 PIL 图像中跟踪 point/pixel 以供参考,同时我进行(透视)变换并切断透明边框。

from PIL import Image

# load image
img = Image.open("img.png")

# do some perspective transformation
img.transform(new_size, Image.PERSPECTIVE, mapping_coeffs)

# cut the borders
img = img.crop(img.getbbox())

对于裁剪,我可以通过减去填充的大小来跟踪位置。但是我该如何进行透视变换,甚至是连续多次变换呢?

对于有同样问题的其他人,我使用 NumPy 制作了一个只有白色参考像素的黑色图像,并按照与我的图像相同的方式对其进行了转换。

from PIL import Image
import numpy as np

# get black img with the same size
refArray = np.zeros(PILimg.size)

# make the reference pixel white
refArray[xRef, yRef] = 1e8

# to PIL image object 
refImg = Image.fromarray(refArray.T)  

对参考图像做同样的变换,然后在变换后的参考图像中找到最大值

ref = np.array(refImg).T
xRef, yRef = np.unravel_index(np.argmax(ref), ref.shape)

编辑:对于某些变换,像素消失了,这是通过使用小方块像素 (5x5) 而不是单个像素来解决的。