Khashayar
Khashayar

Reputation: 2034

Transform Rectangle to trapezoid for perspective

I have picture from front-view. and I want to turn this into bird's eye view. Now I want to calculate for each point in the rectangle (x,y) what will be transformed x,y in the trapezoid. enter image description here

there must be a formula for this transformation with a given x and y and also the angle of the trapezoid (a).

I am programming in C and using opencv.

Thanks a lot in advance.

Upvotes: 6

Views: 6255

Answers (2)

Jeru Luke
Jeru Luke

Reputation: 21203

I was able to figure out a way for your problem.

Here is the code I used for the same:

Importing the required packages:
import cv2
import numpy as np
Reading the image to be used:
filename = '1.jpg'
img = cv2.imread(filename)
cv2.imwrite('img.jpg',img)

enter image description here

Storing the height and width of the image in separate variables:
ih, iw, _ = img.shape
Creating a black window whose size is bigger than that of the image and storing its height and width in separate variables:
black = np.zeros((ih + 300, iw + 300, 3), np.uint8)
cv2.imwrite('black.jpg',black)
bh, bw, _ = black.shape

enter image description here

Storing the 4 corner points of the image in an array:
pts_src = np.array([[0.0, 0.0],[float(iw), 0.0],[float(iw), float(ih)],[0.0,float(ih)]])
Storing the 4 corner points of the trapezoid to be obtained:
pts_dst = np.array([[bw * 0.25, 0],[bw * 0.75, 0.0],[float(bw), float(bh)],[0.0,float(bh)]])
Calculating the homography matrix using pts_src and pts_dst:
h, status = cv2.findHomography(pts_src, pts_dst)
Warping the given rectangular image into the trapezoid:
im_out = cv2.warpPerspective(img, h, (black.shape[1],black.shape[0]))
cv2.imwrite("im_outImage.jpg", im_out)

enter image description here

cv2.waitKey(0)
cv2.destroyAllWindows()

If you alter the values in the array pts_dst you will be able to get different kinds of quadrilaterals.

Upvotes: 4

cedrou
cedrou

Reputation: 2790

Did you consider the homography transform. You use this to create or correct perspective in an image, I think that it is exactly what you want.

With OpenCV, you can use the method cv::findHomography(). The arguments are the 4 initial points (vertices of your rectangle) and the 4 final points (the vertices of the trapeze). You get a transformation matrix that you can then use with cv::warpPerspective() or cv::perspectiveTransform().

Upvotes: 6

Related Questions