2017-09-13 92 views
0

我试图插入一个128d向量,我在包含多个面向MongoDB集合(向量)的图像中生成了一张脸。我使用着名的dlib库来生成128d向量。当我尝试将这个向量插入到mongodb集合中时,我得到了“无法编码对象错误”。错误如下。如何在Python中使用pymongo插入128d向量到MongoDB数据库

File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 610, in _raise_connection_failure 
    raise error 
bson.errors.InvalidDocument: Cannot encode object: dlib.vector([-0.078586, 0.0277601, 0.02961, 0.0263595, -0.0423636, -0.0593996, -0.0353243, -0.157486, 0.169706, -0.0115421, 0.215085, 0.0998522, -0.230498, -0.0380571, -0.0662888, 0.0504411, -0.0678306, -0.0943572, -0.123836, -0.0879753, -0.0753862, 0.000870723, 0.0786572, 0.0651935, -0.0732055, -0.294396, -0.108001, -0.122248, 0.0798309, -0.0558914, -0.00326786, -0.00399151, -0.2, -0.0997921, 0.0628334, -0.0214193, -0.0168998, -0.00545083, 0.260324, -0.0224971, -0.137103, 0.0410911, 0.0381873, 0.228159, 0.101016, 0.0886697, 0.0711474, -0.12792, 0.0942142, -0.139165, 0.0716797, 0.147697, 0.0957785, -0.00807651, 0.0464634, -0.18575, 0.00923027, 0.0976636, -0.24552, 0.145688, 0.0765331, -0.0418556, -0.0641425, 0.00440269, 0.181549, 0.134916, -0.0709987, -0.182558, 0.168222, -0.238072, 0.041242, 0.10536, -0.0684752, -0.199106, -0.233173, 0.00511742, 0.417584, 0.176161, -0.11886, 0.0600367, -0.16006, -0.0130243, 0.0705707, -0.0569518, -0.136003, 0.0180192, -0.0785295, -0.00361975, 0.212427, 0.0941055, -0.064303, 0.178207, 0.00868456, 0.0107785, 0.0646739, 0.0319019, -0.11788, -0.046726, -0.129802, 0.00561518, -0.0292626, -0.0468726, 0.132234, 0.00913511, -0.159603, 0.0933984, -0.0159525, -0.0224207, 0.00211018, 0.119351, -0.154814, -0.0764414, 0.170755, -0.303818, 0.304808, 0.111342, 0.066825, 0.12282, 0.0600208, 0.0596608, -0.0402757, -0.017425, -0.0706421, -0.102285, 0.0109511, -0.0790169, 0.18963, 0.0300883]) 

我曾尝试将此128d向量转换为列表,np数组但没有帮助。

有没有办法插入128d向量,因为它是在MongoDB中使用pymongo,因为我想比较128d向量的相似度以后。

我试图向mongodb插入向量的代码部分如下。

face_descriptor = facerec.compute_face_descriptor(img, shape) 
     print(face_descriptor) 
     result = db.vectors.insert_one({"image": face_descriptor, "paths" : f}) 

你的帮助真的很感谢。谢谢。

回答

0

PyMongo方法insert_one()不接受任意对象。请参阅PyMongo Tutorial: Inserting a Document

您应该将矢量对象转换为文档。请参阅MongoDB Data Modelling Introduction作为入门指南。 例如,你可以设计如下:

doc = { '0': [-0.078586, 0.0277601, 0.02961, 0.0263595], 
     '1': [-0.078586, 0.0277601, 0.02961, 0.0263595] } 

确保考虑到你如何去以后查询。以后可以用来检索数据的领域是什么?另请参阅MongoDB Indexes

替代方案也可以存储对象的Python pickle。例如:

doc = { 'queryable_value': <pickle> } 

正如你可以看到有各种方式来设计架构,玩不同的设计,看看有什么最适合你的应用程序。

+0

我首先转化所述载体引入numpy的数组,然后到一个python列表。它解决了这个问题。是的,我稍后再询问它们,以检查它们的相似性,并且完全符合我的要求。感谢您的建议/链接。 –

0

我只是将它转换为一个列表以保存在数据库中。

face_descriptor_list = list(facerec.compute_face_descriptor(img, shape)) 
db.vectors.insert_one({"image": face_descriptor_list, "paths" : f}) 

检索:

从DB获取它之后,转换回DLIB矢量

img_data = db.vectors.find_one({...}) 
face_descriptor = dlib.vector(img_data['image']) 
相关问题