酸洗 cv2.KeyPoint 导致 PicklingError [英] Pickling cv2.KeyPoint causes PicklingError
问题描述
我想在给定目录中的所有图像中搜索 surfs 并保存它们的关键点和描述符以备将来使用.我决定使用pickle,如下所示:
I want to search surfs in all images in a given directory and save their keypoints and descriptors for future use. I decided to use pickle as shown below:
#!/usr/bin/env python
import os
import pickle
import cv2
class Frame:
def __init__(self, filename):
surf = cv2.SURF(500, 4, 2, True)
self.filename = filename
self.keypoints, self.descriptors = surf.detect(cv2.imread(filename, cv2.CV_LOAD_IMAGE_GRAYSCALE), None, False)
if __name__ == '__main__':
Fdb = open('db.dat', 'wb')
base_path = "img/"
frame_base = []
for filename in os.listdir(base_path):
frame_base.append(Frame(base_path+filename))
print filename
pickle.dump(frame_base,Fdb,-1)
Fdb.close()
当我尝试执行时,出现以下错误:
When I try to execute, I get a following error:
File "src/pickle_test.py", line 23, in <module>
pickle.dump(frame_base,Fdb,-1)
...
pickle.PicklingError: Can't pickle <type 'cv2.KeyPoint'>: it's not the same object as cv2.KeyPoint
有谁知道,这是什么意思以及如何解决?我使用的是 Python 2.6 和 Opencv 2.3.1
Does anybody know, what does it mean and how to fix it? I am using Python 2.6 and Opencv 2.3.1
非常感谢
推荐答案
问题是您无法将 cv2.KeyPoint 转储到 pickle 文件.我遇到了同样的问题,并设法通过在使用 Pickle 转储它们之前自己序列化和反序列化关键点来解决它.
The problem is that you cannot dump cv2.KeyPoint to a pickle file. I had the same issue, and managed to work around it by essentially serializing and deserializing the keypoints myself before dumping them with Pickle.
所以用元组表示每个关键点及其描述符:
So represent every keypoint and its descriptor with a tuple:
temp = (point.pt, point.size, point.angle, point.response, point.octave,
point.class_id, desc)
将所有这些点附加到一些列表中,然后用 Pickle 转储.
Append all these points to some list that you then dump with Pickle.
然后当你想再次检索数据时,用Pickle加载所有数据:
Then when you want to retrieve the data again, load all the data with Pickle:
temp_feature = cv2.KeyPoint(x=point[0][0],y=point[0][1],_size=point[1], _angle=point[2],
_response=point[3], _octave=point[4], _class_id=point[5])
temp_descriptor = point[6]
使用上述代码从这些数据中创建一个 cv2.KeyPoint,然后您可以使用这些点来构建特征列表.
Create a cv2.KeyPoint from this data using the above code, and you can then use these points to construct a list of features.
我怀疑有一种更简洁的方法可以做到这一点,但以上对我来说效果很好(而且速度很快).您可能需要稍微处理一下您的数据格式,因为我的功能存储在特定于格式的列表中.我试图在其通用基础上使用我的想法来呈现上述内容.我希望这可以帮助你.
I suspect there is a neater way to do this, but the above works fine (and fast) for me. You might have to play around with your data format a bit, as my features are stored in format-specific lists. I tried to present the above using my idea at its generic base. I hope that this may help you.
这篇关于酸洗 cv2.KeyPoint 导致 PicklingError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!