首页 > 编程语言 >【Python】键鼠操作、区域截图

【Python】键鼠操作、区域截图

时间:2023-12-27 22:45:19浏览次数:29  
标签:截图 hash screenshot img Python cv2 键鼠 hash1 str

1.跟踪鼠标位置

import time,os
import pyautogui as pag

try:
    while True:
        print("按下Ctrl + C 结束程序")
        x, y = pag.position()
        posStr = "当前鼠标位置:" + str(x).rjust(4) + ',' + str(y).rjust(4)
        print(posStr)
        time.sleep(1)
        os.system('cls')
except KeyboardInterrupt:
    print('已退出')

2.鼠标点击

import pyautogui
import time
counts=3
while counts>0:
    pyautogui.click(x=1671, y=90)
    time.sleep(2)
    #pyautogui.click(x=1181,y=539)
    break

3.屏幕截图

from pyautogui import screenshot
import time
from PIL import ImageGrab

def grab_screenshot():#全屏截图
    shot = screenshot()
    shot.save("my_screenshot.png")

def grab_screenshot_area():#指定区域截图
    area = (0,0,500,500)
    shot = ImageGrab.grab(area)
    shot.save("my_screenshot_area.png")

def grab_screenshot_delay():#延时全屏截图
    time.sleep(5)
    shot = screenshot()
    shot.save("my_screen_delay.png")


grab_screenshot_area()

4.图像相似度

import cv2
import numpy as np


# 均值哈希算法
def aHash(img):
    # 缩放为8*8
    img = cv2.resize(img, (8, 8))
    # 转换为灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # s为像素和初值为0,hash_str为hash值初值为''
    s = 0
    hash_str = ''
    # 遍历累加求像素和
    for i in range(8):
        for j in range(8):
            s = s + gray[i, j]
    # 求平均灰度
    avg = s / 64
    # 灰度大于平均值为1相反为0生成图片的hash值
    for i in range(8):
        for j in range(8):
            if gray[i, j] > avg:
                hash_str = hash_str + '1'
            else:
                hash_str = hash_str + '0'
    return hash_str


# 差值感知算法
def dHash(img):
    # 缩放8*8
    img = cv2.resize(img, (9, 8))
    # 转换灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    hash_str = ''
    # 每行前一个像素大于后一个像素为1,相反为0,生成哈希
    for i in range(8):
        for j in range(8):
            if gray[i, j] > gray[i, j + 1]:
                hash_str = hash_str + '1'
            else:
                hash_str = hash_str + '0'
    return hash_str


# 感知哈希算法(pHash)
def pHash(img):
    # 缩放32*32
    img = cv2.resize(img, (32, 32))  # , interpolation=cv2.INTER_CUBIC

    # 转换为灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 将灰度图转为浮点型,再进行dct变换
    dct = cv2.dct(np.float32(gray))
    # opencv实现的掩码操作
    dct_roi = dct[0:8, 0:8]

    hash = []
    avreage = np.mean(dct_roi)
    for i in range(dct_roi.shape[0]):
        for j in range(dct_roi.shape[1]):
            if dct_roi[i, j] > avreage:
                hash.append(1)
            else:
                hash.append(0)
    return hash


# 通过得到RGB每个通道的直方图来计算相似度
def classify_hist_with_split(image1, image2, size=(256, 256)):
    # 将图像resize后,分离为RGB三个通道,再计算每个通道的相似值
    image1 = cv2.resize(image1, size)
    image2 = cv2.resize(image2, size)
    sub_image1 = cv2.split(image1)
    sub_image2 = cv2.split(image2)
    sub_data = 0
    for im1, im2 in zip(sub_image1, sub_image2):
        sub_data += calculate(im1, im2)
    sub_data = sub_data / 3
    return sub_data


# 计算单通道的直方图的相似值
def calculate(image1, image2):
    hist1 = cv2.calcHist([image1], [0], None, [256], [0.0, 255.0])
    hist2 = cv2.calcHist([image2], [0], None, [256], [0.0, 255.0])
    # 计算直方图的重合度
    degree = 0
    for i in range(len(hist1)):
        if hist1[i] != hist2[i]:
            degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))
        else:
            degree = degree + 1
    degree = degree / len(hist1)
    return degree


# Hash值对比
def cmpHash(hash1, hash2):
    n = 0
    # hash长度不同则返回-1代表传参出错
    if len(hash1)!=len(hash2):
        return -1
    # 遍历判断
    for i in range(len(hash1)):
        # 不相等则n计数+1,n最终为相似度
        if hash1[i] != hash2[i]:
            n = n + 1
    return n


img1 = cv2.imread('my_screenshot_area.png')  #  6------5 ----2--------0.84
img2 = cv2.imread('my_screenshot_area1.png')


hash1 = aHash(img1)
hash2 = aHash(img2)
n = cmpHash(hash1, hash2)
print('均值哈希算法相似度:', n)#不超过5,就说明两张图像很相似;如果大于10,就说明这是两张不同的图像

hash1 = dHash(img1)
hash2 = dHash(img2)
n = cmpHash(hash1, hash2)
print('差值哈希算法相似度:', n)

hash1 = pHash(img1)
hash2 = pHash(img2)
n = cmpHash(hash1, hash2)
print('感知哈希算法相似度:', n)

n = classify_hist_with_split(img1, img2)
print('三直方图算法相似度:', n)

 

标签:截图,hash,screenshot,img,Python,cv2,键鼠,hash1,str
From: https://www.cnblogs.com/shan-gui-yao/p/17931587.html

相关文章

  • Python 虚拟环境工具及使用总结
    ​ 参考文档:Python虚拟环境工具及使用总结1、virtualenvvirtualenv是一个创建隔离的Python环境的工具。它可以创建一个包含指定版本Python解释器的环境,并可以安装独立的库和依赖。Python官方提供的虚拟环境工具。Virtualenv 的原理是基于Python的模块化机制,通过创建一......
  • Python进阶
    Object介绍  Python的Object是一种数据抽象或者数据结构抽象,Object应该同时具备:本征值(Indentity)、型式(Type)、值(Value)三个参数。a=45print(id(a))#表示在python中的唯一内存地址,具备唯一性print(type(a))print(a)/*-----output-------*/2063144480432<class'int'>......
  • 【python爬虫课程设计】拉勾网—数据分析师岗位内容爬取+数据分析可视化
    一、选题背景随着互联网的发展,数据分析岗位在各行各业中的需求越来越大。拉勾网作为国内知名的招聘网站,其上的数据分析岗位信息具有很高的参考价值。通过对拉勾网上的数据分析岗位进行数据分析,可以了解当前数据分析岗位的市场情况,为求职者提供有价值的参考信息,同时也可以为企......
  • 简单的用Python采集下微博评论,制作可视化词云图
    简单的用Python来获取微博评论,制作词云图。首先准备环境模块环境使用Python3.8或以上版本即可Pycharm任意版本模块使用importrequestsimportwordcloudimportjieba 以上三个模块都需要安装,直接pipinstall加上模块名安装即可。爬虫基本流......
  • Python实战:从数据库到Excel的复杂查询结果处理【中】
    一、前言在上篇中,我已经成功从数据库查询到数据,并根据指定条件将数据写入到excel中,但是写入的数据和我们通过数据库连接工具查询到的结果并不一致,接下来我们就来解决:Python从数据库查询的数据保存到excel中后,数据格式异常的问题二、解决步骤分析现象使用Navicat从数据库查询到的数......
  • python 使用 rsa库进行RSA签名和加解密
     python使用rsa库进行RSA签名和加解密 #-*-coding:UTF-8-*-#!/usr/bin/envpythonimportbase64importrsafromrsaimportcommon#使用rsa库进行RSA签名和加解密classRsaUtil(object):PUBLIC_KEY_PATH='/tmp/gbzj/public_key.pem'#公钥P......
  • 【Python数据分析课程设计】大数据分析—利用k-means 聚类分析对客户细分分析
    一、选题的背景在当今社会,大数据已经成为了企业决策的重要依据。通过对客户进行细分分析,企业可以更好地了解客户的需求和行为,从而制定更加精准的营销策略,提高市场竞争力。要达到的数据分析目标是通过对客户数据的分析,找出不同客户群体的特征和需求,为企业提供有针对性的营销......
  • python生成word文档
    python生成word文档,感觉比java生成方便很多下面看看步骤1、环境pipinstallpython-docx2、准备一张需要插入word中的图片monty-truth.png3、一段代码fromdocximportDocumentfromdocx.sharedimportInchesdocument=Document()document.add_heading('Document......
  • python实现汉诺塔游戏
    highlighter-pythonlt=list()#左边的空列表rt=list()#右边的空列表ct=list()#中间的空列表#初始化函数definit():size=int(input("请输入你要挑战的高度:"))#建立左边的汉诺塔foriinrange(1,size+1):lt.append(i*2-1);......
  • 一个完整Python实战项目:selenium识别验证码实现自动登录,自动操作浏览器获取某东数据
    最近都没啥时间,很久没更新了。今天分享一下,如何用selenium识别验证码,实现自动登录以及获取数据。目标:某东话不多说直接开始准备工作环境Python3.10Pycharm模块使用importrandomimporttimefromseleniumimportwebdriverimportpyautoguii......