mathpix_ocr.py 990 B

1234567891011121314151617181920212223242526272829303132
  1. import base64
  2. import requests
  3. import json
  4. import cv2
  5. import numpy as np
  6. def opecv2base64(img):
  7. image = cv2.imencode('.jpg', img)[1]
  8. base64_data = str(base64.b64encode(image))[2:-1]
  9. return base64_data
  10. def mathpix_api(img):
  11. image = opecv2base64(img)
  12. image_uri = "data:image/jpg;base64," + image
  13. r = requests.post("https://api.mathpix.com/v3/latex",
  14. data=json.dumps({'src': image_uri,
  15. 'formats': ['latex_normal', 'latex_styled']}),
  16. headers={"app_id": "1092963746_qq_com", "app_key": "0c3b77b0c3720175e0ba",
  17. "Content-type": "application/json"},
  18. timeout=7).json()
  19. res = r['latex_styled']
  20. latex_confidence = r['latex_confidence']
  21. # print(res)
  22. return res, latex_confidence
  23. if __name__ == '__main__':
  24. img_path0 = r'F:\save\img_withbgm\0003.png'
  25. img0 = np.asarray(cv2.imread(img_path0))
  26. mathpix_api(img0)