Pickling cv2.KeyPoint causes PicklingError

后端 未结 3 1702
南笙
南笙 2020-12-02 23:35

I want to search surfs in all images in a given directory and save their keypoints and descriptors for future use. I decided to use pickle as shown below:

#!         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 00:30

    A similar solution to the one provided by Poik. Just call this once before pickling.

    def patch_Keypoint_pickiling(self):
        # Create the bundling between class and arguments to save for Keypoint class
        # See : https://stackoverflow.com/questions/50337569/pickle-exception-for-cv2-boost-when-using-multiprocessing/50394788#50394788
        def _pickle_keypoint(keypoint): #  : cv2.KeyPoint
            return cv2.KeyPoint, (
                keypoint.pt[0],
                keypoint.pt[1],
                keypoint.size,
                keypoint.angle,
                keypoint.response,
                keypoint.octave,
                keypoint.class_id,
            )
        # C++ Constructor, notice order of arguments : 
        # KeyPoint (float x, float y, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
    
        # Apply the bundling to pickle
        copyreg.pickle(cv2.KeyPoint().__class__, _pickle_keypoint)
    

    More than for the code, this is for the incredibly clear explanation available there : https://stackoverflow.com/a/50394788/11094914

    Please note that if you want to expand this idea to other "unpickable" class of openCV, you only need to build a similar function to "_pickle_keypoint". Be sure that you store attributes in the same order as the constructor. You can consider copying the C++ constructor, even in Python, as I did. Mostly C++ and Python constructors seems not to differ too much.

    I has issue with the "pt" tuple. However, a C++ constructor exists for X and Y separated coordinates, and thus, allow this fix/workaround.

提交回复
热议问题