Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาและวาด Contours ในภาพด้วย OpenCV Python

Contours = เส้นขอบของวัตถุในภาพ (เชื่อมจุดที่มี Intensity เท่ากัน) ใช้ใน Shape Analysis, Object Detection

ฟังก์ชันหลัก

  • cv2.findContours() - หา Contours
  • cv2.drawContours() - วาด Contours

Syntax

contours, hierarchy = cv2.findContours(
    image, mode, method
)

cv2.drawContours(
    image, contours, contourIdx, color, thickness
)

Mode (Retrieval Mode)

  • cv2.RETR_EXTERNAL - เฉพาะ Contours นอกสุด
  • cv2.RETR_LIST - ทั้งหมด ไม่สน Hierarchy
  • cv2.RETR_TREE - ทั้งหมด พร้อม Hierarchy Tree

Method (Approximation)

  • cv2.CHAIN_APPROX_NONE - เก็บทุกจุด
  • cv2.CHAIN_APPROX_SIMPLE - บีบอัด (เก็บจุดมุม)

ตัวอย่างโค้ด Python

import cv2

# โหลดภาพ
image = cv2.imread("shapes.jpg")

# Preprocess: Grayscale -> Edge Detection
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 10, 100)

# หา Contours
contours, hierarchy = cv2.findContours(
    edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
)

print("Number of Contours found:", len(contours))

# วาด Contours บางอัน
cv2.drawContours(image, contours, 0, (0, 230, 255), 6)  # Contour 0: สีเหลือง
cv2.drawContours(image, contours, 2, (0, 230, 255), 6)  # Contour 2: สีเหลือง
# contourIdx = -1 → วาดทั้งหมด

# แสดงผล
cv2.imshow('Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

ผลลัพธ์

Number of Contours found = 3

แสดงภาพพร้อมเส้นขอบสีเหลืองรอบรูปทรง

ขั้นตอนทั่วไป

  1. Load Image
  2. Grayscale
  3. Blur (Optional: GaussianBlur)
  4. Edge Detection (Canny)
  5. Find Contours
  6. Filter/Draw Contours