How to do it...

  1. Import all of the necessary modules, open an image, and display it on the screen:
import cv2, randomimport numpy as npimg = cv2.imread('bw.png', cv2.IMREAD_GRAYSCALE)
  1. Find the contours of the loaded image, draw them, and show the result:
im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)cv2.drawContours(color, contours, -1, (0,255,0), 3)cv2.imshow('contours', color)cv2.waitKey()cv2.destroyAllWindows()
  1. Take the first contour, find its area in various cases, and output the resulting numbers:
contour = contours[0]print('Area of contour is %.2f' % cv2.contourArea(contour))print('Signed area of contour is %.2f' % cv2.contourArea(contour, True)) ...

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.