ในโปรแกรมนี้ เราจะตรวจจับ Contours ในภาพ Contours สามารถอธิบายได้ง่ายๆ ว่าเป็น Curve ที่เชื่อมต่อจุดต่อเนื่องทั้งหมดที่มีสีหรือ Intensity เท่ากัน Contours เป็นเครื่องมือที่มีประโยชน์สำหรับการวิเคราะห์รูปร่าง และการตรวจจับและจดจำวัตถุ
ภาพต้นฉบับ

อัลกอริทึม
Step 1: Import OpenCV
Step 2: Import Matplotlib
Step 3: อ่านภาพ
Step 4: แปลงภาพจาก BGR2RGB
Step 5: แปลงภาพ RGB เป็น Grayscale
Step 6: ทำ Thresholding บนภาพ
Step 7: หา Contours บนภาพ
Step 8: วาด Contours บนภาพ
Step 9: แสดงผลลัพธ์
ตัวอย่างโค้ด
import cv2
import matplotlib.pyplot as plt
image = cv2.imread('testimage.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
plt.imshow(image)
plt.show()
ผลลัพธ์
