harris角点检测
img = cv2.imread("chess.jpg")
img = cv2.resize(img, (600, 600))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dst = cv2.cornerHarris(gray, 2, 3, 0.04)
img[dst > 0.01 * dst.max()] = [0, 0, 255]
show('img', img)
SIFT
高斯差分金字塔DOG
img = cv2.imread("Lenargb.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 得到特征点
sift = cv2.SIFT_create()
kp = sift.detect(gray, None)
img = cv2.drawKeypoints(gray, kp, img)
show('img', img)
# 计算特征
kp, des = sift.compute(gray, kp)
print(des[0])
特征匹配
特征点一一匹配
Brute-Force 蛮力匹配
1对1匹配
img1 = cv2.imread("books.png", 0)
img2 = cv2.imread("book.png", 0)
sift = cv2.SIFT_create()
# kp关键点,des特征向量
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# 特征点互相匹配
bf = cv2.BFMatcher(crossCheck=True)
# 1对1匹配
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x: x.distance)
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=2)
show('img3', img3)
k对最佳匹配
# k对最佳匹配
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)
good = []
for m, n in matches:
if m.distance < 0.75 * n.distance:
good.append([m])
img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good, None, flags=2)
show('img3', img3)
图像拼接实例
# 图像拼接实例
imgA = cv2.imread("p2.png")
# show('imgA', imgA)
imgB = cv2.imread("p1.png")
# show('imgB', imgB)
imgB = cv2.resize(imgB, (imgA.shape[1], imgA.shape[0]))
img1 = cv2.cvtColor(imgA, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(imgB, cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT_create()
# kp关键点,des特征向量
kp1, fea1 = sift.detectAndCompute(img1, None)
kp2, fea2 = sift.detectAndCompute(img2, None)
kp1 = np.float32([kp.pt for kp in kp1])
kp2 = np.float32([kp.pt for kp in kp2])
bf = cv2.BFMatcher()
matches = bf.knnMatch(fea1, fea2, k=2)
match = []
for m in matches:
if len(m) == 2 and m[0].distance < 0.75 * m[1].distance:
match.append((m[0].trainIdx, m[0].queryIdx))
if len(match) > 4:
ptsA = np.float32([kp1[i] for (_, i) in match])
ptsB = np.float32([kp2[i] for (i, _) in match])
(H, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC)
result = cv2.warpPerspective(imgA, H, (imgA.shape[1] + imgB.shape[1], imgA.shape[0]))
show('result', result)
result[0:imgB.shape[0], 0:imgB.shape[1]] = imgB
show('result', result)