你回来了?
我们一直在隔壁!

Python 截图转文字

from PIL import ImageGrab
import tkinter
import requests
import base64
from io import BytesIO
import json
import pyperclip
import math
import os
 
 
class PScreenWindow:
    def __init__(self):
        self._sx, self._sy = 0, 0
 
        self._win = tkinter.Tk()
        self._win.attributes("-alpha", 0.6)  # 设置窗口半透明
        self._win.attributes("-fullscreen", True)  # 设置全屏
        self._win.attributes("-topmost", True)  # 设置窗口在最上层
        self._width, self._height = self._win.winfo_screenwidth(
        ), self._win.winfo_screenheight()
        self._screenImage = ImageGrab.grab()
        self._screenImage.save("temp.png", format='PNG')
        self._tempImage = tkinter.PhotoImage(file="temp.png")
        # 创建画布
        self._canvas = tkinter.Canvas(
            self._win, width=self._width, height=self._height, highlightthickness=0, borderwidth=0)
 
        self._canvas.create_image(
            self._width*0.5, self._height*0.5, image=self._tempImage)
        self._canvas.create_rectangle(
            0, 0, self._width, self._height, fill='black', outline='', tag="bg")
        self._canvas.pack(fill="both")
        self._win.bind('<Button-1>', self.mouseEvent)  # 绑定鼠标左键点击事件
        self._win.bind('<Button-3>', self.mouseEvent)  # 绑定鼠标右键点击事件
        self._win.bind('<ButtonRelease-1>', self.mouseEvent)  # 绑定鼠标左键点击释放事件
        self._win.bind('<B1-Motion>', self.mouseMove)  # 绑定鼠标左键点击移动事件
        # 绑定Esc按键退出事件
        self._win.bind('<Escape>', lambda e: self.exit())
        self._win.mainloop()  # 窗口持久化
 
    def exit(self):
        try:
            os.remove('temp.png')
        except:
            pass
        self._win.destroy()
        print("操作完成")
 
    def getDistance(self, x1, y1,  x2, y2):
        return math.sqrt((x1-x2)**2+(y1-y2)**2)
 
    def sortPoint(self, x1, y1, x2, y2):
        return [min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)]
 
    def mouseEvent(self, event):
        print(event.state, event.num)
        if (event.num == 3):
            self.exit()
            return
        if event.state == 8:  # 鼠标左键按下
            self._sx, self._sy = event.x, event.y
            self._canvas.delete("bg")
        elif event.state == 264:  # 鼠标弹起
            d = self.getDistance(self._sx, self._sy, event.x, event.y)
            if d < 20:
                return
            x1, y1, x2, y2 = self.sortPoint(
                self._sx, self._sy, event.x, event.y)
            self._canvas.create_text(
                (x1+x2)*0.5, (y1+y2)*0.5, text="识别中...", font=("微软雅黑", 16), fill='red')
 
            img = self._screenImage.crop(
                (x1, y1, x2, y2))
            outBuffer = BytesIO()
            img.save(outBuffer, format='PNG')
            byteData = outBuffer.getvalue()
            imgBase64 = base64.b64encode(byteData).decode('ascii')
 
            # print(imgBase64)
            url = "http://www.xxxxxxxx.cn/TesseractOCR/"
            data = {"type": "ocr", "img": imgBase64}
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
 
            res = requests.post(url=url, data=data, headers=headers)
            content = res.text
            # print("识别结果:", content)
            if content.startswith(u'\ufeff'):
                content = content.encode('utf8')[3:].decode('utf8')
            try:
                data = json.loads(content)
                if (data.get("code") == "1"):
                    pyperclip.copy(data.get("text"))
                else:
                    pyperclip.copy("ocr fail")
            except Exception as e:
                pyperclip.copy(str(e))
            self.exit()
 
    def mouseMove(self, event):
        d = self.getDistance(self._sx, self._sy, event.x, event.y)
        if d < 20:
            return
        x1, y1, x2, y2 = self.sortPoint(self._sx, self._sy, event.x, event.y)
        rectPoints = {"left": [0, 0, x1, self._height], "top": [x1, 0, x2,  y1], "right": [
            x2, 0, self._width,  self._height], "bottom": [x1, y2, x2,  self._height]}
        for key in rectPoints:
            self._canvas.delete(key)
            ltx, lty, rbx, rby = rectPoints[key]
            self._canvas.create_rectangle(
                ltx, lty, rbx, rby,  fill='black', outline='', tag=key)
        self._canvas.delete("border")
        self._canvas.create_rectangle(
            x1, y1, x2, y2,  fill='', outline='red', tag="border")
 
 
if __name__ == '__main__':
    psw = PScreenWindow()
赞(0)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《Python 截图转文字
文章链接:https://www.gebizhan.com/2057.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

隔壁评论 抢沙发

快来看啊,隔壁站!

我们就是隔壁站的老王

隔壁邮箱隔壁TG

登录

找回密码

注册