简体   繁体   English

如何在python中保存词袋数据?

[英]How to save bag of words datas in python?

Here is my code :这是我的代码:

sift=cv2.xfeatures2d.SIFT_create()
descriptors_unclustered=[]
dictionarysize=800
BOW=cv2.BOWKmeansTrainer(dictionarysize)
for p in training-paths :
    kp,dsc=sift.detectAndCompute(image,None)
    BOW.add(dsc)

dictionary=BOW.cluster()
bowdiction=cv2.BOWImgDescriptorExtractor(sift, cv2.BFMatcher(cv2.NORM_L2))
bowdiction.setvocabulary(dictionary)

I want to save this bowdiction data to use it later.我想保存这个弓词数据以备后用。 I dont want to wait every time for these calculations so how can I save this data ?我不想每次都等待这些计算,所以我该如何保存这些数据?

Use pickle for this为此使用泡菜

  1. Save BOW to pickle:保存 BOW 到泡菜:

     import pickle sift=cv2.xfeatures2d.SIFT_create() descriptors_unclustered=[] dictionarysize=800 BOW=cv2.BOWKmeansTrainer(dictionarysize) for p in training-paths : kp,dsc=sift.detectAndCompute(image,None) BOW.add(dsc) with open('bow_pickle.pickle', 'wb') as f: pickle.dump(f)
  2. Return the data from pickle:从pickle返回数据:

     import pickle with open('bow_pickle.pickle', 'rb') as f: BOW = pickle.load(f) dictionary=BOW.cluster() bowdiction=cv2.BOWImgDescriptorExtractor(sift,cv2.BFMatcher(cv2.NORM_L2)) bowdiction.setvocabulary(dictionary)

I know this is old.我知道这是旧的。 But as I came here and saw no answer, I tried a few things and this worked:但是当我来到这里并没有看到任何答案时,我尝试了一些事情并且这奏效了:

dictionary=BOW.cluster() is what takes most time. dictionary=BOW.cluster()是最耗时的。 So you only need to save dictionary.所以你只需要保存字典。 Which is just an ndarray:这只是一个 ndarray:

np.savetxt('bow_dict.txt', dictionary)

loaded_dictionary = np.loadtxt('bow_dict.txt')

And then proceed with然后继续

bowdiction=cv2.BOWImgDescriptorExtractor(sift,cv2.BFMatcher(cv2.NORM_L2))
bowdiction.setvocabulary(loaded_dictionary)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM