分别显示对图像bridge.jpg执行Harris角检测和Shi-Tomasi角检测的结果,通过对函数参数的调整观察检测结果的变化。要求通过参数的设置,使检测结果中能含8个角点,用红色标注Shi-Tomasi角检测结果,用蓝色标注Harris角检测结果
时间: 2023-11-27 14:54:58 浏览: 107
首先,我们需要导入必要的库和图像,并将其转换为灰度图像:
```python
import cv2
import numpy as np
img = cv2.imread('bridge.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
接下来,我们可以使用`cv2.cornerHarris`函数来执行Harris角检测,并使用`cv2.cornerSubPix`函数对检测到的角进行精细化调整。我们可以通过调整`blockSize`和`ksize`参数来调整检测结果。下面是一个示例:
```python
# Harris角检测
dst = cv2.cornerHarris(gray, 2, 3, 0.04)
dst = cv2.dilate(dst, None)
ret, dst = cv2.threshold(dst, 0.01*dst.max(), 255, 0)
dst = np.uint8(dst)
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
corners = cv2.cornerSubPix(gray, np.float32(centroids), (5,5), (-1,-1), criteria)
# 绘制Harris角检测结果
for i in range(1, len(corners)):
x,y = corners[i]
cv2.circle(img, (int(x),int(y)), 5, (255,0,0), 2)
```
然后,我们可以使用`cv2.goodFeaturesToTrack`函数来执行Shi-Tomasi角检测,并使用`cv2.cornerSubPix`函数对检测到的角进行精细化调整。我们可以通过调整`maxCorners`和`qualityLevel`参数来调整检测结果。下面是一个示例:
```python
# Shi-Tomasi角检测
corners = cv2.goodFeaturesToTrack(gray, 8, 0.01, 10)
corners = np.int0(corners)
for i in corners:
x,y = i.ravel()
cv2.circle(img, (x,y), 5, (0,0,255), 2)
cv2.putText(img, "Shi-Tomasi Corner", (x-25,y-25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2)
```
最后,我们可以将Harris角检测结果和Shi-Tomasi角检测结果合并到同一张图像中,并将它们分别用红色和蓝色标注。下面是完整代码:
```python
import cv2
import numpy as np
img = cv2.imread('bridge.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Harris角检测
dst = cv2.cornerHarris(gray, 2, 3, 0.04)
dst = cv2.dilate(dst, None)
ret, dst = cv2.threshold(dst, 0.01*dst.max(), 255, 0)
dst = np.uint8(dst)
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
corners = cv2.cornerSubPix(gray, np.float32(centroids), (5,5), (-1,-1), criteria)
# 绘制Harris角检测结果
for i in range(1, len(corners)):
x,y = corners[i]
cv2.circle(img, (int(x),int(y)), 5, (255,0,0), 2)
# Shi-Tomasi角检测
corners = cv2.goodFeaturesToTrack(gray, 8, 0.01, 10)
corners = np.int0(corners)
for i in corners:
x,y = i.ravel()
cv2.circle(img, (x,y), 5, (0,0,255), 2)
cv2.putText(img, "Shi-Tomasi Corner", (x-25,y-25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2)
cv2.imshow('Harris and Shi-Tomasi Corner Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意,我们在上面的代码中设置了Shi-Tomasi角检测参数为`maxCorners=8`和`qualityLevel=0.01`,以使结果中含有8个角点。
阅读全文