[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Perspective Transform Quad



Kamilche wrote:

I have a need to tile a bitmap across an arbitrary quadrilateral, and
apply perspective to it.
The Python Imaging Library (PIL) has an undocumented function that
might work, but I can't figure out how to make it work. You're
supposed to pass it 8 parameters, a b c d e f g h .

My version of PIL doesn't have this function (the Image.PERSPECTIVE constant exists, but it raises an exception), but most likely the 8 parameters correspond to all but one of the elements for a 2D transformation matrix:


[x']   [a b c][x]
[y'] = [d e f][y]
[w']   [g h 1][1]

The AFFINE transform method allows you to supply 6 of these:

[x'] = [a b c][x]
[y'] = [d e f][y]
[w'] = [0 0 1][1]

Typically projection occurs from 3D to 2D, and the Z coordinate is used as the perspective divide:

[x'] = [1 0 0 0][x]
[y'] = [0 1 0 0][y]
[z'] = [0 0 1 0][z]
[w'] = [0 0 1 0][1]

The resulting 4-tuple (x,y,z,w) is divided through by w to project into 3D: (x/w, y/w, z/w).

In your application you don't have 3D data, but you can achieve the same result using Y as the perspective divide (higher values of Y mean higher values of W, so pixels near the top of the image will be have have their X coordinate divided more):

[x'] = [1 0 0][x]
[y'] = [0 y 0][y]
[w'] = [0 1 0][1]

However, it appears that the function you describe will not accept "y" as a matrix parameter, or any value besides 0 for the bottom-left element. So this function won't solve your problem.

There is a QUAD transform in PIL which you could use to map a trapezium to a rectangle. The result will not look correct though, as it will not apply perspective-correct interpolation. The result may be "good enough" (the current generation of mobile devices with 3D chipsets do not employ perspective correction, but all PC chips have done so since texture mapping was introduced).

Any 3D imaging library will be able to apply the perspective you need.

Cheers
Alex.