How to do it...

You need to complete the following steps:

  1. Import the modules we need:
import cv2import numpy as np
  1. Define a function that applies PCA to contour points and determines the new basis:
def contours_pca(contours):    # join all contours points into the single matrix and remove unit dimensions     cnt_pts = np.vstack(contours).squeeze().astype(np.float32)    mean, eigvec = cv2.PCACompute(cnt_pts, None)    center = mean.squeeze().astype(np.int32)    delta = (150*eigvec).astype(np.int32)    return center, delta
  1. Define a function that displays the results of applying PCA to points of contours:
def draw_pca_results(image, contours, center, delta):    cv2.drawContours(image, contours, -1, (255, 255, 0)) cv2.line(image, tuple((center + delta[0])), ...

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.