Opencv + Python Saving and Loading Keypoints
In this tutorial, we will write 2 python scripts -Â
To load a image, extract the keypoints and save them in a file.
To load the file saved in the previous script and draw the contours on the same image used in step 1.
For loading and saving data, we will use cPickle package. To store data in a file we use dump and to load data we use loads. The problem we have is that we cannot directly dump keypoints objects, if we try to do so, we'll get an error as shown below -Â
pickle.PicklingError: Can't pickle <type 'cv2.KeyPoint'>: it's not the same object as cv2.KeyPoint
So, we need to serialize and deserialize the keypoints data.
So, let's write code, for the first script.
SAVING THE KEYPOINTS
import cv2 import cPickle im=cv2.imread("/home/bikz05/Desktop/dataset/checkered-3.jpg") gr=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) d=cv2.FeatureDetector_create("SIFT") kp=d.detect(gr) index = [] for point in kp: temp = (point.pt, point.size, point.angle, point.response, point.octave, point.class_id) index.append(temp) # Dump the keypoints f = open("/home/bikz05/Desktop/dataset/keypoints.txt", "w") f.write(cPickle.dumps(index)) f.close()
We have saved our keypoints in keypoints.txt . Now, let's load those keypoints in a separate script and draw them on the same image.
LOADING THE KEYPOINTS
import cv2 import cPickle im=cv2.imread("/home/bikz05/Desktop/dataset/checkered-3.jpg") index = cPickle.loads(open("/home/bikz05/Desktop/dataset/keypoints.txt").read()) kp = [] for point in index: temp = cv2.KeyPoint(x=point[0][0],y=point[0][1],_size=point[1], _angle=point[2], _response=point[3], _octave=point[4], _class_id=point[5]) kp.append(temp) # Draw the keypoints imm=cv2.drawKeypoints(im, kp); cv2.imshow("Image", imm); cv2.waitKey(0)
That's it, the above script when run will display the image with all the keypoints marked on it.
RESULTS
INPUT IMAGEÂ
OUTPUT IMAGE








