6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-11-28

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)
6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?