6
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

Python3版OpenCVのKeyPointをファイルに書き出す

Pickleモジュールを使いKeyPointをファイルに書き出そうとしたところエラーが出たので
その時の対応策のメモです。
検索すれば割とすぐ出てきたのであまり需要はないかもしれませんが一応。

環境

  • Python 3.5.2
  • OpenCV 3.1.0

参考URL

http://stackoverflow.com/questions/26501193/opencv-python-find-a-code-for-writing-keypoins-to-a-file
ここでの回答とほぼ同じです

失敗例

out_kp_and_des.py
import cv2
import pickle


img = cv2.imread('XXXX.jpg')
detector = cv2.AKAZE_create()
# keypointsとdescriptors
kp, des = detector.detectAndCompute(img, None)

with open('XXXX.pickle', mode='wb') as f:
    pickle.dump((kp, des), f)

KeyPointをそのままPickle化しようとするとPicklingError: Can't pickle <class 'cv2.KeyPoint'>: it's not the same object as cv2.KeyPointのようなエラーが出ます。

解決策

out_kp_and_des.py
import cv2
import pickle


img = cv2.imread('XXXX.jpg')
detector = cv2.AKAZE_create()
kp, des = detector.detectAndCompute(img, None)

index = []
for p in kp:
    temp = (p.pt, p.size, p.angle, p.response, p.octave, p.class_id)
    index.append(temp)
with open('XXXX.pickle', mode='wb') as f:
    pickle.dump((index, des), f)

KeyPointのアトリビュートを取り出してそれをリストに入れてPickle化って感じになります。
ファイル読み込みは以下のような感じです。

load_kp_and_des.py
import cv2
import pickle


with open('XXXX.pickle', mode='rb') as f:
    index, des = pickle.load(f)
kp = []
for p in index:
    temp = cv2.KeyPoint(x=p[0][0], y=p[0][1], _size=p[1], _angle=p[2],
                        _response=p[3], _octave=p[4], _class_id=p[5])
    kp.append(temp)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
6
Help us understand the problem. What are the problem?