cv2.KeyPoint()怎么用
时间: 2023-06-25 19:07:36 浏览: 638
`cv2.KeyPoint()` 是 OpenCV 中用于表示关键点的类。它有以下参数:
- `x`: 关键点的 x 坐标。
- `y`: 关键点的 y 坐标。
- `_size`: 关键点的尺度大小。
- `_angle`: 关键点的方向角度。
- `_response`: 关键点响应强度。
- `_octave`: 关键点所在的金字塔层数。
- `_class_id`: 关键点的类别 ID。
下面是一个简单的示例,用于创建一个 `cv2.KeyPoint` 对象:
```python
import cv2
# 创建一个 KeyPoint 对象
kp = cv2.KeyPoint(x=100, y=100, _size=20)
```
你也可以使用以下方法来获取或设置 KeyPoint 的属性:
```python
import cv2
# 创建一个 KeyPoint 对象
kp = cv2.KeyPoint(x=100, y=100, _size=20)
# 获取和修改属性
print(kp.pt) # (100.0, 100.0)
print(kp.size) # 20.0
kp.size = 30.0
print(kp.size) # 30.0
```
除了直接创建 `cv2.KeyPoint` 对象外,它还可以与其他 OpenCV 函数一起使用,例如 `cv2.drawKeypoints()`。
相关问题
解释如下代码:def draw_matches(img1, kp1, img2, kp2, matches, color=None): """Draws lines between matching keypoints of two images. Keypoints not in a matching pair are not drawn. Args: img1: An openCV image ndarray in a grayscale or color format. kp1: A list of cv2.KeyPoint objects for img1. img2: An openCV image ndarray of the same format and with the same element type as img1. kp2: A list of cv2.KeyPoint objects for img2. matches: A list of DMatch objects whose trainIdx attribute refers to img1 keypoints and whose queryIdx attribute refers to img2 keypoints. """ # We're drawing them side by side. Get dimensions accordingly. # Handle both color and grayscale images. if len(img1.shape) == 3: new_shape = (max(img1.shape[0], img2.shape[0]), img1.shape[1]+img2.shape[1], img1.shape[2]) elif len(img1.shape) == 2: new_shape = (max(img1.shape[0], img2.shape[0]), img1.shape[1]+img2.shape[1]) new_img = np.zeros(new_shape, type(img1.flat[0])) # Place images onto the new image. new_img[0:img1.shape[0],0:img1.shape[1]] = img1 new_img[0:img2.shape[0],img1.shape[1]:img1.shape[1]+img2.shape[1]] = img2 # Draw lines between matches. Make sure to offset kp coords in second image appropriately. r = 2 thickness = 1 print(len(kp1),len(kp2), len(matches) ) if color: c = color for m in matches[0:20]: # Generate random color for RGB/BGR and grayscale images as needed. if not color: c = np.random.randint(0,256,3) if len(img1.shape) == 3 else np.random.randint(0,256) # So the keypoint locs are stored as a tuple of floats. cv2.line(), like most other things, # wants locs as a tuple of ints. c = [255,255,255] end1 = tuple(np.round(kp1[m.queryIdx].pt).astype(int)) end2 = tuple(np.round(kp2[m.trainIdx].pt).astype(int) + np.array([img1.shape[1], 0])) cv2.line(new_img, end1, end2, c, thickness) cv2.circle(new_img, end1, r, c, thickness) cv2.circle(new_img, end2, r, c, thickness) plt.figure(figsize=(15,15)) plt.imshow(new_img) plt.show()
这是一个 Python 函数,用于将两张图片中的匹配关键点连接起来,并显示出来。函数的输入参数包括:img1,kp1,img2,kp2,matches,以及连接线的颜色(color)。
函数首先根据输入的两张图片的大小创建一个新的图像,用于在其中绘制匹配关键点。然后将输入的两张图片分别放置在新图像的左侧和右侧。
接下来,函数根据 matches 中的关键点信息,在新图像中绘制连接线。如果 color 参数不为空,则使用指定的颜色,否则使用随机颜色。对于每个匹配,函数将在两个关键点处绘制圆圈,并使用 cv2.line 函数画出连接线。
最后,函数展示绘制好的新图像。可以看出,这个函数的作用是可视化两张图片中的匹配关键点。
import cv2 import numpy as np # 读取两幅图像 img1 = cv2.imread('D:\wzk\JIEMIAN\images\er_duibidu.jpg') img2 = cv2.imread('D:\wzk\JIEMIAN\images\yi_duibidu.jpg') # 将两幅图像转换为灰度图像 gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # 提取图像特征点 orb = cv2.ORB_create() kp1, des1 = orb.detectAndCompute(gray1, None) kp2, des2 = orb.detectAndCompute(gray2, None) # 匹配特征点 matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING) matches = matcher.match(des1, des2) # 选择最佳匹配点 matches = sorted(matches, key=lambda x: x.distance) good_matches = matches[:int(len(matches)*0.15)] # 绘制特征点连接图 img3 = cv2.drawMatches(img1, kp1, img2, kp2, good_matches, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS) # 计算变换矩阵 src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2) M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) # 拼接图像 result = cv2.warpPerspective(img1, M, (img1.shape[1] + img2.shape[1], img1.shape[0])) result[0:img2.shape[0], 0:img2.shape[1]] = img2 # 保存连接图 cv2.imwrite('D:\wzk\JIEMIAN\Result\ORB-pz.jpg', img3) # 保存第二幅图像 cv2.imwrite('D:\wzk\JIEMIAN\Result\ORB-pj.jpg', result) # 显示结果 cv2.namedWindow("Keypoint Matches", cv2.WINDOW_NORMAL) cv2.imshow("Keypoint Matches", img3) cv2.namedWindow("Result",cv2.WINDOW_NORMAL) cv2.imshow('Result', result) cv2.waitKey(0) cv2.destroyAllWindows()改进为对文件夹内的多幅图像进行配准拼接
可以使用循环遍历文件夹内的所有图像,对每幅图像进行配准拼接,最终将所有拼接结果合并成一张大图像。
以下是示例代码:
```
import cv2
import numpy as np
import os
# 定义文件夹路径和结果保存路径
folder_path = 'D:\wzk\JIEMIAN\images'
result_path = 'D:\wzk\JIEMIAN\Result\ORB-pj.jpg'
# 获取文件夹内所有图像路径
img_paths = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.jpg')]
# 遍历所有图像,进行配准拼接
result = cv2.imread(img_paths[0])
for i in range(1, len(img_paths)):
img = cv2.imread(img_paths[i])
# 将两幅图像转换为灰度图像
gray1 = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 提取图像特征点
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(gray1, None)
kp2, des2 = orb.detectAndCompute(gray2, None)
# 匹配特征点
matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
matches = matcher.match(des1, des2)
# 选择最佳匹配点
matches = sorted(matches, key=lambda x: x.distance)
good_matches = matches[:int(len(matches)*0.15)]
# 计算变换矩阵
src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
# 拼接图像
result = cv2.warpPerspective(result, M, (result.shape[1] + img.shape[1], result.shape[0]))
result[0:img.shape[0], result.shape[1]-img.shape[1]:] = img
# 保存拼接结果
cv2.imwrite(result_path, result)
# 显示结果
cv2.namedWindow("Result",cv2.WINDOW_NORMAL)
cv2.imshow('Result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
代码中使用了 `os` 模块来遍历文件夹内所有图像的路径,然后对每幅图像进行配准拼接。最终将所有拼接结果合并成一张大图像,并保存到指定路径。
阅读全文