“KeyPoint”类型的对象不是JSON可序列化的opencv

时间:2018-02-22 01:03:04

标签: python json opencv sift keypoint

我正在尝试使用图像关键点和描述符作为json对象发送服务器请求...这是我的代码..

import cv2 
import requests
import json

imgDetail = {'keypoints': '', 'descriptor': ''}
sift = cv2.xfeatures2d.SIFT_create()

img = cv2.imread('images/query.jpg', 0)  
kp, des = sift.detectAndCompute(img, None)

des = des.tolist()

imgDetail['keypoints'] = kp  
imgDetail['descriptor'] = des

jsonDump = json.dumps(imgDetail)

resp = requests.post("http://localhost:5000", json=jsonDump, headers={'content-type': 'application/json'})

但它给了我以下错误...........

Traceback (most recent call last):
File "E:/python projects/mawa/image.py", line 23, in <module>
jsonDump = json.dumps(imgDetail)
File "E:\Programs\Python\Python36\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "E:\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "E:\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0)
File "E:\Programs\Python\Python36\lib\json\encoder.py", line 180, in default o.__class__.__name__)

TypeError: Object of type 'KeyPoint' is not JSON serializable

任何人都可以为此提供解决方案。先谢谢

1 个答案:

答案 0 :(得分:0)

如果您看到 kp 变量,则它是 KeyPoint 实例的列表。 即:kp看起来像[<KeyPoint 0x109f6da50>, <KeyPoint 0x109f6dd50>, <KeyPoint 0x10a1b2060>, <KeyPoint 0x10a1b2090>, <KeyPoint 0x10a1b20c0>, <KeyPoint 0x10a1b2030>, <KeyPoint 0x10a1a0a80>, <KeyPoint 0x10a1a0660>,...]

当您尝试转储imgDetail时,关键点(即:kp)会出错,因为KeyPoint实例无法序列化。

您需要遍历kp列表并将实例更改为dict。

imgDetail['keypoints'] = [{'angle': k.angle, 'response': k.response} for k in kp]

KeyPoint类没有 tolist() __ dict __ ()方法。所以你可能需要创建自己的dict并传递给json.dumps()。