[Python] 纯文本查看 复制代码
# 案例为本地图库与桌面区域(区域截屏)做图片对比
import time
import os
import cv2 as cv
import numpy as np
from mss import mss
# 1:启用对比图展示
ImgContrast = 1
# 1:启用对比次数提示
DiscernShow = 1
# 对比间隔(毫秒)
DiscernInterval = 50
# 截屏间隔时间(毫秒)
ScreenshotInterval = 200
# 对比图片列表
gun_list = []
# 对比图片地址
imgfile = "image"
# 匹配相似度级别
DiscernLevel = 60
# 截屏范围
box = (1540, 956, 1723, 1026)
# 对比图片特征点
def get_Img_Similarity_Opencv(img1, img2, img1name):
Matches_good = 0
Matches_all = 0
image1 = cv.imread(img1)
image2 = cv.cvtColor(img2, cv.COLOR_RGB2GRAY)
ret1, thresh1 = cv.threshold(image1, 250, 255, cv.THRESH_BINARY)
ret2, thresh2 = cv.threshold(image2, 250, 255, cv.THRESH_BINARY)
# 创建sift检测器
sift = cv.SIFT_create()
# 查找监测点和匹配符
kp1, des1 = sift.detectAndCompute(thresh1, None)
kp2, des2 = sift.detectAndCompute(thresh2, None)
if des1 is None:
print(img1name + "图片像素成色太低,无法识别")
return 0, 0
if des2 is None:
print("截图区域像素成色太低,无法对比")
return 0, 0
try:
# 获取flann匹配器
FLANN_INDEX_TREE = 0
indexParams = dict(algorithm=FLANN_INDEX_TREE, trees=5)
searchParams = dict(checks=50)
flann = cv.FlannBasedMatcher(indexParams, searchParams)
# 进行匹配
matches = flann.knnMatch(des1, des2, k=2)
# 准备空的掩膜 画好的匹配项
if ImgContrast == "1":
matchesMask = [[0, 0] for i in range(len(matches))]
for i, (m, n) in enumerate(matches):
Matches_all += 1
if m.distance < 0.7 * n.distance:
if ImgContrast == "1":
matchesMask[i] = [1, 0]
Matches_good += 1
if ImgContrast == "1":
drawPrams = dict(matchColor=(0, 255, 0), singlePointColor=(255, 0, 0), matchesMask=matchesMask, flags=0)
img3 = cv.drawMatchesKnn(thresh1, kp1, thresh2, kp2, matches, None, **drawPrams)
cv.imshow("matches", img3)
cv.waitKey(0)
if DiscernShow == "1":
print(img1name + "匹配成功次数:" + str(Matches_good) + " 总匹配次数:" + str(Matches_all))
time.sleep(DiscernInterval)
except:
print("对比图片特征点异常\n\n")
return 0, 0
else:
return Matches_good, Matches_all
# 匹配图片
def get_Img_Similarity(im):
for gun_name in gun_list:
result, result_all = get_Img_Similarity_Opencv(r""+imgfile+"\\" + gun_name + ".png", im, gun_name)
if result == 0 and result_all == 0:
print("对比失败")
return
if result >= int(result_all * DiscernLevel) and (result != 0 or result_all != 0):
print("对比成功")
return
else:
print("对比失败")
return
# 获取桌面截屏区域图片
def get_ScreenShot(box_img):
try:
with mss() as sct:
shot = sct.grab(box_img)
return shot
except:
print("截图范围错误")
# 获取桌面截屏匹配
def get_Screen():
img = get_ScreenShot(box)
arr = np.array(img.pixels, dtype=np.uint8)
get_Img_Similarity(arr)
time.sleep(ScreenshotInterval)
# 获取需要对比的图片信息
def get_ImgList(img_dir):
for files in os.listdir(img_dir):
if os.path.splitext(files)[1] == '.png':
gun_list.append(os.path.splitext(files)[0])
def main():
get_ImgList(imgfile)
while True:
cv.destroyAllWindows()
get_Screen()
if __name__ == '__main__':
main()