抓取屏幕并将其传递给tesseract
进行OCR处理非常简单。
PIL(pillow)库可以在MacOS和Windows上轻松抓取帧。然而,Linux的这个功能是最近才添加的,因此下面的代码解决了它不存在的问题。(我在Ubuntu 19.10上,我的Pillow不支持它)。
用户使用屏幕区域矩形坐标启动程序。主循环不断抓取屏幕的此区域,并将其提供给Tesseract。如果Tesseract在图像中发现任何非空白文本,则会将其写入stdout。
请注意,这不是一个真正的实时系统。没有时间保证,每一帧的时间都不同。您的计算机可能达到60 FPS或6 FPS。这也会受到您要监视的矩形大小的极大影响。
import sys
import pytesseract
from PIL import Image
try:
from PIL import ImageGrab
use_grab = True
except Exception as ex:
if ( sys.platform == 'linux' ):
from Xlib import display, X
use_grab = False
else:
raise ex
def screenGrab( rect ):
""" Given a rectangle, return a PIL Image of that part of the screen.
Handles a Linux installation with and older Pillow by falling-back
to using XLib """
global use_grab
x, y, width, height = rect
if ( use_grab ):
image = PIL.ImageGrab.grab( bbox=[ x, y, x+width, y+height ] )
else:
dsp = display.Display()
root = dsp.screen().root
raw_image = root.get_image( x, y, width, height, X.ZPixmap, 0xffffffff )
image = Image.frombuffer( "RGB", ( width, height ), raw_image.data, "raw", "BGRX", 0, 1 )
return image
if ( __name__ == "__main__" ):
EXE = sys.argv[0]
del( sys.argv[0] )
if ( len( sys.argv ) != 4 or sys.argv[0] in ( '--help', '-h', '-?', '/?' ) ):
sys.stderr.write( EXE + ": monitors section of screen for text\n" )
sys.stderr.write( EXE + ": Give x, y, width, height as arguments\n" )
sys.exit( 1 )
x = int( sys.argv[0] )
y = int( sys.argv[1] )
width = int( sys.argv[2] )
height = int( sys.argv[3] )
screen_rect = [ x, y, width, height ]
print( EXE + ": watching " + str( screen_rect ) )
while ( True ):
image = screenGrab( screen_rect )
text = pytesseract.image_to_string( image )
text = text.strip()
if ( len( text ) > 0 ):
print( text )
这个答案是从Stack Overflow上其他答案中拼凑而来的。
如果你经常使用这个答案,最好添加一个速率限制器来节省一些CPU。它可能可以在每个循环中休眠半秒钟。