首页 > 解决方案 > cv:assertion 因透视变换而失败

问题描述

我在应用单应性时遇到了这个错误, (-215:Assertion failed) scn + 1 == m.cols in function 'cv::perspectiveTransform'正如我所指出的,我认为 des1 和 des2 的长度小于 2 存在问题,如果是这样的话。但我面临上述错误,这让我摸不着头脑

代码

#!/usr/bin/env python

import cv2
import numpy as np
from utils import mouse_handler
from utils import get_four_points
import sys


cap = cv2.VideoCapture('2.mp4')
MIN_MATCH_COUNT = 5
#img1 = cv2.imread('b.png', cv2.IMREAD_UNCHANGED)
img1 = cv2.imread('b.png', 0) # Query picture
img2 = cv2.imread('d.png', 0) # training picture
sift = cv2.xfeatures2d.SIFT_create()

# Use SIFT to find key points and descriptors
kp1, des1 = sift.detectAndCompute(img1, None)


# Loop until the end of the video
while (cap.isOpened()):
    ret, frame = cap.read()
    # Display image.
    kp2, des2 = sift.detectAndCompute(frame, None)
    FLANN_INDEX_KDTREE = 0
    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
    search_params = dict(checks=50)

    flann = cv2.FlannBasedMatcher(index_params, search_params)
    if (des1 is not None and len(des1) > 2 and des2 is not None and len(des2) > 2):
        matches = flann.knnMatch(des1, des2, k=2)
    #matches = flann.knnMatch(des1, des2, k=2)

        good = []
        for m, n in matches:
            if m.distance < 0.7 * n.distance:
                good.append(m)

        if len(good) > MIN_MATCH_COUNT:
            src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
            dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)

            M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
            matchesMask = mask.ravel().tolist()

            h, w = img1.shape
            pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
            dst = cv2.perspectiveTransform(pts, M)
            print(dst)

        else:
            print("Not enough matches are found", (len(good), MIN_MATCH_COUNT))
            matchesMask = None
    cv2.imshow("Image", frame);
    #cv2.waitKey(1);
    
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

标签: pythonopencvhomography

解决方案


推荐阅读