改进下面代码使其输出特征点连线图和拼接图import cv2 # 读取图片 img1 = cv2.imread("qiao1.jpg") img2 = cv2.imread("qiao2.jpg") # 转换为灰度图像 gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # Shi-Tomasi角点检测 corners1 = cv2.goodFeaturesToTrack(gray1, 25, 0.01, 10) corners2 = cv2.goodFeaturesToTrack(gray2, 25, 0.01, 10) # 计算光流 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) # 筛选匹配点 good_new = p1[st == 1] good_old = corners1[st == 1] # 计算变换矩阵 M, _ = cv2.findHomography(good_new, good_old, cv2.RANSAC) # 进行透视变换 result = cv2.warpPerspective(img2, M, (img1.shape[1] + img2.shape[1], img2.shape[0])) result[0:img1.shape[0], 0:img1.shape[1]] = img1 # 保存拼接结果 cv2.imwrite("result.jpg", result)
时间: 2023-07-16 19:16:00 浏览: 101
可以改进代码如下:
```python
import cv2
# 读取图片
img1 = cv2.imread("qiao1.jpg")
img2 = cv2.imread("qiao2.jpg")
# 转换为灰度图像
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# Shi-Tomasi角点检测
corners1 = cv2.goodFeaturesToTrack(gray1, 25, 0.01, 10)
corners2 = cv2.goodFeaturesToTrack(gray2, 25, 0.01, 10)
# 计算光流
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)
# 筛选匹配点
good_new = p1[st == 1]
good_old = corners1[st == 1]
# 计算变换矩阵
M, _ = cv2.findHomography(good_new, good_old, cv2.RANSAC)
# 进行透视变换
result = cv2.warpPerspective(img2, M, (img1.shape[1] + img2.shape[1], img2.shape[0]))
result[0:img1.shape[0], 0:img1.shape[1]] = img1
# 画出特征点连线图
for i, (new, old) in enumerate(zip(good_new, good_old)):
a, b = new.ravel()
c, d = old.ravel()
cv2.line(result, (a, b), (c, d), (0, 0, 255), 2)
# 拼接图
cv2.imwrite("result.jpg", result)
```
在原有的代码基础上,我们新增了以下代码:
1. 画出特征点连线图
```python
for i, (new, old) in enumerate(zip(good_new, good_old)):
a, b = new.ravel()
c, d = old.ravel()
cv2.line(result, (a, b), (c, d), (0, 0, 255), 2)
```
这段代码使用 `cv2.line()` 函数画出了特征点的连线,并将其绘制在拼接图上。其中,`good_new` 和 `good_old` 分别是筛选出的匹配点的新旧坐标,`ravel()` 函数用于将其展平为一维数组,然后使用 `cv2.line()` 函数连接两个点。
2. 输出拼接图
```python
cv2.imwrite("result.jpg", result)
```
这段代码使用 `cv2.imwrite()` 函数输出拼接图。
阅读全文