寫部落格時,數學公式的編輯比較佔用時間,在上一篇中詳細介紹瞭如何在Markdown
中編輯數學符號與公式。
https://www.cnblogs.com/bytesfly/p/markdown-formula.html
當然,有時候我們僅僅是想把現成的公式搬到markdown
中來編輯,此時如果有工具能把公式截圖直接解析成Latex
程式碼就方便了。
剛好這幾天看到好幾個微信公眾號都在推送image-to-latex
這個開源專案:
https://github.com/kingyiusuen/image-to-latex
Convert images of LaTex math equations into LaTex code.
該專案當前(2021年09月02日)star人數為631,Fork為81:
最近正好也是在瞭解機器學習、深度學習相關的東西,於是打算上手感受一下轉換效果。
百聞不如一試
其實image-to-latex
這個專案的README
寫得算是比較清楚了,介紹了專案的來龍去脈、可以改進的地方、如何使用等等。
快速開始
下面我把自己第一次嘗試的過程簡單記錄如下:
- 克隆專案
git clone --depth=1 https://github.com/kingyiusuen/image-to-latex.git
cd image-to-latex
多囉嗦一句:
--depth: 用來指定克隆的深度,1表示克隆最近的一次commit。這種方法克隆是為了減小專案體積的,加快克隆速度,對於那種龐大且活躍的開源專案非常有效。
- 準備Python環境
該專案依賴Python環境,由於我用的是conda
來管理虛擬環境的,不是用venv
,所以這裡的步驟可能與README
上的有一點點差異。
此時應該是在專案目錄下,即image-to-latex
目錄,該目錄下有requirements.txt
檔案。
# 建立新的python3.6環境
conda create --name latex python=3.6
# 啟用環境
conda activate latex
# 安裝依賴
pip install -r requirements.txt
關於Python環境的搭建,可以參考我之前的部落格:
https://www.cnblogs.com/bytesfly/p/python-environment.html
- 下載模型
For example, you can use the following command to download my best run.
到了這步本該是模型訓練(Model Training
),我這裡僅想體驗一下,可以直接下載別人已經訓練好的模型。
python scripts/download_checkpoint.py kingyiusuen/image-to-latex/1w1abmg1
此時shell顯示如下:
(latex) ➜ python scripts/download_checkpoint.py kingyiusuen/image-to-latex/1w1abmg1
wandb: (1) Create a W&B account
wandb: (2) Use an existing W&B account
wandb: (3) Don't visualize my results
wandb: Enter your choice: 3
wandb: You chose 'Don't visualize my results'
Downloading model checkpoint...
Model checkpoint downloaded to image-to-latex/artifacts/model.pt.
下載需要稍微等等,模型有將近2個G的大小。
- 啟動服務
(1) 啟動後端服務,執行命令make api
An API is created to make predictions using the trained model.
看下專案的Makefile
檔案,其實make api
就是呼叫了下面的啟動命令:
uvicorn api.app:app --host 0.0.0.0 --port 8000 --reload --reload-dir image-to-latex --reload-dir api
瀏覽器開啟 http://localhost:8000/docs ,看到介面文件如下:
(2) 啟動前端介面,執行命令make streamlit
同樣,看下專案的Makefile
檔案,其實make streamlit
呼叫了下面的啟動命令:
streamlit run streamlit/app.py
瀏覽器開啟 http://localhost:8501/ ,就是上傳圖片的介面:
至此,image-to-latex
就成功啟動了,下面就期待轉換公式的效果了!
上手體驗
下面我作為一個小白使用者,體驗一下image-to-latex
的轉換效果。
我從之前的部落格中截圖了10個公式,使用下來,感覺當前的效果並非太理想。注意,個別解析出來僅是缺少了右}
,這種也可以算解析出來了。如下:
測試來看,貌似對多行公式的解析不太好。當然了,有這樣的免費工具來輔助我們把公式圖片轉成Latex
程式碼已經讓人挺驚喜了。相信以後隨著更多的人蔘與演算法的優化、模型的改善,解析的效果會更好。
寫在後面
I found a pretty established tool called Mathpix Snip that converts handwritten formulas into LaTex code.
image-to-latex
這個專案的README
裡也提到了mathpix
這個更加成熟的工具。免費版每月能識別50次公式圖片。詳情見:
下載試了下,識別的效果確實不錯。(注意:非廣告,本人與mathpix
無任何關係,僅僅試了下而已!!!)
百聞不如一試,動手嘗試之後才有發言權。後面有時間會看看image-to-latex
的程式碼實現,學習學習。