Takunojiのプログラミング・プレイグラウンド(遊び場)

Javaプログラミングを基本にして、ゲーム作成に必要なことの調査結果、やったら面白そうなことなどを記載します。プログラミングのススメ的なことも記載します。プログラミングで楽しく遊ぶために色々と記載して行きます。

Python OpenCv 機械学習1 〜機械学習処理の事始め〜

前回まで、Blenderで家紋を作成しようといていました。
イメージファイルを読み込み、イメージの輪郭から座標点を取得して、
Blender上にVertexとして表示するところまで来ました。

そこから色々と試したのですが、まずは画像の解析が必要だと思い
今回に至る次第です。

とりあえずは、コードです。

ここのサイトから失敬して来ました。
翻訳機能を使用しながら読んでます。(笑)

そして、イメージファイルを変換するための処理はこちらをどうぞ

Reading and Writing Images — OpenCV 3.0.0-dev documentation

※赤文字の部分は起動しなかったので修正しました。

import cv2

import numpy as np



SZ=20

bin_n = 16 # Number of bins



svm_params = dict( kernel_type = cv2.ml.SVM_LINEAR,

                    svm_type = cv2.ml.SVM_C_SVC,

                    C=2.67, gamma=5.383 )



affine_flags = cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR



def deskew(img):

    m = cv2.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 = cv2.warpAffine(img,M,(SZ, SZ),flags=affine_flags)

    return img



def hog(img):

    gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)

    gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)

    mag, ang = cv2.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 = cv2.imread('digits.png',0)



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]



######     Now training      ########################



deskewed = [map(deskew,row) for row in train_cells]

hogdata = [map(hog,row) for row in deskewed]

trainData = np.float32(hogdata).reshape(-1,64)

responses = np.float32(np.repeat(np.arange(10),250)[:,np.newaxis])



svm = cv2.SVM()

svm.train(trainData,responses, params=svm_params)

svm.save('svm_data.dat')



######     Now testing      ########################



deskewed = [map(deskew,row) for row in test_cells]

hogdata = [map(hog,row) for row in deskewed]

testData = np.float32(hogdata).reshape(-1,bin_n*4)

result = svm.predict_all(testData)



#######   Check Accuracy   ########################

mask = result==responses

correct = np.count_nonzero(mask)

print correct*100.0/result.size

上記のコードから「Now Training」の部分を実行したいのですが。。。
以下のようなエラーが出力されました。

Traceback (most recent call last):
  File "/20180330_MchineLearning1.py", line 17, in <module>
AttributeError: module 'cv2.cv2' has no attribute 'SVM_LINEAR'
Error: Python script fail, look in the console for now...

これのでバックに手間取り今日のところは終了です。
ちなみに、原因は「opencv-contribをインストールする必要があります」
ということのようです。
OpenCvのインストールディレクトリに移動して、以下のコマンドを叩きます。

pip install opencv-contrib-gp = bpy.context.scene.grease_pencil

これで、動くと思ったのですが…

動きませんでした(笑)

いや、上記の問題は解決したのですが

Now Trainingの部分にある

train()が動かなかったのです…

 

なので、次回はpythonから横っ飛びしてc++でのOpenCvを見てみようと思います。

 

Eclipse セットアップ

  1. Java Install Eclipse〜開発ツールのインストール〜
  2. TensorFlow C++環境〜EclipseにCDTをインストール〜
  3. Setup OpenGL with Java〜JOGLを使う準備 for Eclipse〜
  4. Eclipse Meven 開発手順〜プロジェクトの作成〜
  5. Java OpenCV 環境セットアップ(on Mac)