Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

OpenCV Python Contours Tutorial: Shape Detection, Object Boundary & Image Segmentation Guide

OpenCV Python – Image Contours

Contours are one of the most important concepts in computer vision. They help detect object boundaries and shapes in an image. In simple terms, contours are curves that join all continuous points along the boundary of an object.

In OpenCV Python, contours are widely used for shape detection, object recognition, and image analysis.


1. What are Contours?

Contours are simply:

  • Boundaries of objects in an image
  • Lines connecting points of equal intensity

They are useful for:

  • Object detection
  • Shape analysis
  • Size measurement
  • Image segmentation

2. Import OpenCV

import cv2

3. Read and Preprocess Image

Contours work best on binary images.

img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

cv2.imshow("Binary Image", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

4. Find Contours

Syntax:

cv2.findContours(image, mode, method)

Example:

contours, hierarchy = cv2.findContours(
thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
)

5. Draw Contours

cv2.drawContours(img, contours, -1, (0, 255, 0), 2)

cv2.imshow("Contours", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

6. Draw Specific Contour

cv2.drawContours(img, contours, 0, (255, 0, 0), 2)

7. Contour Hierarchy

Hierarchy defines relationships between contours:

  • Parent contours
  • Child contours
print(hierarchy)

8. Contour Area

for cnt in contours:
area = cv2.contourArea(cnt)
print("Area:", area)

9. Contour Perimeter

for cnt in contours:
perimeter = cv2.arcLength(cnt, True)
print("Perimeter:", perimeter)

10. Bounding Rectangle

for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)

11. Approximate Shape

for cnt in contours:
epsilon = 0.02 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
print("Vertices:", len(approx))

12. Why Contours are Important

Contours are used in:

  • Object detection systems
  • Face recognition
  • Shape classification
  • Medical imaging
  • OCR and document scanning

13. Common Mistakes

❌ Using color image directly

✔ Solution:

cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

❌ Missing threshold step

✔ Solution:

  • Always convert image to binary before finding contours

14. Conclusion

Contours in OpenCV Python are essential for detecting object boundaries and analyzing shapes. They form the foundation of many computer vision applications like object detection and image segmentation.

Once you master contours, you can move to advanced shape recognition and object tracking systems.




Post a Comment

0 Comments