import cv2
import numpy as np
import mnist
import svm_mnist_hog_train
# ํ๋ จํด์ ์ ์ฅํ SVM ๊ฐ์ฒด ์ฝ๊ธฐ ---โ
svm = cv2.ml.SVM_load('./svm_mnist.xml')
# ์ธ์ํ ์๊ธ์จ ์ด๋ฏธ์ง ์ฝ๊ธฐ ---โก
image = cv2.imread('../img/4027.png')
cv2.imshow("image", image)
cv2.waitKey(0)
# ์ธ์ํ ์ด๋ฏธ์ง๋ฅผ ๊ทธ๋ ์ด ์ค์ผ์ผ๋ก ๋ณํ ๋ฐ ์ค๋ ์ํ๋ ์ ์ฉ ---โข
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
_, gray = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# ์ต์ธ๊ณฝ ์ปจํฌ์ด๋ง ์ฐพ๊ธฐ ---โฃ
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, \
cv2.CHAIN_APPROX_SIMPLE)[-2:]
for c in contours:
# ์ปจํฌ์ด๋ฅผ ๊ฐ์ธ๋ ์ธ์ ์ฌ๊ฐํ ๊ตฌํ๊ธฐ ---โค
(x, y, w, h) = cv2.boundingRect(c)
# ์ธ์ ์ฌ๊ฐํ์ ํฌ๊ธฐ๊ฐ ๋๋ฌด ์์๊ฒ์ ์ ์ธ ---โฅ
if w >= 5 and h >= 25:
# ์ซ์ ์์ญ๋ง roi๋ก ํ๋ณดํ๊ณ ์ฌ๊ฐํ ๊ทธ๋ฆฌ๊ธฐ ---โฆ
roi = gray[y:y + h, x:x + w]
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 1)
# ํ
์คํธ ๋ฐ์ดํ ํ์์ผ๋ก ๋ณํ ---โง
px20 = mnist.digit2data(roi, False)
# ๊ธฐ์ธ์ด์ง ์ซ์๋ฅผ ๋ฐ๋ก ์ธ์ฐ๊ธฐ ---โจ
deskewed = svm_mnist_hog_train.deskew(px20)
# ์ธ์ํ ์ซ์์ ๋ํ HOG ๋์คํฌ๋ฆฝํฐ ๊ณ์ฐ ---โฉ
hogdata = svm_mnist_hog_train.hogDesc.compute(deskewed)
testData = np.float32(hogdata).reshape(-1, hogdata.shape[0])
# ๊ฒฐ๊ณผ ์์ธกํด์ ํ์ ---โช
ret, result = svm.predict(testData)
cv2.putText(image, "%d"%result[0], (x , y + 155), \
cv2.FONT_HERSHEY_COMPLEX, 2, (255, 0, 0), 2)
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
์คํ๊ฒฐ๊ณผ