Contour Detection คือการหาขอบเขตของวัตถุในภาพ ใช้ใน Computer Vision, Image Segmentation, Shape Analysis
โมดูล skimage.measure มีฟังก์ชัน find_contours() ใช้ Algorithms **Marching Squares** หา Contours ที่ระดับความเข้ม (Level) ที่กำหนด
หมายเหตุ: scikit-image (skimage) แยกจาก scikit-learn (sklearn) แม้ชื่อคล้ายกัน แต่ skimage เน้น Image Processing
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
from skimage import measure
# สร้างข้อมูลทดสอบ: ฟังก์ชัน Sin/Cos ผสม
x, y = np.ogrid[-6.7:np.pi:215j, -1.2:np.pi:215j]
r = np.sin(np.exp((np.sin(x)**3 + np.cos(y)**2)))
# หา Contours ที่ Level = 0.8
contours = measure.find_contours(r, 0.8)
# พลอต
fig, ax = plt.subplots()
ax.imshow(r, cmap=plt.cm.gray)
for contour in contours:
ax.plot(contour[:, 1], contour[:, 0], linewidth=2, color='red')
ax.set_title('Contours at Level 0.8')
ax.axis('image')
ax.set_xticks([])
ax.set_yticks([])
plt.show()
ผลลัพธ์

คำอธิบาย
สร้าง Grid 2D ด้วย
np.ogrid(Open Grid - Memory Efficient)คำนวณค่า Intensity r จากฟังก์ชัน Sin/Cos 複雜
measure.find_contours(image, level)หา Contours ที่ Intensity = levelคืน List ของ Arrays (N, 2) = (row, column) Coordinates
พลอตภาพ Grayscale แล้ววาด Contours ทับกัน
พารามิเตอร์ find_contours()
find_contours(array, level, fully_connected='low', positive_orientation='low')
level: ค่า Intensity ที่ต้องการหา Contour (Float)fully_connected: 'low' (Face-connected) หรือ 'high' (Vertex-connected)positive_orientation: ทิศทางของ Contour
การใช้งานกับภาพจริง
from skimage import io, color, measure
# โหลดภาพ แปลง Grayscale
image = io.imread('image.png')
if image.ndim == 3:
image = color.rgb2gray(image)
# หา Contours หลาย Levels
levels = [0.3, 0.5, 0.7]
for level in levels:
contours = measure.find_contours(image, level)
# ประมวลผลต่อ...
เปรียบเทียบ: find_contours vs OpenCV findContours
| คุณสมบัติ | skimage.measure.find_contours | cv2.findContours |
|---|---|---|
| Input | Grayscale Float Array | Binary Image (Thresholded) |
| Method | Marching Squares (Sub-pixel) | Border Following (Pixel-level) |
| Output | Float Coordinates (Precise) | Integer Pixel Coordinates |
| Use Case | Scientific, Precise Measurement | General CV, Real-time |