Contour Retrieval Mode

By | October 25, 2021
Print Friendly, PDF & Email
1,251 Views

Sinopsis

Sering akan kita gunakan findcontours jika berhadapan untuk menentukan jumlah dan lokasi sebuah objek dalam operasi morfologi. Ada beberapa opsi yang kita gunakan mengenai Contour Retrieval Mode yaitu RETR_EXTERNAL dan RETR_TREE Perbedaan mendasar keduanya yaitu seperti berikut

Bila kita menginginkan hasil untuk sebuah objek (berlubang) hanya dikenal untuk sebagai 1 kesatuan objek, maka gunakan RETR_EXTERNAL yang artinya bahwa out boundary yang akan digunakan!

# -*- coding: utf-8 -*-
"""
Created on Sat Oct 01 11:08:15 2016

@author: mulkan

untuk mengenalkan contours
"""


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

def rgb2gray(gambar):
    return cv2.cvtColor(gambar,cv2.COLOR_BGR2GRAY)
def close(string):
    plt.close(string)
def imshow(gambar,color=False):
    plt.figure()
    if color==True:
        plt.imshow(gambar)
    else    :
        plt.imshow(gambar,cmap=plt.cm.gray)
font = cv2.FONT_HERSHEY_SIMPLEX
close('all')     
img = cv2.imread('karakter3.jpg', cv2.IMREAD_GRAYSCALE);
img_2 = img.copy()
cv2.bitwise_not(img,img_2)
ret,thresh = cv2.threshold(img_2,127,255,0)
contours_1, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
index = 1
for contour in contours_1:
    [x,y,w,h] = cv2.boundingRect(contour)      
    if w > 10 and h>10:
        cv2.rectangle(img_2,(x,y),(x+w,y+h),(255,255,0),2)
        cnt = contour
        M = cv2.moments(cnt)
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])
        #cv2.circle(img_2, (cx, cy), 7, (255, 255, 255), -2)
        cv2.putText(img_2,str(index),(cx,cy), font, 4,(255,255,255),2)
        index = index+1    
imshow(img_2,color=False),plt.title('RETR_EXTERNAL')

img_3 = img.copy()
cv2.bitwise_not(img,img_3)
contours_2, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
index = 1
for contour in contours_2:
    [x,y,w,h] = cv2.boundingRect(contour)
    if w > 10 and h>10:
        cv2.rectangle(img_3,(x,y),(x+w,y+h),(255,255,0),2)
        cnt = contour
        M = cv2.moments(cnt)
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])
        #cv2.circle(img_2, (cx, cy), 7, (255, 255, 255), -2)
        cv2.putText(img_3,str(index),(cx,cy), font, 4,(255,255,255),2)
        index = index+1    
imshow(img_3,color=False),plt.title('RETR_TREE')

 

See also  Aplikasi Scanner Kartu KTP Indonesia

Leave a Reply