Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning OpenCV 3 Computer Vision with Python (Update)

You're reading from   Learning OpenCV 3 Computer Vision with Python (Update) Unleash the power of computer vision with Python using OpenCV

Arrow left icon
Product type Paperback
Published in Sep 2015
Publisher
ISBN-13 9781785283840
Length 266 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (11) Chapters Close

Preface 1. Setting Up OpenCV FREE CHAPTER 2. Handling Files, Cameras, and GUIs 3. Processing Images with OpenCV 3 4. Depth Estimation and Segmentation 5. Detecting and Recognizing Faces 6. Retrieving Images and Searching Using Image Descriptors 7. Detecting and Recognizing Objects 8. Tracking Objects 9. Neural Networks with OpenCV – an Introduction Index

Contours – bounding box, minimum area rectangle, and minimum enclosing circle


Finding the contours of a square is a simple task; irregular, skewed, and rotated shapes bring the best out of the cv2.findContours utility function of OpenCV. Let's take a look at the following image:

In a real-life application, we would be most interested in determining the bounding box of the subject, its minimum enclosing rectangle, and its circle. The cv2.findContours function in conjunction with a few other OpenCV utilities makes this very easy to accomplish:

import cv2
import numpy as np

img = cv2.pyrDown(cv2.imread("hammer.jpg", cv2.IMREAD_UNCHANGED))

ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) , 127, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
  # find bounding box coordinates
  x,y,w,h = cv2.boundingRect(c)
  cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)

  # find minimum area...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime