/* * opencv-perspective-transform - Example program for cvWarpPerspective() * * Copyright (C) 2013 Antonio Ospite * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #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 \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); /* Transform only a part of the whole image */ viewport.x = 0; viewport.y = 0; viewport.width = WIDTH; viewport.height = HEIGHT; cvSetImageROI(image, viewport); /* Calculate the perspective transform */ 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 perspective transform */ transformed_image = cvCreateImage(cvSize(WIDTH, HEIGHT), image->depth, image->nChannels); if (!transformed_image) { fprintf(stderr, "Cannot create transformed 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; }