Goals

Transformations

OpenCV provides two transformation functions, cv2.warpAffine and cv2.warpPerspective, with which you can have all kinds of transformations. cv2.warpAffine takes a 2x3 transformation matrix while cv2.warpPerspective takes a 3x3 transformation matrix as input.

Scaling

Scaling is just resizing of the image. OpenCV comes with a function cv2.resize() for this purpose. The size of the image can be specified manually, or you can specify the scaling factor. Different interpolation methods are used. Preferable interpolation methods are cv2.INTER_AREA for shrinking and cv2.INTER_CUBIC (slow) & cv2.INTER_LINEAR for zooming. By default, interpolation method used is cv2.INTER_LINEAR for all resizing purposes. You can resize an input image either of following methods:

To find this transformation matrix, OpenCV provides a function, cv2.getRotationMatrix2D. Check below example which rotates the image by 90 degree with respect to center without any scaling.

1 img = cv2.imread('messi5.jpg',0)

2 rows,cols = img.shape

3

4 M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)

5 dst = cv2.warpAffine(img,M,(cols,rows))

See the result:

image

Affine Transformation

In affine transformation, all parallel lines in the original image will still be parallel in the output image. To find the transformation matrix, we need three points from input image and their corresponding locations in output image. Then cv2.getAffineTransform will create a 2x3 matrix which is to be passed to cv2.warpAffine.

Check below example, and also look at the points I selected (which are marked in Green color):

1 img = cv2.imread('drawing.png')

2 rows,cols,ch = img.shape

3

4 pts1 = np.float32([[50,50],[200,50],[50,200]])

5 pts2 = np.float32([[10,100],[200,50],[100,250]])

6

7 M = cv2.getAffineTransform(pts1,pts2)

8

9 dst = cv2.warpAffine(img,M,(cols,rows))

10

11 plt.subplot(121),plt.imshow(img),plt.title('Input')

12 plt.subplot(122),plt.imshow(dst),plt.title('Output')

13 plt.show()

See the result:

image

Perspective Transformation

For perspective transformation, you need a 3x3 transformation matrix. Straight lines will remain straight even after the transformation. To find this transformation matrix, you need 4 points on the input image and corresponding points on the output image. Among these 4 points, 3 of them should not be collinear. Then transformation matrix can be found by the function cv2.getPerspectiveTransform. Then apply cv2.warpPerspective with this 3x3 transformation matrix.