吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3744|回复: 81
收起左侧

[原创工具] 52pj专发,Python 截图转文字的小工具(有源码)

  [复制链接]
Pwaerm 发表于 2023-1-25 16:51
本帖最后由 Pwaerm 于 2023-1-26 09:54 编辑

以前是用QQ破图,但是QQ需要把图片发送出去,再打开图片长按才能识别成文字。
一直想弄个小工具,截图以后剪贴板就自动变成文字,方便粘贴 。所以就折腾了这个。



因为我的服务器上已经部署了TesseractOCR,所以识图部分就通过 requests.post 交给服务器去完成的。
   TesseractOCR服务器部署简要说明(涉及的文件软件,在下载地址中都有)
   1  安装 tesseractOCR (EXE)软件,并配置环境变量。
   2  安装 apache 服务器(我用的是xmapp)。
   3  把压缩包中的 TesseractOCR (PHP)放到 apache 服务器生成的htdocs 文件夹中去,然后就可以使用  http://www.xxxxx.com /TesseractOCR 这个API了,好外是没有限制,精确度也行,而且方便自己所有相关的应用访问。

*:python本身也可以直接使用TesseractOCR


   打开软件后按住鼠标选定要识别的区域,松开鼠标就可以去粘贴识别出来的内容了。
   右键可以中止操作。
   老规则,上源码:
   下载地址: 链接:https://pan.baidu.com/s/1e8N-GbYuYMnWwNZrO6xGPw?pwd=4fds  提取码:4fds

001.png

002.png


003.png

打包后文件有点大呢python不建议打包


[Asm] 纯文本查看 复制代码
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()









免费评分

参与人数 17吾爱币 +16 热心值 +17 收起 理由
ssqyc + 1 热心回复!
wu蛋糕 + 1 + 1 谢谢@Thanks!
i67 + 1 + 1 我很赞同!
zhixiangwangluo + 1 + 1 谢谢@Thanks!
vipcao888 + 1 谢谢@Thanks!
风之暇想 + 7 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
xiaobaikan + 1 + 1 谢谢@Thanks!
confiant + 1 谢谢@Thanks!
chao8709 + 1 + 1 我很赞同!
yanglinman + 1 谢谢@Thanks!
jaguar001 + 1 我很赞同!
netspirit + 1 已经处理,感谢您对吾爱破解论坛的支持!
LuckyClover + 1 + 1 谢谢@Thanks!
苏浩 + 1 + 1 热心回复!
yechengyaoshi + 1 + 1 我很赞同!
blfiag + 1 对截图部分处理感兴趣!
katelya + 1 + 1 热心回复!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

rhci 发表于 2023-1-28 12:58
Pwaerm 发表于 2023-1-28 10:54
trwebocr 的API 是 http://192.168.0.9/api/tr-run/    这种形式,要带上 api/tr-run/

另外 它的返回 ...

。。。给个完整代码吧,我这半吊子,看不懂
[Shell] 纯文本查看 复制代码
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://192.168.6.196:8089/api/tr-run/"
            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()
 楼主| Pwaerm 发表于 2023-1-28 13:25
rhci 发表于 2023-1-28 12:58
。。。给个完整代码吧,我这半吊子,看不懂
[Shell] 纯文本查看 复制代码
from PIL import ImageGrab
impo ...[/quote]
[mw_shl_code=asm,true] 
# TrWebOCR 识别
            url = "http://192.168.6.196:8089"
            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)
            try:
                tempStr = ''
                data = json.loads(content)
                data = data["data"]["raw_out"]
                for line in data:
                    tempStr += line[1]+"\n"
                print(tempStr)
                pyperclip.copy(tempStr)
            except Exception as e:
                print("后台返回数据解析出错: ", str(e))
                pyperclip.copy("ocrFail:" + str(e))
            self.exit()


替换一下
我心所爱 发表于 2023-1-25 17:24
noah88 发表于 2023-1-25 17:32
感谢分享,就是怕配置麻烦
saker1 发表于 2023-1-25 17:36
这是个不错的实用小程序,如果开发个安卓版将会锦上添花。文件占用量以短小精悍为最佳,并且绿色程序。
千军破 发表于 2023-1-25 17:38
多谢分享
ajiYH 发表于 2023-1-25 18:26
感谢分享!!!
csa 发表于 2023-1-25 18:26
下载试用下先,谢谢
nbwww 发表于 2023-1-25 18:28
收藏了  谢谢
lhtzty 发表于 2023-1-25 18:44
谢谢分享!!!!!!!!!
gztf 发表于 2023-1-25 18:45
感谢分享!!!
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 提醒:禁止复制他人回复等『恶意灌水』行为,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2023-2-4 07:34

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表