欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python调用mathpix api识别图片中的公式

程序员文章站 2022-06-15 18:20:18
借助mathpix软件可以很方便的识别图片中的公式,复制到word中,可编辑的模式。但是免费版的mathpix只提供每月50次的使用,很难满足要求,但可喜的是他们提供了每月1000次的免费调用接口。https://accounts.mathpix.com/ocr-api/keys登录该网址即可申请app_id和app_key本文参考这篇博客编写了调用的python脚本https://sspai.com/post/57181这个脚本使用起来很简单,通过任意一款截图软件把要是别的图片复制到粘贴板...

借助mathpix软件可以很方便的识别图片中的公式,复制到word中,可编辑的模式。但是免费版的mathpix只提供每月50次的使用,很难满足要求,但可喜的是他们提供了每月1000次的免费调用接口。

https://accounts.mathpix.com/ocr-api/keys

登录该网址即可申请app_id和app_key

本文参考这篇博客编写了调用的python脚本https://sspai.com/post/57181

这个脚本使用起来很简单,通过任意一款截图软件把要是别的图片复制到粘贴板,脚本的功能是把粘贴板的图片保持到d盘,并送到mathpix的识别接口,返回json格式的对象,对其解析得到识别的latex格式的公式,识别结果会显示在console窗口,也会保存在equation.txt文件中,把识别结果复制到word可以显示正常的可编辑的公式,

 # example from https://github.com/Mathpix/api-examples/blob/master/python/mathpix.py

import os,base64,requests,json
from PIL import ImageGrab

env = os.environ
#HOME = env.get('HOME') + "/Desktop/"
HOME = "D:\\"

default_headers = {
    'app_id': env.get('APP_ID', '***********'),
    'app_key': env.get('APP_KEY', '********************'),
    'Content-type': 'application/json'
}

service = 'https://api.mathpix.com/v3/latex'


# Return the base64 encoding of an image with the given filename.
def image_uri(filename):
    image_data = open(filename, "rb").read()
    return "data:image/jpg;base64," + base64.b64encode(image_data).decode()

# Call the Mathpix service with the given arguments, headers, and timeout.
def latex(args, headers=default_headers, timeout=300):
    r = requests.post(service, data=json.dumps(args), headers=headers, timeout=timeout)
    return json.loads(r.text)

def mathpix(): 
# 从剪贴板获取公式  
    im = ImageGrab.grabclipboard()
    im.save(HOME+'screen.png','PNG')
    r = latex({
        'src': image_uri(HOME+"screen.png"),
        "ocr": ["math", "text"], 
        'formats': ['latex_styled']
    })
    print(r['latex_styled'])
    f=open("equation.txt",'a')
    f.write(r['latex_styled']+'\n')
    f.close()
	

if __name__ == '__main__':
    # 调用 macOS 的 screencapture 命令行工具
    #os.system("screencapture -i -c")
    mathpix()

比如

Python调用mathpix api识别图片中的公式

的识别结果是

y = | a + b | / c

在word中插入latex格式的公式,可以转化为正常的显示方式

本文地址:https://blog.csdn.net/yanfeng1022/article/details/108861420