2023年12月7日 星期四

jpg2txt圖檔轉換為文字檔(PYTHON)

作業環境前置準備:

 安裝必要性元件(辨識核心元件tesseract-ocr 需下載安裝,外加要辦識之語系)

 

安裝相關套件

 pip install pillow

 pip install pytesseract

 

 PYTHON程式,如下:

# -*- coding: utf-8 -*-
'''
python取圖檔,辨識中文
'''
#'開啟檔案總管 (開啟轉換後之檔案使用)'
import os,sys
import subprocess
import glob
from os import path

from PIL import Image
import pytesseract

#'開啟GUI 取得來源檔(準備欲轉換聲音來源,開啟檔案對話視窗宣告處理)
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename(initialdir = "/",title = "Select file for OCR (選擇欲辨識圖檔轉文字檔)",filetypes = (("JPG files","*.jpg"),("JPEG files","*.jpeg"),("All files","*.*")))

#'預設位址如下,但如安裝不同處,需告訴PYHTON 辨識核心元件在哪,如此方能辦識處理
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'

img = Image.open(file_path)
text1 = pytesseract.image_to_string(img, lang='chi_tra')


with open('file.txt', mode = 'w') as f:
    f.write(text1)
    f.close()

#'將剛才圖檔辨識後結果,以檔案總管直接將它開啟查閱
subprocess.Popen('explorer "file.txt"')