当前位置: 首页>>代码示例>>Python>>正文


Python cv2.findHomography方法代码示例

本文整理汇总了Python中cv2.findHomography方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.findHomography方法的具体用法?Python cv2.findHomography怎么用?Python cv2.findHomography使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cv2的用法示例。


在下文中一共展示了cv2.findHomography方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: buildPano

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def buildPano(defished):
    # Build the panoram from the defisheye images
    offsets = []
    finalWidth = defished[0].width
    # Get the offsets and calculte the final size
    for i in range(0, len(defished) - 1):
        H, M, offset = findHomography(defished[i], defished[i + 1])
        dfw = defished[i + 1].width
        offsets.append(offset)
        finalWidth += int(dfw - offset[0])

    final = Image((finalWidth, defished[0].height))
    final = final.blit(defished[0], pos=(0, 0))
    xs = 0
    # blit subsequent images into the final image
    for i in range(0, len(defished) - 1):
        w = defished[i + 1].width
        h = defished[i + 1].height
        mask = constructMask(w, h, offsets[i][0])
        xs += int(w - offsets[i][0])
        final = final.blit(defished[i + 1], pos=(xs, 0), alphaMask=mask)
    return final 
开发者ID:cynricfu,项目名称:dual-fisheye-video-stitching,代码行数:24,代码来源:fisheye2equirec.py

示例2: copyTextureTest

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def copyTextureTest(options):
    testdir = 'texture_test/'
    for index in xrange(1):
        planes = np.load(testdir + '/planes_' + str(index) + '.npy')
        image = cv2.imread(testdir + '/image_' + str(index) + '.png')
        segmentations = np.load(testdir + '/segmentations_' + str(index) + '.npy')
        segmentation = np.argmax(segmentations, axis=2)
        plane_depths = calcPlaneDepths(planes, WIDTH, HEIGHT)
        
        textureImage = cv2.imread('../textures/texture_0.jpg')
        textureImage = cv2.resize(textureImage, (WIDTH, HEIGHT), interpolation=cv2.INTER_LINEAR)
        floorPlaneIndex = findFloorPlane(planes, segmentation)
        if floorPlaneIndex == -1:
            continue
        mask = segmentation == floorPlaneIndex
        uv = findCornerPoints(planes[floorPlaneIndex], plane_depths[:, :, floorPlaneIndex], mask)
        source_uv = np.array([[0, 0], [0, HEIGHT], [WIDTH, 0], [WIDTH, HEIGHT]])

        h, status = cv2.findHomography(source_uv, uv)
        textureImageWarped = cv2.warpPerspective(textureImage, h, (WIDTH, HEIGHT))
        image[mask] = textureImageWarped[mask]
        cv2.imwrite(testdir + '/' + str(index) + '_texture.png', textureImageWarped)
        cv2.imwrite(testdir + '/' + str(index) + '_result.png', image)
        continue
    return 
开发者ID:art-programmer,项目名称:PlaneNet,代码行数:27,代码来源:CopyTexture.py

示例3: findHomography

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def findHomography(image_1_kp, image_2_kp, matches):
    image_1_points = np.zeros((len(matches), 1, 2), dtype=np.float32)
    image_2_points = np.zeros((len(matches), 1, 2), dtype=np.float32)

    for i in range(0,len(matches)):
        image_1_points[i] = image_1_kp[matches[i].queryIdx].pt
        image_2_points[i] = image_2_kp[matches[i].trainIdx].pt


    homography, mask = cv2.findHomography(image_1_points, image_2_points, cv2.RANSAC, ransacReprojThreshold=2.0)

    return homography


#
#   Align the images so they overlap properly...
#
# 
开发者ID:cmcguinness,项目名称:focusstack,代码行数:20,代码来源:FocusStack.py

示例4: frame_homography

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def frame_homography(totalPts, homTh):
    """
    Filter foreground points i.e. the outlier points found by fitting
    homography using RANSAC
    Input:
        totalPts: (numAllPoints, 4): x0, y0, x1, y1
        fgPts: (numAllPoints, 4): x0, y0, x1, y1
    """
    if totalPts.ndim != 2 or totalPts.shape[0] < 8 or homTh < 0:
        return totalPts

    import cv2
    p1 = totalPts[:, :2].astype('float')
    p2 = totalPts[:, 2:4].astype('float')
    _, status = cv2.findHomography(
        p1, p2, cv2.RANSAC, ransacReprojThreshold=homTh)
    fgPts = totalPts[status[:, 0] == 0, :]
    return fgPts 
开发者ID:pathak22,项目名称:videoseg,代码行数:20,代码来源:dm_tracker.py

示例5: getHomography

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def getHomography(self, rightKps, rightDescriptor):
        rawMatches = self.matcher.knnMatch(self.leftDescriptor, rightDescriptor, 2)
        matches = []

        for m in rawMatches:
            if(len(m)==2 and m[0].distance < m[1].distance*self.ratio):
                matches.append((m[0].trainIdx, m[0].queryIdx))

        if(len(matches) >=4):
            # print(matches)
            ptsB = np.float32([self.leftKps[i] for (_, i) in matches])
            ptsA = np.float32([rightKps[i] for (i, _) in matches])

            # ptsB = H*ptsA
            H, status = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, self.reprojThresh)
            return H

        return None 
开发者ID:shekkizh,项目名称:ImageProcessingProjects,代码行数:20,代码来源:StitchingFromVideo.py

示例6: compute_homography_error

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def compute_homography_error(kpts1, kpts2, matches, shape2, H_gt):
    if matches.shape[0] == 0:
        return False, None
    kpts1 = kpts1[matches[:, 0]]
    kpts2 = kpts2[matches[:, 1]]
    H, _ = cv2.findHomography(kpts2, kpts1, cv2.RANSAC, 3.0)
    if H is None:
        return None

    w, h = shape2
    corners2 = to_homogeneous(
        np.array([[0, 0], [0, h-1], [w-1, h-1], [w-1, 0]]))
    corners1_gt = np.dot(corners2, np.transpose(H_gt))
    corners1_gt = corners1_gt[:, :2] / corners1_gt[:, 2:]
    corners1 = np.dot(corners2, np.transpose(H))
    corners1 = corners1[:, :2] / corners1[:, 2:]
    mean_dist = np.mean(np.linalg.norm(corners1 - corners1_gt, axis=1))
    return mean_dist 
开发者ID:ethz-asl,项目名称:hfnet,代码行数:20,代码来源:local_descriptors.py

示例7: findHomography

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def findHomography(self, i1, i2, pairs):
        src = []
        dst = []
        for pair in pairs:
            c1 = i1.coord_list[pair[0]]
            c2 = i2.coord_list[pair[1]]
            src.append( c1 )
            dst.append( c2 )
        #H, status = cv2.findHomography(np.array([src]).astype(np.float32),
        #                               np.array([dst]).astype(np.float32),
        #                               cv2.RANSAC, 5.0)
        H, status = cv2.findHomography(np.array([src]).astype(np.float32),
                                       np.array([dst]).astype(np.float32))
        #print str(affine)
        return H

    # compare against best 'placed' image (averaging transform
    # matrices together directly doesn't do what we want) 
开发者ID:UASLab,项目名称:ImageAnalysis,代码行数:20,代码来源:Placer.py

示例8: tran_matrix

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def tran_matrix(src_img, src_points, dst_img, dst_points):
    h = cv2.findHomography(dst_points, src_points)
    output = cv2.warpAffine(dst_img, h[0][:2], (src_img.shape[1], src_img.shape[0]),
                            borderMode=cv2.BORDER_TRANSPARENT,
                            flags=cv2.WARP_INVERSE_MAP)

    return output 
开发者ID:gyp03,项目名称:yry,代码行数:9,代码来源:morpher.py

示例9: match

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def match(self, key_a, fea_a, key_b, fea_b):
		# Compute the raw matches and initialize the list of actual matches
		matcher = cv2.DescriptorMatcher_create(self.distance_method)
		raw_matches = matcher.knnMatch(fea_b, fea_a, 2)
		matches = []

		# Loop over the raw matches
		for match in raw_matches:
			# Ensure the distance is within a certain ratio of each other
			if len(match) == 2 and match[0].distance < match[1].distance * self.ratio:
				matches.append((match[0].trainIdx, match[0].queryIdx))

		# Check to see if there are enough matches to process
		if len(matches) > self.min_matches:
			# Construct the two sets of points
			poi_a = np.float32([key_a[i] for (i, _) in matches])
			poi_b = np.float32([key_b[j] for (_, j) in matches])

			# Compute the homography between the two sets of points and compute the ratio of matched points
			(_, status) = cv2.findHomography(poi_a, poi_b, cv2.RANSAC, 4.0)

			# Return the ratio of the number of matched keypoints to the total number of keypoints
			return float(status.sum()) / status.size

		# No matches were found
		return -1.0 
开发者ID:hsSam,项目名称:PracticalPythonAndOpenCV_CaseStudies,代码行数:28,代码来源:covermatcher.py

示例10: track

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def track(self, frame):
        '''Returns a list of detected TrackedTarget objects'''
        self.frame_points, frame_descrs = self.detect_features(frame)
        if len(self.frame_points) < MIN_MATCH_COUNT:
            return []
        matches = self.matcher.knnMatch(frame_descrs, k = 2)
        matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < m[1].distance * 0.75]
        if len(matches) < MIN_MATCH_COUNT:
            return []
        matches_by_id = [[] for _ in xrange(len(self.targets))]
        for m in matches:
            matches_by_id[m.imgIdx].append(m)
        tracked = []
        for imgIdx, matches in enumerate(matches_by_id):
            if len(matches) < MIN_MATCH_COUNT:
                continue
            target = self.targets[imgIdx]
            p0 = [target.keypoints[m.trainIdx].pt for m in matches]
            p1 = [self.frame_points[m.queryIdx].pt for m in matches]
            p0, p1 = np.float32((p0, p1))
            H, status = cv2.findHomography(p0, p1, cv2.RANSAC, 3.0)
            status = status.ravel() != 0
            if status.sum() < MIN_MATCH_COUNT:
                continue
            p0, p1 = p0[status], p1[status]

            x0, y0, x1, y1 = target.rect
            quad = np.float32([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
            quad = cv2.perspectiveTransform(quad.reshape(1, -1, 2), H).reshape(-1, 2)

            track = TrackedTarget(target=target, p0=p0, p1=p1, H=H, quad=quad)
            tracked.append(track)
        tracked.sort(key = lambda t: len(t.p0), reverse=True)
        return tracked 
开发者ID:makelove,项目名称:OpenCV-Python-Tutorial,代码行数:36,代码来源:plane_tracker.py

示例11: match_and_draw

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def match_and_draw(win):
        with Timer('matching'):
            raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2) #2
        p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
        if len(p1) >= 4:
            H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
            print('%d / %d  inliers/matched' % (np.sum(status), len(status)))
            # do not draw outliers (there will be a lot of them)
            kp_pairs = [kpp for kpp, flag in zip(kp_pairs, status) if flag]
        else:
            H, status = None, None
            print('%d matches found, not enough for homography estimation' % len(p1))

        vis = explore_match(win, img1, img2, kp_pairs, None, H) 
开发者ID:makelove,项目名称:OpenCV-Python-Tutorial,代码行数:16,代码来源:asift.py

示例12: match_and_draw

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def match_and_draw(win):
        print('matching...')
        raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2) #2
        p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
        if len(p1) >= 4:
            H, status = cv2.findHomography(p1, p2, cv2.RANSAC, 5.0)
            print('%d / %d  inliers/matched' % (np.sum(status), len(status)))
        else:
            H, status = None, None
            print('%d matches found, not enough for homography estimation' % len(p1))

        vis = explore_match(win, img1, img2, kp_pairs, status, H) 
开发者ID:makelove,项目名称:OpenCV-Python-Tutorial,代码行数:14,代码来源:find_obj.py

示例13: _find_homography

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def _find_homography(self, sch_pts, src_pts):
        """多组特征点对时,求取单向性矩阵."""
        try:
            M, mask = cv2.findHomography(sch_pts, src_pts, cv2.RANSAC, 5.0)
        except Exception:
            import traceback
            traceback.print_exc()
            raise HomographyError("OpenCV error in _find_homography()...")
        else:
            if mask is None:
                raise HomographyError("In _find_homography(), find no transfomation matrix...")
            else:
                return M, mask 
开发者ID:AirtestProject,项目名称:Airtest,代码行数:15,代码来源:keypoint_base.py

示例14: _find_homography

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def _find_homography(sch_pts, src_pts):
    """多组特征点对时,求取单向性矩阵."""
    try:
        M, mask = cv2.findHomography(sch_pts, src_pts, cv2.RANSAC, 5.0)
    except Exception:
        import traceback
        traceback.print_exc()
        raise HomographyError("OpenCV error in _find_homography()...")
    else:
        if mask is None:
            raise HomographyError("In _find_homography(), find no mask...")
        else:
            return M, mask 
开发者ID:AirtestProject,项目名称:Airtest,代码行数:15,代码来源:sift.py

示例15: find_homography

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import findHomography [as 别名]
def find_homography(keypoints_pic1, keypoints_pic2, matches) -> (List, np.float32, np.float32):
        # Find an Homography matrix between two pictures
        # From two list of keypoints and a list of matches, extrat
        # A list of good matches found by RANSAC and two transformation matrix (an homography and a rigid homography/affine)

        # Instanciate outputs
        good = []

        # Transforming keypoints to list of points
        src_pts = np.float32([keypoints_pic1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
        dst_pts = np.float32([keypoints_pic2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)

        # Find the transformation between points
        transformation_matrix, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

        # Compute a rigid transformation (without depth, only scale + rotation + translation)
        transformation_rigid_matrix, rigid_mask = cv2.estimateAffinePartial2D(src_pts, dst_pts)

        # Get a mask list for matches = A list that says "This match is an in/out-lier"
        matchesMask = mask.ravel().tolist()

        # Filter the matches list thanks to the mask
        for i, element in enumerate(matchesMask):
            if element == 1:
                good.append(matches[i])

        return good, transformation_matrix, transformation_rigid_matrix 
开发者ID:CIRCL,项目名称:douglas-quaid,代码行数:29,代码来源:distance_ransac_orb.py


注:本文中的cv2.findHomography方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。