OpenCV 4.13.0
Open Source Computer Vision
読み込み中...
検索中...
見つかりません
🤖 AIによる機械翻訳(非公式) — これは OpenCV 4.13.0 公式リファレンス(英語)を AI (Claude) で自動翻訳したものです。訳に誤りを含む場合があります。正確な情報は 公式英語版(原文) を参照してください。
SVMによる手書き文字のOCR

目的

この章では

  • ここでは手書き文字のOCRを再び取り上げるが、kNNではなくSVMを用いる。

手書き数字のOCR

kNNでは、ピクセルの輝度をそのまま特徴ベクトルとして使用した。今回は特徴ベクトルとして Histogram of Oriented Gradients (HOG) を使用する。

ここでは、HOGを求める前に、画像の2次モーメントを用いて画像の傾きを補正する。そこでまず、数字画像を受け取って傾きを補正する関数 deskew() を定義する。以下が deskew() 関数である。

def deskew(img):
m = cv.moments(img)
if abs(m['mu02']) < 1e-2:
return img.copy()
skew = m['mu11']/m['mu02']
M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
img = cv.warpAffine(img,M,(SZ, SZ),flags=affine_flags)
return img

以下の画像は、上記の deskew 関数をゼロの画像に適用したものを示している。左の画像が元画像で、右の画像が傾き補正後の画像である。

image

次に、各セルのHOG記述子を求める必要がある。そのために、各セルのSobel微分をX方向とY方向で求める。次に、各ピクセルにおける勾配の大きさと方向を求める。この勾配は16個の整数値に量子化される。この画像を4つのサブ正方形に分割する。各サブ正方形について、その大きさで重み付けした方向のヒストグラム(16ビン)を計算する。こうして各サブ正方形から16個の値を含むベクトルが得られる。4つのサブ正方形からの4つのベクトルを合わせると、64個の値を含む特徴ベクトルが得られる。これがデータの学習に使用する特徴ベクトルである。

def hog(img):
gx = cv.Sobel(img, cv.CV_32F, 1, 0)
gy = cv.Sobel(img, cv.CV_32F, 0, 1)
mag, ang = cv.cartToPolar(gx, gy)
bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16)
bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:]
mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
hist = np.hstack(hists) # hist is a 64 bit vector
return hist

最後に、前の例と同様に、大きなデータセットを個々のセルに分割することから始める。各数字について、250セルを学習データに、残りの250セルをテスト用に確保する。完全なコードは以下に示すが、こちら からダウンロードすることもできる。

#!/usr/bin/env python
import cv2 as cv
import numpy as np
SZ=20
bin_n = 16 # Number of bins
affine_flags = cv.WARP_INVERSE_MAP|cv.INTER_LINEAR
def deskew(img):
m = cv.moments(img)
if abs(m['mu02']) < 1e-2:
return img.copy()
skew = m['mu11']/m['mu02']
M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
img = cv.warpAffine(img,M,(SZ, SZ),flags=affine_flags)
return img
def hog(img):
gx = cv.Sobel(img, cv.CV_32F, 1, 0)
gy = cv.Sobel(img, cv.CV_32F, 0, 1)
mag, ang = cv.cartToPolar(gx, gy)
bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16)
bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:]
mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]
hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]
hist = np.hstack(hists) # hist is a 64 bit vector
return hist
img = cv.imread(cv.samples.findFile('digits.png'),0)
if img is None:
raise Exception("we need the digits.png image from samples/data here !")
cells = [np.hsplit(row,100) for row in np.vsplit(img,50)]
# First half is trainData, remaining is testData
train_cells = [ i[:50] for i in cells ]
test_cells = [ i[50:] for i in cells]
deskewed = [list(map(deskew,row)) for row in train_cells]
hogdata = [list(map(hog,row)) for row in deskewed]
trainData = np.float32(hogdata).reshape(-1,64)
responses = np.repeat(np.arange(10),250)[:,np.newaxis]
svm = cv.ml.SVM_create()
svm.setKernel(cv.ml.SVM_LINEAR)
svm.setType(cv.ml.SVM_C_SVC)
svm.setC(2.67)
svm.setGamma(5.383)
svm.train(trainData, cv.ml.ROW_SAMPLE, responses)
svm.save('svm_data.dat')
deskewed = [list(map(deskew,row)) for row in test_cells]
hogdata = [list(map(hog,row)) for row in deskewed]
testData = np.float32(hogdata).reshape(-1,bin_n*4)
result = svm.predict(testData)[1]
mask = result==responses
correct = np.count_nonzero(mask)
print(correct*100.0/result.size)
void cartToPolar(InputArray x, InputArray y, OutputArray magnitude, OutputArray angle, bool angleInDegrees=false)
Calculates the magnitude and angle of 2D vectors.
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
Loads an image from a file.
void Sobel(InputArray src, OutputArray dst, int ddepth, int dx, int dy, int ksize=3, double scale=1, double delta=0, int borderType=BORDER_DEFAULT)
Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator.
Moments moments(InputArray array, bool binaryImage=false)
Calculates all of the moments up to the third order of a polygon or rasterized shape.
void warpAffine(InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar &borderValue=Scalar())
Applies an affine transformation to an image.

この手法では、ほぼ94%の精度が得られた。SVMの各種パラメータに異なる値を試して、より高い精度が得られるか確認してみるとよい。あるいは、この分野の技術論文を読んで、それらを実装してみるのもよいだろう。

追加リソース

  1. Histograms of Oriented Gradients Video

演習

  1. OpenCVのサンプルには digits.py が含まれており、上記の手法を少し改良してより良い結果を得ている。参考文献も含まれている。これを確認して理解しよう。