本文共 2616 字,大约阅读时间需要 8 分钟。
PyTesseract是基于Python的OCR工具,依托Google的Tesseract-OCR引擎,支持多种图片格式(如JPG、PNG、GIF等)转文字识别。
通过pip安装(建议使用pip3):
pip install pytesseract==0.3.10 pillow==10.4.0 Tesseract是开源OCR引擎,支持多语言文字识别,安装方法如下:
Tesseract OCR GitHub地址:https://github.com/tesseract-ocr/tesseractWindows安装地址:https://digi.bib.uni-mannheim.de/tesseractMac/Linux安装方法:https://tesseract-ocr.github.io/tessdoc/Installation.html 安装完成后,建议设置PATH环境变量和TESSDATA_PREFIX变量:
PATH="D:\Development\Tesseract-OCR;..."; TESSDATA_PREFIX="D:\Development\Tesseract-OCR\tessdata"; import pytesseractfrom PIL import Image def image_to_string(image_path, language='chi_sim'):image = Image.open(image_path)enhancer = ImageEnhance.Contrast(image)img_contrast = enhancer.enhance(2.0)text = pytesseract.image_to_string(img_contrast, lang=language)return text
登录百度AI开放平台,进入“控制台—人工智能—语音技术”界面,获取APPID、API KEY、SECRET KEY。
pip install baidu-aip==4.16.13 from aip import AipSpeechclass SpeechRecognition(APIView):def post(self, request):try:APP_ID = '' # 替换为你的APPIDAPI_KEY = '' # 替换为你的API KEYSECRET_KEY = '' # 替换为你的SECRET KEY
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) audio_file = 'media\\audio\\16k.wav' # 语音文件路径 with open(audio_file, 'rb') as fp: audio_data = fp.read() res = client.asr(audio_data, 'wav', 16000, { 'dev_pid': 1536, }) if res['err_no'] == 0: ret['data'] = res['result'][0] else: ret['code'] = 101 ret['msg'] = res['err_msg'] except Exception as e: ret['code'] = 102 ret['msg'] = e return Response(ret) pip install speech 由于Speech模块最初开发于Python 2.x,在Python 3.x中需手动调整源文件,建议参考官方文档进行配置。
import speech def speak(text):speech.say(text)speech.runAndWait()speech.stop()
pip install pyttsx3 import pyttsx3def text_to_audio(text, language, rate, volume, filename):engine = pyttsx3.init()engine.setProperty('rate', rate)engine.setProperty('volume', volume)voices = engine.getProperty('voices')
if language == 0: engine.setProperty('voice', voices[0].id)elif language == 1: engine.setProperty('voice', voices[1].id)engine.say(text)engine.save_to_file(text, filename)engine.runAndWait()engine.stop() def main(): text = """从前,有一座美丽的大森林...""" pyttsx3(text=text, language=0, rate=200, volume=0.9, filename="media\\audio\\ptttsx3中文测试.mp3", sayit=1) if name == 'main':main()
转载地址:http://mjofk.baihongyu.com/