将提取的SURF描述符和关键点存储在* .npy文件中

时间:2014-09-05 07:19:08

标签: python opencv

我是Python和opencv的新手。我设法获取描述符以及在图像上绘制关键点,但我需要知道如何存储它以供将来比较。

2 个答案:

答案 0 :(得分:3)

您可以关注this link。我个人使用以下代码加载和保存SURF描述符

def read_features_from_file(filename):
    """ Read feature properties and return in matrix form. """
    if os.path.getsize(filename) <= 0:
        return np.array([]), np.array([])
    f = np.load(filename)
    if f.size == 0:
        return np.array([]), np.array([])
    f = np.atleast_2d(f)
    return f[:,:7], f[:,7:] # feature locations, descriptors

def write_features_to_file(filename, locs, desc):
    np.save(filename, np.hstack((locs,desc)))

[编辑]:添加更多代码和用法示例:

def pack_keypoint(keypoints, descriptors):
    kpts = np.array([[kp.pt[0], kp.pt[1], kp.size,
                  kp.angle, kp.response, kp.octave,
                  kp.class_id]
                 for kp in keypoints])
    desc = np.array(descriptors)
    return kpts, desc

def unpack_keypoint(array):
    try:
        kpts = array[:,:7]
        desc = array[:,7:]
        keypoints = [cv2.KeyPoint(x, y, _size, _angle, _response, int(_octave), int(_class_id))
                 for x, y, _size, _angle, _response, _octave, _class_id in list(kpts)]
        return keypoints, np.array(desc)
    except(IndexError):
        return np.array([]), np.array([])

def process_image(imagename, resultname):
    img = cv2.imread(imagename, 0)
    k = surf.detect(img, None)
    if len(k) > 0:
        k, des = surf.compute(img, k)
    else:
        des = []
    k, des = pack_keypoint(k, des) #
    write_features_to_file(resultname, k, des)

答案 1 :(得分:0)

这对我有用:

# Initiate SURF detector
surf = cv2.xfeatures2d.SURF_create()
surf.setHessianThreshold(10000)

img1 = cv2.imread("images/85_hires.png", 4)
kp1, des1 = surf.detectAndCompute(img1, None)
img2 = cv2.imread("images/85_hires.png", 4)
kp2, des2 = surf.detectAndCompute(img2, None)

np.savetxt("test.txt", des2)

new = np.loadtxt("test.txt").astype('float32')
print(getImageScore(des1, des2))
print(getImageScore(des1, new))