Image segmentation adalah proses membagi image kedalam bagian yang berbeda. Countours adalah salah satu teknik untuk melakukan image segmentation.
Countours dapat didefinisikan sebagai garis atau kurva yang berkelanjutan yang memetakan batas sebuah objek didalam image. Countour digunakna untuk object detection dan shape analysis.
Fungsi yang digunakan adalah
countours, hierarchy = cv2.findContours(edge, hierarchy, approximation_method)
Perhatian, untuk OpenCV 3.x, akan mengembalikan 3 value, yaitu boolean yang menunjukan fungsi berhasil. gunakan format code berikut:
_, countours, hierarchy = cv2.findContours(edge, hierarchy, approximation_method)
Approximation Method
- cv2.CHAIN_APPROX_NONE akan menyimpan semua data boundary points.
- cv2.CHAIN_APPROX_SIMPLE akan menyimpan data start dan end dari boundary points. Contoh, segitiga akan hanya memiliki 3 boundary points.
Hierarchy countour ada 4 jenis. Kita akan bahas 2 hierarchy yang umum digunakan yaitu RETR_LIST dan RETR_EXTERNAL.
- cv2.RETR_LIST : mengembalikan seluruh countour.
- cv2.RETR_EXTERNAL : mengembalikan outer countour.
- cv2.RETR_COMP: mengembalikan dalam 2-level hierarchy
- cv2.RETR_TREE : mengembalikan full hierarchy.
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
img = cv2.imread('countours_detection.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edge = cv2.Canny(img_gray, 30, 200)
countours, hierarchy = cv2.findContours(edge, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(img, countours, -1, (0,255,0), 3)
fig, ax1 = plt.subplots(1, 1, figsize=(14,7))
ax1.set_title('Contours External')
ax1.imshow(img)
print('Number of countors found =' + str(len(countours)))

countours, hierarchy = cv2.findContours(edge, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(img, countours, -1, (0,255,0), 3)
fig, ax1 = plt.subplots(1, 1, figsize=(14,7))
ax1.set_title('Contours List')
ax1.imshow(img)
print('Number of countors found =' + str(len(countours)))

File image download di https://drive.google.com/file/d/1mhLmm0NDSqn9Nngrc5riYG_L6koDSntM/view?usp=sharing
File colab buka di https://colab.research.google.com/drive/11e_8GYwHMLUMMt6Jb5WtVvDIWPSNfroV?usp=sharing