+#include <stdio.h>
+#include <errno.h>
+#include <opencv2/core/core_c.h>
+#include <opencv2/highgui/highgui_c.h>
+#include <opencv2/imgproc/imgproc_c.h>
+
+#define WIDTH 800
+#define HEIGHT 480
+
+#define X_CORRECTION 200
+
+int main(int argc, char *argv[])
+{
+ int ret;
+ IplImage *image;
+ IplImage *transformed_image;
+ CvRect viewport;
+ CvPoint2D32f src[4];
+ CvPoint2D32f dst[4];
+ CvMat *perspective_matrix;
+
+ if (argc != 2) {
+ fprintf(stderr, "usage: %s <image>\n", argv[0]);
+ ret = -EINVAL;
+ goto out;
+ }
+
+ image = cvLoadImage(argv[1], CV_LOAD_IMAGE_COLOR);
+ if (!image) {
+ fprintf(stderr, "Cannot load image\n");
+ ret = -EINVAL;
+ goto out;
+ }
+
+ cvNamedWindow("Viewport", 0);
+ cvResizeWindow("Viewport", WIDTH, HEIGHT);
+
+ /* Trasform only a part of the whole image */
+ viewport.x = 0;
+ viewport.y = 0;
+ viewport.width = WIDTH;
+ viewport.height = HEIGHT;
+ cvSetImageROI(image, viewport);
+
+ /* Calculate the prospective tranformation */
+ src[0].x = 0;
+ src[0].y = 0;
+ src[1].x = WIDTH;
+ src[1].y = 0;
+ src[2].x = WIDTH;
+ src[2].y = HEIGHT;
+ src[3].x = 0;
+ src[3].y = HEIGHT;
+
+ dst[0].x = X_CORRECTION;
+ dst[0].y = 0;
+ dst[1].x = WIDTH - X_CORRECTION;
+ dst[1].y = 0;
+ dst[2].x = WIDTH;
+ dst[2].y = HEIGHT;
+ dst[3].x = 0;
+ dst[3].y = HEIGHT;
+
+ perspective_matrix = cvCreateMat(3, 3, CV_64F);
+ if (!perspective_matrix) {
+ fprintf(stderr, "Cannot create matrix\n");
+ ret = -EINVAL;
+ goto out_destroy_window;
+ }
+
+ perspective_matrix = cvGetPerspectiveTransform(src, dst,
+ perspective_matrix);
+
+ /* Create a new image and apply the prospective transformation */
+ transformed_image = cvCreateImage(cvSize(WIDTH, HEIGHT), image->depth,
+ image->nChannels);
+ if (!transformed_image) {
+ fprintf(stderr, "Cannot create trasnformed image\n");
+ ret = -EINVAL;
+ goto out_release_mat;
+ }
+
+ cvWarpPerspective(image, transformed_image, perspective_matrix,
+ CV_INTER_LINEAR | CV_WARP_FILL_OUTLIERS,
+ cvScalarAll(0));
+
+ cvShowImage("Viewport", transformed_image);
+
+ cvWaitKey(0);
+
+ ret = 0;
+
+out_release_mat:
+ cvReleaseMat(&perspective_matrix);
+out_destroy_window:
+ cvDestroyWindow("Viewport");
+ cvReleaseImage(&image);
+out:
+ return ret;
+}