Matching Shape Menggunakan Contour

Matching shape adalah proses mencari shape yang sama berdasarkan referensi contour template. Fungsi yang digunakan cv2.matchShapes()

cv2.matchShapes(contour_template, contour, method, method_parameter)
  • contour_template : referensi contour yang digunakan untuk proses matching.
  • contour: contour yang akan dibandingkan.
  • method: type dari contour matching.
  • method_parameter: diisi nilai nol, tidak memiliki efek pada PpenCV untuk Python.

Berikut code untuk melakukan matching shape

import cv2
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

template = cv2.imread('template01.jpg', 0)
plt.imshow(template, cmap='gray')
target = cv2.imread('target01.jpg')
target_gray = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
plt.imshow(target_gray, cmap='gray')
ret, treshold1 = cv2.threshold(template, 127, 255, 0)
ret, treshold2 = cv2.threshold(target_gray, 127, 255, 0)

contours, hierarchy = cv2.findContours(treshold1, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)
template_contour = countours[1]

contours, hierarchy = cv2.findContours(treshold2, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
  match = cv2.matchShapes(template_contour, c, 1, 0.0)
  print (match)
  if match < 0.15:
    closest_contour = c
  else:
    closest_contour = []

cv2.drawContours(target, [closest_contour], -1, (255,0,0), 2)
plt.imshow(target)

Image download di https://drive.google.com/file/d/1cH2uKZsH1R6SIgLMPlRk-vWPHzvziJH1/view?usp=sharing

File Colab di https://colab.research.google.com/drive/1WfLe6Ttj6CYOi8KK9lhkcoToi95618VK?usp=sharing

Sharing is caring:

Leave a Comment