import cv2
import numpy as np
# 读取emoji图片和大图
emoji_img = cv2.imread('emoji.png', 0) # 确保使用灰度模式读取
large_img = cv2.imread('large_image.png', 0)
# 创建SIFT(尺度不变特征变换)检测器
sift = cv2.SIFT_create()
# 寻找两幅图像的关键点和描述符
keypoints_emoji, descriptors_emoji = sift.detectAndCompute(emoji_img, None)
keypoints_large_img, descriptors_large_img = sift.detectAndCompute(large_img, None)
# 使用FLANN(Fast Library for Approximate Nearest Neighbors)匹配器进行描述符匹配
index_params = dict(algorithm=1, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(descriptors_emoji, descriptors_large_img, k=2)
# 筛选出较好的匹配点
good_matches = []
for m, n in matches:
if m.distance < 0.7 * n.distance:
good_matches.append(m)
# 仅当emoji的足够数量的特征点能够在大图中找到匹配时才继续
MIN_MATCH_COUNT = 10
if len(good_matches) > MIN_MATCH_COUNT:
# 从好的匹配中提取出对应点
src_pts = np.float32([keypoints_emoji[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints_large_img[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
# 利用匹配点找到两图之间的单应性
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
# 获取emoji图像的宽高
h, w = emoji_img.shape
# 获取emoji图片的四个顶点坐标,并通过计算单应性能获得对应的在大图中的顶点坐标
pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
dst = cv2.perspectiveTransform(pts, M)
# 在大图上画出找到的emoji的位置
large_img_color = cv2.cvtColor(large_img, cv2.COLOR_GRAY2BGR) # 将大图转为彩色以便画出多彩边界
img_with_emoji = cv2.polylines(large_img_color, [np.int32(dst)], True, (0, 255, 0), 3, cv2.LINE_AA)
# 显示结果
cv2.imshow('Found Emoji', img_with_emoji)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Not enough matches are found - %d/%d" % (len(good_matches), MIN_MATCH_COUNT))
import cv2
import numpy as np
# 读取emoji图片和大图
emoji_img = cv2.imread('emoji.png', 0)
large_img = cv2.imread('large_image.png', 0)
# 使用ORB创建检测器
orb = cv2.ORB_create()
# 寻找两幅图像的关键点和描述符
keypoints_emoji, descriptors_emoji = orb.detectAndCompute(emoji_img, None)
keypoints_large_img, descriptors_large_img = orb.detectAndCompute(large_img, None)
# 使用BF匹配器,并设置crossCheck为True
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(descriptors_emoji, descriptors_large_img)
# 根据distance排序匹配点(最好的匹配在前)
matches = sorted(matches, key = lambda x:x.distance)
# 设置显示的匹配点数量的阈值
# 这个值可能需要根据你的特定情况调整
MIN_MATCH_COUNT = 10
if len(matches) > MIN_MATCH_COUNT:
# 绘制匹配结果
img_matches = cv2.drawMatches(emoji_img, keypoints_emoji, large_img, keypoints_large_img, matches[:MIN_MATCH_COUNT], None, flags=2)
# 显示结果
cv2.imshow('Matches', img_matches)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Not enough matches are found - %d/%d" % (len(matches), MIN_MATCH_COUNT))