Python cv2.NORM_L2 Examples

The following are 15 code examples of cv2.NORM_L2(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: find_obj.py    From OpenCV-Python-Tutorial with MIT License 10 votes vote down vote up
def init_feature(name):
    chunks = name.split('-')
    if chunks[0] == 'sift':
        detector = cv2.xfeatures2d.SIFT_create()
        norm = cv2.NORM_L2
    elif chunks[0] == 'surf':
        detector = cv2.xfeatures2d.SURF_create(800)
        norm = cv2.NORM_L2
    elif chunks[0] == 'orb':
        detector = cv2.ORB_create(400)
        norm = cv2.NORM_HAMMING
    elif chunks[0] == 'akaze':
        detector = cv2.AKAZE_create()
        norm = cv2.NORM_HAMMING
    elif chunks[0] == 'brisk':
        detector = cv2.BRISK_create()
        norm = cv2.NORM_HAMMING
    else:
        return None, None
    if 'flann' in chunks:
        if norm == cv2.NORM_L2:
            flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
        else:
            flann_params= dict(algorithm = FLANN_INDEX_LSH,
                               table_number = 6, # 12
                               key_size = 12,     # 20
                               multi_probe_level = 1) #2
        matcher = cv2.FlannBasedMatcher(flann_params, {})  # bug : need to pass empty dict (#1329)
    else:
        matcher = cv2.BFMatcher(norm)
    return detector, matcher 
Example #2
Source File: distance_ransac_orb.py    From douglas-quaid with GNU General Public License v3.0 6 votes vote down vote up
def filter_matrix_corners_homography(pts, max, matrix) -> (float, List):
        '''
        Compute the images of the image corners and of its center (i.e. the points you get when you apply the homography to those corners and center),
        and verify that they make sense, i.e. are they inside the image canvas (if you expect them to be)? Are they well separated from each other?
        Return a distance and a list of the transformed points
        '''

        # Transform the 4 corners thanks to the transformation matrix calculated
        transformed_pts = cv2.perspectiveTransform(pts, matrix)

        # Compute the difference between original and modified position of points
        dist = round(cv2.norm(pts - transformed_pts, cv2.NORM_L2) / max, 10)  # sqrt((X1-X2)²+(Y1-Y2)²+...)

        # Totally an heuristic (geometry based):
        if dist < 0.20:
            return dist, transformed_pts
        else:
            return 1, transformed_pts 
Example #3
Source File: distance_ransac_orb.py    From douglas-quaid with GNU General Public License v3.0 6 votes vote down vote up
def filter_matrix_corners_affine(pts, max, matrix) -> (float, List):
        '''
        Compute the images of the image corners and of its center (i.e. the points you get when you apply the homography to those corners and center),
        and verify that they make sense, i.e. are they inside the image canvas (if you expect them to be)? Are they well separated from each other?
        Return a distance and a list of the transformed points
        '''

        # Make affine transformation
        add_row = np.array([[0, 0, 1]])
        affine_matrix = np.concatenate((matrix, add_row), axis=0)
        transformed_pts_affine = cv2.perspectiveTransform(pts, affine_matrix)

        # Affine distance
        tmp_dist_affine = round(cv2.norm(pts - transformed_pts_affine, cv2.NORM_L2) / max, 10)  # sqrt((X1-X2)²+(Y1-Y2)²+...)

        # Totally an heuristic (geometry based):
        if tmp_dist_affine < 0.20:
            return tmp_dist_affine, transformed_pts_affine
        else:
            return 1, transformed_pts_affine 
Example #4
Source File: findobj.py    From airtest with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_feature(name):
    chunks = name.split('-')
    if chunks[0] == 'sift':
        detector = cv2.SIFT()
        norm = cv2.NORM_L2
    elif chunks[0] == 'surf':
        detector = cv2.SURF(800)
        norm = cv2.NORM_L2
    elif chunks[0] == 'orb':
        detector = cv2.ORB(400)
        norm = cv2.NORM_HAMMING
    else:
        return None, None
    if 'flann' in chunks:
        if norm == cv2.NORM_L2:
            flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
        else:
            flann_params= dict(algorithm = FLANN_INDEX_LSH,
                               table_number = 6, # 12
                               key_size = 12,     # 20
                               multi_probe_level = 1) #2
        matcher = cv2.FlannBasedMatcher(flann_params, {})  # bug : need to pass empty dict (#1329)
    else:
        matcher = cv2.BFMatcher(norm)
    return detector, matcher 
Example #5
Source File: find_obj.py    From airtest with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_feature(name):
    chunks = name.split('-')
    if chunks[0] == 'sift':
        detector = cv2.SIFT()
        norm = cv2.NORM_L2
    elif chunks[0] == 'surf':
        detector = cv2.SURF(800)
        norm = cv2.NORM_L2
    elif chunks[0] == 'orb':
        detector = cv2.ORB(400)
        norm = cv2.NORM_HAMMING
    else:
        return None, None
    if 'flann' in chunks:
        if norm == cv2.NORM_L2:
            flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
        else:
            flann_params= dict(algorithm = FLANN_INDEX_LSH,
                               table_number = 6, # 12
                               key_size = 12,     # 20
                               multi_probe_level = 1) #2
        matcher = cv2.FlannBasedMatcher(flann_params, {})  # bug : need to pass empty dict (#1329)
    else:
        matcher = cv2.BFMatcher(norm)
    return detector, matcher 
Example #6
Source File: feature_matcher.py    From pyslam with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, norm_type=cv2.NORM_HAMMING, cross_check = False, ratio_test=kRatioTest, type = FeatureMatcherTypes.FLANN):
        super().__init__(norm_type=norm_type, cross_check=cross_check, ratio_test=ratio_test, type=type)
        if norm_type == cv2.NORM_HAMMING:
            # FLANN parameters for binary descriptors 
            FLANN_INDEX_LSH = 6
            self.index_params= dict(algorithm = FLANN_INDEX_LSH,   # Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search
                        table_number = 6,      # 12
                        key_size = 12,         # 20
                        multi_probe_level = 1) # 2            
        if norm_type == cv2.NORM_L2: 
            # FLANN parameters for float descriptors 
            FLANN_INDEX_KDTREE = 1
            self.index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 4)  
        self.search_params = dict(checks=32)   # or pass empty dictionary                 
        self.matcher = cv2.FlannBasedMatcher(self.index_params, self.search_params)  
        self.matcher_name = 'FlannFeatureMatcher' 
Example #7
Source File: descriptors.py    From hfnet with MIT License 6 votes vote down vote up
def matching(desc1, desc2, do_ratio_test=False, cross_check=True):
    if desc1.dtype == np.bool and desc2.dtype == np.bool:
        desc1, desc2 = np.packbits(desc1, axis=1), np.packbits(desc2, axis=1)
        norm = cv2.NORM_HAMMING
    else:
        desc1, desc2 = np.float32(desc1), np.float32(desc2)
        norm = cv2.NORM_L2

    if do_ratio_test:
        matches = []
        matcher = cv2.BFMatcher(norm)
        for m, n in matcher.knnMatch(desc1, desc2, k=2):
            m.distance = 1.0 if (n.distance == 0) else m.distance / n.distance
            matches.append(m)
    else:
        matcher = cv2.BFMatcher(norm, crossCheck=cross_check)
        matches = matcher.match(desc1, desc2)
    return matches_cv2np(matches) 
Example #8
Source File: find_obj.py    From ImageAnalysis with MIT License 6 votes vote down vote up
def init_feature(name):
    chunks = name.split('-')
    if chunks[0] == 'sift':
        detector = cv2.SIFT()
        norm = cv2.NORM_L2
    elif chunks[0] == 'surf':
        detector = cv2.SURF(400)
        norm = cv2.NORM_L2
    elif chunks[0] == 'orb':
        detector = cv2.ORB(400)
        norm = cv2.NORM_HAMMING
    else:
        return None, None
    if 'flann' in chunks:
        if norm == cv2.NORM_L2:
            flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
        else:
            flann_params= dict(algorithm = FLANN_INDEX_LSH,
                               table_number = 6, # 12
                               key_size = 12,     # 20
                               multi_probe_level = 1) #2
        matcher = cv2.FlannBasedMatcher(flann_params, {})  # bug : need to pass empty dict (#1329)
    else:
        matcher = cv2.BFMatcher(norm)
    return detector, matcher 
Example #9
Source File: find_obj.py    From PyCV-time with MIT License 6 votes vote down vote up
def init_feature(name):
    chunks = name.split('-')
    if chunks[0] == 'sift':
        detector = cv2.SIFT()
        norm = cv2.NORM_L2
    elif chunks[0] == 'surf':
        detector = cv2.SURF(800)
        norm = cv2.NORM_L2
    elif chunks[0] == 'orb':
        detector = cv2.ORB(400)
        norm = cv2.NORM_HAMMING
    else:
        return None, None
    if 'flann' in chunks:
        if norm == cv2.NORM_L2:
            flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
        else:
            flann_params= dict(algorithm = FLANN_INDEX_LSH,
                               table_number = 6, # 12
                               key_size = 12,     # 20
                               multi_probe_level = 1) #2
        matcher = cv2.FlannBasedMatcher(flann_params, {})  # bug : need to pass empty dict (#1329)
    else:
        matcher = cv2.BFMatcher(norm)
    return detector, matcher 
Example #10
Source File: cv_detection_right_hand.py    From AI-Robot-Challenge-Lab with MIT License 5 votes vote down vote up
def __rotate_image_size_corrected(image, angle):
    # Calculate max size for the rotated template and image offset
    image_size_height, image_size_width = image.shape
    image_center_x = image_size_width // 2
    image_center_y = image_size_height // 2

    # Create rotation matrix
    rotation_matrix = cv2.getRotationMatrix2D((image_center_x, image_center_y), -angle, 1)

    # Apply offset
    new_image_size = int(math.ceil(cv2.norm((image_size_height, image_size_width), normType=cv2.NORM_L2)))
    rotation_matrix[0, 2] += (new_image_size - image_size_width) / 2
    rotation_matrix[1, 2] += (new_image_size - image_size_height) / 2

    # Apply rotation to the template
    image_rotated = cv2.warpAffine(image, rotation_matrix, (new_image_size, new_image_size))
    return image_rotated 
Example #11
Source File: distance_ransac_orb.py    From douglas-quaid with GNU General Public License v3.0 5 votes vote down vote up
def compute_matrix_pictures_corners():
        # Get the size of the current matching picture
        # TODO : Store somewhere the shape of the uploaded picture ?
        # h, w, d = pic1.image.shape
        # TODO : For now, just take a random size picture
        h, w, d = 1000, 1000, 3

        # Get the position of the 4 corners of the current matching picture
        pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
        max = 4 * cv2.norm(np.float32([[w, h]]), cv2.NORM_L2)

        return pts, max 
Example #12
Source File: camera_calibration.py    From camera_calibration_API with Apache License 2.0 5 votes vote down vote up
def _calc_reprojection_error(self,figure_size=(8,8),save_dir=None):
        """
        Util function to Plot reprojection error
        """
        reprojection_error = []
        for i in range(len(self.calibration_df)):
            imgpoints2, _ = cv2.projectPoints(self.calibration_df.obj_points[i], self.calibration_df.rvecs[i], self.calibration_df.tvecs[i], self.camera_matrix, self.dist_coefs)
            temp_error = cv2.norm(self.calibration_df.img_points[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)
            reprojection_error.append(temp_error)
        self.calibration_df['reprojection_error'] = pd.Series(reprojection_error)
        avg_error = np.sum(np.array(reprojection_error))/len(self.calibration_df.obj_points)
        x = [os.path.basename(p) for p in self.calibration_df.image_names]
        y_mean = [avg_error]*len(self.calibration_df.image_names)
        fig,ax = plt.subplots()
        fig.set_figwidth(figure_size[0])
        fig.set_figheight(figure_size[1])
        # Plot the data
        ax.scatter(x,reprojection_error,label='Reprojection error', marker='o') #plot before
        # Plot the average line
        ax.plot(x,y_mean, label='Mean Reprojection error', linestyle='--')
        # Make a legend
        ax.legend(loc='upper right')
        for tick in ax.get_xticklabels():
            tick.set_rotation(90)
        # name x and y axis
        ax.set_title("Reprojection_error plot")
        ax.set_xlabel("Image_names")
        ax.set_ylabel("Reprojection error in pixels")
        
        if save_dir:
            plt.savefig(os.path.join(save_dir,"reprojection_error.png"))
        
        plt.show()
        print("The Mean Reprojection Error in pixels is:  {}".format(avg_error)) 
Example #13
Source File: find_obj.py    From PyCV-time with MIT License 5 votes vote down vote up
def init_feature(name):
    chunks = name.split('-')
    if chunks[0] == 'sift':
        detector = cv2.xfeatures2d.SIFT()
        norm = cv2.NORM_L2
    elif chunks[0] == 'surf':
        detector = cv2.xfeatures2d.SURF(800)
        norm = cv2.NORM_L2
    elif chunks[0] == 'orb':
        detector = cv2.ORB(400)
        norm = cv2.NORM_HAMMING
    elif chunks[0] == 'akaze':
        detector = cv2.AKAZE()
        norm = cv2.NORM_HAMMING
    elif chunks[0] == 'brisk':
        detector = cv2.BRISK()
        norm = cv2.NORM_HAMMING
    else:
        return None, None
    if 'flann' in chunks:
        if norm == cv2.NORM_L2:
            flann_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
        else:
            flann_params= dict(algorithm = FLANN_INDEX_LSH,
                               table_number = 6, # 12
                               key_size = 12,     # 20
                               multi_probe_level = 1) #2
        matcher = cv2.FlannBasedMatcher(flann_params, {})  # bug : need to pass empty dict (#1329)
    else:
        matcher = cv2.BFMatcher(norm)
    return detector, matcher 
Example #14
Source File: core.py    From idmatch with MIT License 5 votes vote down vote up
def normalize_result(webcam, idcard):
    diff_correy = cv2.norm(settings.COREY_MATRIX, idcard, cv2.NORM_L2)
    diff_wilde = cv2.norm(settings.WILDE_MATRIX, idcard, cv2.NORM_L2)
    diff_min = diff_correy if diff_correy < diff_wilde else diff_wilde
    diff = cv2.norm(webcam, idcard, cv2.NORM_L2)
    score = float(diff) / float(diff_min)
    percentage = (1.28 - score * score * score) * 10000 / 128
    return {
        'percentage': percentage,
        'score': score,
        'message': utils.matching_message(score)
    } 
Example #15
Source File: matcher.py    From ImageAnalysis with MIT License 4 votes vote down vote up
def configure():
    global detect_scale
    global the_matcher
    global max_distance
    global min_pairs

    detect_scale = detector_node.getFloat('scale')
    detector_str = detector_node.getString('detector')
    if detector_str == 'SIFT' or detector_str == 'SURF':
        norm = cv2.NORM_L2
        max_distance = 270.0
    elif detector_str == 'ORB' or detector_str == 'Star':
        norm = cv2.NORM_HAMMING
        max_distance = 64
    else:
        log("Detector not specified or not known:", detector_str)
        quit()

    # work around a feature/bug: flann enums don't exist
    FLANN_INDEX_KDTREE = 1
    FLANN_INDEX_LSH    = 6
    if norm == cv2.NORM_L2:
        flann_params = {
            'algorithm': FLANN_INDEX_KDTREE,
            'trees': 5
        }
    else:
        flann_params = {
            'algorithm': FLANN_INDEX_LSH,
            'table_number': 6,     # 12
            'key_size': 12,        # 20
            'multi_probe_level': 1 #2
        }
    search_params = {
        'checks': 100
    }
    the_matcher = cv2.FlannBasedMatcher(flann_params, search_params)
    min_pairs = matcher_node.getFloat('min_pairs')

# Iterate through all the matches for the specified image and
# delete keypoints that don't satisfy the homography (or
# fundamental) relationship.  Returns true if match set is clean, false
# if keypoints were removed.
#
# Notice: this tends to eliminate matches that aren't all on the
# same plane, so if the scene has a lot of depth, this could knock
# out a lot of good matches.