Perspective transformations

Updated:

Previously I wrote a short article about Imagick in php here, as part of learning the image processing using  php.

The discussion in this article is how to process image distortion to create perspective. The idea is to distort image by moving points to new location.

The syntax defined by Imagick is an array of points

[source_x, source_y, dest_x, dest_y ... ]

This is a little bit confusing for anyone started learning this. So here's another example

[
0,0, 0,5,
0,100, 0,95,
]

As shown here, there are the two points are being moved to new locations. Point (0,0) -> (0,5) and point (0, 100) -> (0, 95).

X and Y coordinate

Working with the image coordinate is like plotting points on the cartesian plane in the area as you can see in the image below, but the y-coordinate think of it as having a positive direction in this case.

Applying on image

We'll be using this image, and it has width=300 and height=200 pixels to apply the idea discussed above.

To create new image resource can be done with

$im = new Imagick('Thinking-of-getting-a-cat.png');

Next define a format of the image

$im->setImageFormat('png');

Next define a virtual pixel method. In digital imaging, a pixel, pel, or picture element is a physical point in a raster image, or the smallest addressable element in an all points addressable display device; so it is the smallest controllable element of a picture represented on the screen. Here we're defining just that virtually and is transparent.

$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);

Next define a control points

$cPoints = [
0,0, 0,0,
0,200, 0,200,
300,0, 300,20,
300,200, 300,180
];

Next pass the $cPoints as arguments in the distorImage method.

$im->distortImage(Imagick::DISTORTION_BILINEAR, $cPoints, true);

Last display the result in the browser.

header('Content-Type: image/png');
echo $im;

It should display.

The whole code

Here's the full code discussed above.

$im = new Imagick('Thinking-of-getting-a-cat.png');
$im->setImageFormat('png');
$im->cropThumbnailImage(300, 200);
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);

$cPoints = [
0,0, 0,0,
0,200, 0,200,
300,0, 300,20,
300,200, 300,180
];

$im->distortImage(Imagick::DISTORTION_BILINEAR, $cPoints, true);
header('Content-Type: image/png');
echo $im;

What's next?

I recommend reading the next article which improved this code by using object-oriented way to make it cleaner coding style here.