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

借助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()

比如

的识别结果是

y = | a + b | / c

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

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oceanstonetree

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值