List

Pada kesempatan ini kita ingin mendeteksi sebuah bentuk kotak dari sebuah contoh image. Download image berikut dan simpan dalam direktori D:\Project\Latihan

buatlah sebuah kode sederhana berikut ini dan simpan dalam nama shape.py.

# Sumber https://pythontips.com/2015/03/11/a-guide-to-finding-books-in-images-using-python-and-opencv/ # import the necessary packages import numpy as np import cv2 # load the image, di ubah ke grayscale image = cv2.imread("example.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (3, 3), 0) #cv2.imshow("Gray", gray) # Deteksi Tepi edged = cv2.Canny(gray, 10, 250) #cv2.imshow("Edged", edged) # construct and apply a closing kernel to 'close' gaps between 'white' # pixels kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) #cv2.imshow("Closed", closed) # find contours (i.e. the 'outlines') in the image and initialize the # total number of books found (cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) total = 0 # Looping dalam contours for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) # if the approximated contour has four points, then assume that the # contour is a book -- a book is a rectangle and thus has four vertices if len(approx) == 4: cv2.drawContours(image, [approx], -1, (0, 255, 0), 4) total += 1 # Menampilkan hasil print ("Terdapat gambar buku sejumlah : ".format(total)) cv2.imshow("Output", image) cv2.waitKey(0)

Jalankan dengan perintah python shape.py, akan didapatkan hasil seperti berikut ini

di command promp akan ditampilkan “Terdapat gambar buku sejumlah : 4