Contour Approximation
adalah algoritma untuk memperikirakan contour dari sebuah bentuk. Hasil dari contour approximation dapat kita tuning berdasarkan akurasi. Untuk lebih jelasnya, mari kita langsung gunakan program sederhana.
Pertama, import library yang diperlukan.
import cv2 import numpy as np import matplotlib.pyplot as plt %matplotlib inline
Kemudian load image yang digunakan, buat copy image dan tentukan treshold. Image awal adalah gambar sketsa rumah.
img = cv2.imread('rss.jpg')
img_copy = img.copy()
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, tresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
plt.imshow(img_copy)

Proses selanjutnya adalah menghitung contour. Hasil contour kita petakan dengan menggambar rectangle pada image.
Terlihat ada 4 contour yang terdeteksi, yaitu contour untuk atap, badan rumah, pintu dan rumah secara keseluruhan.
contours, hierarchy = cv2.findContours(tresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) for c in contours: x,y,w,h = cv2.boundingRect(c) cv2.rectangle(img_copy, (x,y), (x+w, y+h), (0,255,0), 2) plt.imshow(img_copy)

Menggambar approximation contour pada image dengan menggunakan fungsi cv2.approxPolyDP(). Presisi dari contour dapat dituning melalui accuracy dengan mengubah koefisien pengali, pada contoh digunakan 0.03.
for c in contours: accuracy = 0.03 * cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, accuracy, True) cv2.drawContours(img, [approx], 0, (255,0,0), 2) plt.imshow(img)

Convex Hull
Convex curves dapat diartikan sebagai contour terluar dari sebuah object. Untuk jelasnya, langsung kita coba dengan code sederhana untuk menentuk convex hull dari object telapak tangan.
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
img = cv2.imread('palm.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, tresh = cv2.threshold(img_gray, 176, 255, 0)
contours, hierarchy = cv2.findContours(tresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
n = len(contours)-1
contours = sorted(contours, key=cv2.contourArea, reverse=False)[:n]
for c in contours:
hull = cv2.convexHull(c)
cv2.drawContours(img, [hull], 0, (255,0,0), 2)
plt.imshow(img

Image download di https://drive.google.com/file/d/1uZGOqt5xW2wKbEs8DJqnpV8fKgMdQRiu/view?usp=sharing
Notebook colab di https://colab.research.google.com/drive/1kPaej40xBtfq1BRJZhTbx6ZHW2mCYqpW?usp=sharing