1.打开pycharm
2.新建文件
3.
import cv2
import numpy as np
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
import win32gui
from ctypes import *
import sys
import aircv
import time
import threading
import cv2
import numpy as np
import random
def screen_cut():#指定窗口截图
hwnd = win32gui.FindWindow(None, “地下城与勇士”)
title = win32gui.GetWindowText(hwnd)
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
img = screen.grabWindow(hwnd).toImage()
img.save(“D:/auto/dnf/screenshot.jpg”)
def mac_match():
im1 = cv2.imread(‘D:/auto/dnf/people_download/time.jpeg’)
im2 = cv2.imread(‘D:/auto/dnf/people_download/time1.jpeg’)
ima1 = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
ima2 = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(ima1, None)
kp2, des2 = sift.detectAndCompute(ima2, None)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
good = []
for m, n in matches:
if m.distance < 0.55 * n.distance:
good.append(m)
src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2) # queryIdx
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2) # trainIdx
####################################### 筛选算法###################
MIN_MATCH_COUNT = 4
#ttt = [kp1[m.queryIdx].pt for m in good]
#print(ttt)
print(len(good))
if len(good) > MIN_MATCH_COUNT:
# 通过距离近的描述符 找到两幅图片的关键点
src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
matchesMask = mask.ravel().tolist()
h, w, no = im1.shape
# 计算第二张图相对于第一张图的畸变
#pts = np.float32([[0, 0], [0, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
#dst = cv2.perspectiveTransform(pts, M)
# im2 = cv2.polylines(im2, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)
else:
matchesMask = 0
return
draw_params = dict(
# matchColor=(0, 255, 0),
singlePointColor=None,
matchesMask=matchesMask,
flags=2)
print(matchesMask)
########################## 坐标提取#######################
flag1 = 0
flag2 = 0
loc = [0, 0]
for i in matchesMask:
loc_temp = [0, 0]
if i:
loc_temp[0], loc_temp[1] = kp1[good[flag1].queryIdx].pt
loc[0] += loc_temp[0]
loc[1] += loc_temp[1]
flag2 += 1
flag1 += 1
loc[0] = int(loc[0] / flag2)
loc[1] = int(loc[1] / flag2)
print(loc)
cv2.namedWindow(“show”)
im3 = cv2.drawMatches(im1, kp1, im2, kp2, good, None, **draw_params)
cv2.imwrite(‘C:/Users/yuanqi/Desktop/15.jpg’, im3)
imshow = cv2.imread(‘C:/Users/yuanqi/Desktop/15.jpg’)
cv2.imshow(“show”, imshow)
cv2.waitKey(0)
#screen_cut()
mac_match()
4.结果
python图像特征点匹配
最新推荐文章于 2024-08-20 06:00:00 发布