opencv 3种角点检测

import cv2
import numpy as np
from matplotlib import pyplot as plt


def cv_show(neme, img):
    # cv2.namedWindow(neme, cv2.WINDOW_NORMAL)
    cv2.imshow(neme, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# 第一个
# Harris 角点检测 cv2.cornerHarris()
img = cv2.imread('1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
# 输入图像必须是 float32,最后一个参数在 0.04 到 0.05 之间
# 参数:图像、角点检测中要考虑的领域大小、Sobel 求导中使用的窗口大小、Harris 角点检测方程中的自由参数,取值参数为 [0,04,0.06]
dst = cv2.cornerHarris(gray, 2, 3, 0.04)
# result is dilated for marking the corners, not important
dst = cv2.dilate(dst, None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst > 0.01 * dst.max()] = [0, 255, 0]
cv_show("s", img)


# 第二个
# 亚像素级精确度的角点 cv2.cornerSubPix()
# 这是 Harris角点检测 的修正版本
img = cv2.imread('1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find Harris corners
gray = np.float32(gray)
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)
# find centroids
# connectedComponentsWithStats(InputArray image, OutputArray labels, OutputArray stats,
# OutputArray centroids, int connectivity=8, int ltype=CV_32S)
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
# define the criteria to stop and refine the corners
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
# Python: cv2.cornerSubPix(image, corners, winSize, zeroZone, criteria)
# zeroZone – Half of the size of the dead region in the middle of the search zone
# over which the summation in the formula below is not done. It is used sometimes
# to avoid possible singularities of the autocorrelation matrix. The value of (-1,-1)
# indicates that there is no such a size.
# 返回值由角点坐标组成的一个数组(而非图像)
corners = cv2.cornerSubPix(gray, np.float32(centroids), (5, 5), (-1, -1), criteria)
# Now draw them
res = np.hstack((centroids, corners))
# np.int0 可以用来省略小数点后面的数字(非四㮼五入)
res = np.int0(res)
img[res[:, 1], res[:, 0]] = [0, 0, 255]
img[res[:, 3], res[:, 2]] = [0, 255, 0]
cv_show("ss", img)

# 第三个
#  Shi-Tomasi 角点检测 & 适合于跟踪的图像特征
# cv2.goodFeaturesToTrack() 使用 Shi-Tomasi 方法获取图像中 N 个最好的角点
img = cv2.imread('1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(gray, 25, 0.01, 10)  # 返回的结果是 [[ 311., 250.]] 两层括号的数组。
corners = np.int0(corners)
for i in corners:
    x, y = i.ravel()
    cv2.circle(img, (x, y), 3, 255, -1)
plt.imshow(img), plt.show()

你可能感兴趣的:(opencv-python,opencv,计算机视觉,人工智能)