简介:本文详细介绍如何使用Python实现图片转文字、语音转文字、文字转语音并保存音频文件,覆盖OCR识别、语音转文本、语音合成三大技术模块,提供完整代码示例与实用建议。
OCR(Optical Character Recognition)技术通过图像处理与模式识别将图片中的文字转换为可编辑文本。Python中常用的OCR库包括:
import pytesseractfrom PIL import Imageimport cv2def image_to_text(image_path, lang='chi_sim+eng'):"""图片转文字主函数:param image_path: 图片路径:param lang: 语言包(中文简体+英文):return: 识别结果文本"""# 图像预处理(可选)img = cv2.imread(image_path)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)_, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)# 使用Tesseract进行OCR识别text = pytesseract.image_to_string(binary, lang=lang)return text# 使用示例if __name__ == '__main__':result = image_to_text('test.png')print("识别结果:\n", result)
chi_sim.traineddata语言包os.listdir()遍历文件夹批量处理图片语音转文字(ASR)技术方案包括:
from vosk import Model, KaldiRecognizerimport pyaudioimport wavedef audio_to_text(audio_path, model_path='vosk-model-small-cn-0.3'):"""语音转文字主函数:param audio_path: 音频文件路径(16kHz 16bit PCM WAV):param model_path: 模型路径:return: 识别结果文本"""# 加载模型model = Model(model_path)# 读取音频文件wf = wave.open(audio_path, "rb")rec = KaldiRecognizer(model, wf.getframerate())# 逐帧识别while True:data = wf.readframes(4000)if len(data) == 0:breakif rec.AcceptWaveform(data):result = rec.Result()return eval(result)["text"] # 解析JSON结果# 使用示例if __name__ == '__main__':text = audio_to_text('test.wav')print("识别结果:", text)
import pyaudioimport queueimport threadingdef realtime_asr(model_path, output_queue):p = pyaudio.PyAudio()stream = p.open(format=pyaudio.paInt16, channels=1,rate=16000, input=True, frames_per_buffer=4000)model = Model(model_path)rec = KaldiRecognizer(model, 16000)while True:data = stream.read(4000)if rec.AcceptWaveform(data):result = rec.Result()output_queue.put(eval(result)["text"])# 多线程实现实时识别q = queue.Queue()t = threading.Thread(target=realtime_asr, args=('vosk-model-small-cn-0.3', q))t.start()while True:if not q.empty():print("实时识别结果:", q.get())
| 方案 | 优点 | 缺点 |
|---|---|---|
| pyttsx3 | 离线使用,支持多语言 | 语音质量一般 |
| edge-tts | 高质量语音,支持SSML | 需联网,有调用限制 |
| 微软TTS API | 商业级语音质量 | 需付费,有调用次数限制 |
import asynciofrom edge_tts import Communicateimport osasync def text_to_speech(text, voice='zh-CN-YunxiNeural', output_file='output.mp3'):"""文字转语音主函数:param text: 待转换文本:param voice: 语音类型(中文推荐使用Yunxi/Yunye):param output_file: 输出音频路径"""communicate = Communicate(text, voice)await communicate.save(output_file)# 使用示例if __name__ == '__main__':text = "这是需要转换的文本内容"asyncio.get_event_loop().run_until_complete(text_to_speech(text, 'zh-CN-YunxiNeural'))print(f"音频已保存至 output.mp3")
import pyttsx3def offline_tts(text, output_file='output.wav'):"""离线文字转语音:param text: 待转换文本:param output_file: 输出音频路径"""engine = pyttsx3.init()# 设置语音属性(Windows系统有效)voices = engine.getProperty('voices')engine.setProperty('voice', voices[1].id) # 1为女性语音engine.setProperty('rate', 150) # 语速# 保存为音频文件engine.save_to_file(text, output_file)engine.runAndWait()# 使用示例offline_tts("这是离线合成的语音", "offline_output.wav")
import osfrom edge_tts import Communicateimport pygamedef full_process(image_path, voice='zh-CN-YunxiNeural'):# 1. 图片转文字text = image_to_text(image_path)print("识别结果:", text)# 2. 文字转语音output_file = "temp_audio.mp3"asyncio.get_event_loop().run_until_complete(text_to_speech(text, voice, output_file))# 3. 播放音频pygame.mixer.init()pygame.mixer.music.load(output_file)pygame.mixer.music.play()# 等待播放完成while pygame.mixer.music.get_busy():continue# 清理临时文件os.remove(output_file)# 使用示例full_process('document.png')
| 场景 | 推荐方案 |
|---|---|
| 离线环境 | Vosk(ASR) + pyttsx3(TTS) |
| 高精度需求 | 云服务API + edge-tts |
| 实时处理 | Vosk实时识别 + 边缘计算设备 |
| 移动端部署 | Flutter集成TFLite模型 |
concurrent.futures实现并行处理
# 下载中文语言包后指定路径pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'text = pytesseract.image_to_string(img, lang='chi_sim')
解决方案:
# 分段合成(每500字符一段)def split_text(text, max_len=500):return [text[i:i+max_len] for i in range(0, len(text), max_len)]segments = split_text("长文本内容")for i, seg in enumerate(segments):await text_to_speech(seg, f'output_{i}.mp3')
本文提供的完整代码与方案经过实际项目验证,开发者可根据具体需求调整参数。建议从离线方案开始实践,逐步过渡到云服务集成,最终实现高可用性的多模态AI应用。