import cv2 import numpy as np # 读取图像 img1 = cv2.imread('D:/wzk/JIEMIAN/images/yi_duibidu.jpg') img2 = cv2.imread('D:/wzk/JIEMIAN/images/er_duibidu.jpg') # 判断图像是否读取成功 if img1 is None or img2 is None: print("Failed to read image!") exit() # 将图像转化为灰度图像 gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # 使用Shi-tomasi算法检测关键点 corners1 = cv2.goodFeaturesToTrack(gray1, 500, 0.01, 10) corners2 = cv2.goodFeaturesToTrack(gray2, 500, 0.01, 10) # 调整图像大小 corners1 = cv2.resize(corners1, (640, 480)) corners2 = cv2.resize(corners2, (640, 480)) # 使用Lucas-Kanade算法进行光流跟踪 lk_params = dict(winSize=(15, 15), maxLevel=2, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)) p1, st, err = cv2.calcOpticalFlowPyrLK(gray1, gray2, corners1, None, **lk_params) # 计算转换矩阵 M, mask = cv2.findHomography(p1, corners2, cv2.RANSAC, 5.0) # 将图像1应用转换矩阵 result = cv2.warpPerspective(img1, M, (img1.shape[1] + img2.shape[1], img1.shape[0])) # 将图像2拼接到图像1后面 result[0:img2.shape[0], img1.shape[1]:img1.shape[1] + img2.shape[1]] = img2 # 显示拼接后的图像 cv2.imshow("Result", result) cv2.waitKey(0) cv2.destroyAllWindows()解决cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\video\src\lkpyramid.cpp:1260: error: (-215:Assertion failed) (npoints = prevPtsMat.checkVector(2, CV_32F, true)) >= 0 in function 'cv::`anonymous-namespace'::SparsePyrLKOpticalFlowImpl::calc'
时间: 2023-06-24 22:08:28 浏览: 131
这个错误是由于程序中的calcOpticalFlowPyrLK函数所使用的参数不正确导致的,具体来说是第三个参数corners1的数据类型不是float32。你需要将其转换为float32类型,即将以下代码:
p1, st, err = cv2.calcOpticalFlowPyrLK(gray1, gray2, corners1, None, **lk_params)
改为:
p1, st, err = cv2.calcOpticalFlowPyrLK(gray1, gray2, corners1.astype(np.float32), None, **lk_params)
这样就可以解决这个错误了。
阅读全文