如何序列化和反序列化2d numpy数组?

2024-10-01 00:29:36 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码给出了错误:

Traceback (most recent call last):
  File "test_features", line 62, in <module>
    matches = flann.knnMatch(des1,des2,k=2)
cv2.error: OpenCV(3.4.2) /Users/travis/build/skvark/opencv-python/opencv/modules/flann/src/miniflann.cpp:488: error: (-215:Assertion failed) query.type() == type && indices.type() == 4 && dists.type() == dtype in function 'runKnnSearch_'

如果删除了注释行,则该行将成功运行。向量的序列化/衍生化打破了它。打印出来的向量看起来是一样的

import cv2
import sys
from scipy import spatial

img1 = cv2.imread(sys.argv[1], 0) 

sift = cv2.xfeatures2d.SURF_create()

# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)

np.savetxt("somefile", des1, delimiter=',')   
des1 = np.genfromtxt("somefile", delimiter=',')     # This line causes knnMatch() to fail

index_params = dict(algorithm = 0, trees = 5)
search_params = dict(checks=50)

flann = cv2.FlannBasedMatcher(index_params,search_params)
matches = flann.knnMatch(des1,des2,k=2)

矢量打印出来的样子:

PRE SERIALISATION
[[-0.05004495  0.01312466  0.2218747  ...  0.02334131  0.0041258
   0.02442142]
 [-0.04608738 -0.02599513  0.07087003 ...  0.01195503  0.02044983
   0.01491418]
 [-0.04459843  0.03581402  0.06140684 ... -0.00125335  0.00398144
   0.0015579 ]
 ...
 [ 0.53539652  0.13471773  0.54491884 ...  0.009786    0.00354042
   0.01311832]
 [ 0.09226374 -0.04803251  0.10523932 ... -0.04199374  0.02648819
   0.05310054]
 [ 0.18635255 -0.0309764   0.18844464 ...  0.02269224  0.00420249
   0.02484703]]

POST SERIALISATION
[[-0.05004495  0.01312466  0.2218747  ...  0.02334131  0.0041258
   0.02442142]
 [-0.04608738 -0.02599513  0.07087003 ...  0.01195503  0.02044983
   0.01491418]
 [-0.04459843  0.03581402  0.06140684 ... -0.00125335  0.00398144
   0.0015579 ]
 ...
 [ 0.5353965   0.13471773  0.54491884 ...  0.009786    0.00354042
   0.01311832]
 [ 0.09226374 -0.04803251  0.10523932 ... -0.04199374  0.02648819
   0.05310054]
 [ 0.18635255 -0.0309764   0.18844464 ...  0.02269224  0.00420249
   0.02484703]]

Tags: inimporttypesyslineerrorparamscv2