Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What is going on with this article?
@mrsaa2000

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

More than 3 years have passed since last update.

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)
5
Help us understand the problem. What is going on with this article?
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
mrsaa2000
初心者です。ほんとに。 主にPython書きます。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
5
Help us understand the problem. What is going on with this article?