python截图识别文字_python截图并转换文字

截图识别文字

作者

万开国[acewan]

【摘要】

本文主要介绍了使用pyHook、pythoncom、pytesseract、PIL、win32api等module实现python的截图识别文字功能。

【正文】

一准备及介绍

1.pyhook

pyHook通过pip直接安装比较困难,可以先下载whl文件再使用pip安装

018541image.png

选择与python环境一致的文件下载,使用cmd导向到下载文件夹,执行安装即可

008378image.png

其他module直接在控制台使用pip命令安装即可

2.module介绍

Pyhook:用于windows平台,监听鼠标和键盘事件,

:提供了访问win32 api的能力

Pytesseract:基于google's Tesseract-OCR的独立封装包

PIL:平台上的图像处理标准库

Win32api:封装windows win32 api额模块

二具体代码

# coding: utf8

import pyHook

import pythoncom

import pytesseract

import sys

from PIL import Image, ImageGrab

from win32api import GetSystemMetrics as

gsm

#提前绑定鼠标位置事件

old_x, old_y = 0, 0

new_x, new_y = 0, 0

full = False

hm = None

chinese = True

#图片识别文字方法,

def GetString(fileName):

#

print(imagePath)

if(chinese):

text = pytesseract.image_to_string(Image.open(fileName), lang='chi_sim')

else:

text = pytesseract.image_to_string(Image.open(fileName))

fl = open('Testxt.txt', 'w')

fl.write(text)

fl.close()

print(text)

return

def on_mouse_event(event):

global old_x, old_y, new_x, new_y, full, hm

if full:

image = ImageGrab.grab((0, 0, gsm(0), gsm(1)))

else:

#鼠标左键按下时,记录当前鼠标位置为截图矩形对角线的起始点

if event.MessageName == "mouse left down":

old_x, old_y = event.Position

#鼠标左键抬起时,记录当前位置为截图矩形对角线的结束点

if event.MessageName == "mouse left up":

new_x, new_y = event.Position

#解除事件绑定

hm.UnhookMouse()

hm = None

image = ImageGrab.grab((old_x, old_y, new_x, new_y))

fiName='printscreen.jpg'

image.save(fiName)

GetString(fiName)

if event.MessageName == "mouse left down":

sys.exit()

return

def capture():

#创建钩子管理对象

hm = pyHook.HookManager()

#将已准备好的方法注册到鼠标事件

hm.SubscribeMouseAll(on_mouse_event)

#开始监听鼠标事件

hm.HookMouse()

#一直监听直到退出程序

pythoncom.PumpMessages()

capture()

三效果展示

截图效果:

090991image.png

转文字效果:

082502image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值