python实现截图获取图片内容并翻译

本文介绍了使用Python进行截图内容的提取和翻译的方法。用户只需将图片放入指定目录,脚本即可自动处理。同时,文章还提及了在macOS上设置开机自启该脚本的步骤,提示用户注意修改相关参数。

只需把图片或者截图放到fileDir目录中就可以提取图片的内容

python代码

import os
import time
import pyperclip
from aip import AipOcr


def init():
    APP_ID = "21197258"
    API_KEY = "2nh0SuB0Z1zbZFtR6mfATYVb"
    SECRET_KEY = "rwXvvdP1iufWGhWGWFfwp0oSPE2gDTfN"
    aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    return aipOcr


def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


def result(filePath, options):
    result = ""
    try:
        data = aipOcr.basicGeneral(get_file_content(filePath), options)
    except:
        raise ConnectionError("网络连接异常!")
    words_result = data['words_result']
    for i in range(len(words_result)):
        result += words_result[i]['words']
    pyperclip.copy(result)


if __name__ == '__main__':

    """存放要识别照片的目录"""
    fileDir = r"/Users/jeffrey/screen"

    """只需要的文件类型"""
    fileType = ["png", "jpg", "bmp"]

    """刷新间隔秒数"""
    waitTime = 2

    """定义参数变量"""
    options = {
        'detect_direction': 'true',
        'language_type': 'CHN_ENG',
    }

    """获取指定目录下的文件,第一次运行不会处理这些文件"""
    oldPhotoList = os.listdir(fileDir)
    while True:
        time.sleep(waitTime)
        newPhotoList = os.listdir(fileDir)
        """利用set集合不可重复性获取不一致的信息"""
        diffList = list((set(oldPhotoList) ^ set(newPhotoList)))
        if len(diffList) >= 1:
            for i in diffList:
                oldPhotoList.append(i)
                diffList.remove(i)
                target = fileDir + os.sep + i
                if not os.path.exists(target):
                    print("文件不存在")
                    continue
                if os.path.splitext(target)[-1].replace(".", "") not in fileType:
                    print("这不是一张图片")
                    continue
                aipOcr = init()
                result(target, options)
                print("已将结果复制到粘贴板")
    pass

macOS使用开机自启运行脚本,部分参数需自行修改,如何设置macOS开机启动脚本

# >>> conda initialize >>>
# 切换到python38
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/jeffrey/opt/miniconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/Users/jeffrey/opt/miniconda3/etc/profile.d/conda.sh" ]; then
        . "/Users/jeffrey/opt/miniconda3/etc/profile.d/conda.sh"
    else
        export PATH="/Users/jeffrey/opt/miniconda3/bin:$PATH"
    fi
fi
unset __conda_setup


conda activate py38
cd /Users/jeffrey/Desktop/快捷脚本/py
python OCR图片识别.py```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值