How to do it...

  1. Import the modules we need:
import cv2import numpy as np
  1. Implement a function which finds the intersection point of two lines:
def intersect(l1, l2):    delta = np.array([l1[1] - l1[0], l2[1] - l2[0]]).astype(np.float32)        delta = 1 / delta    delta[:, 0] *= -1        b = np.matmul(delta, np.array([l1[0], l2[0]]).transpose())    b = np.diagonal(b).astype(np.float32)            res = cv2.solve(delta, b)    return res[0], tuple(res[1].astype(np.int32).reshape((2)))
  1. Define a function which un-warps the perspective distortions by calculating the correspondence between four pairs of distorted and un-distorted points:
def rectify(image, corners, out_size):    rect = np.zeros((4, 2), dtype = "float32")    rect[0] = corners[0]    rect[1] = corners[1] rect[2] = corners[2] ...

Get OpenCV 3 Computer Vision with Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.