简体   繁体   中英

Store the extracted SURF descriptors and keypoints in *.npy file

I'm new to Python and opencv. I manage to get the descriptors as well as draw the keypoints onto the image but I need to know how to store it for future comparison.

You may follow this link . I personally use the following code to load and save SURF descriptors

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)))

[EDIT]: add more codes and usage example:

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)

this worked for me:

# 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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