python-tesseract - 如何使用 python tesseract 将所有类型的图像转换为文本
问题描述
我正在尝试使用 python tesseract 将文件夹中的所有类型的图像转换为文本。下面是我正在使用的,只有 .png 文件被转换为 .txt,其他类型没有被转换为文本。
import os
import pytesseract
import cv2
import re
import glob
import concurrent.futures
import time
def ocr(img_path):
out_dir = "Output//"
img = cv2.imread(img_path)
text = pytesseract.image_to_string(img,lang='eng',config='--psm 6')
out_file = re.sub(".png",".txt",img_path.split("\\")[-1])
out_path = out_dir + out_file
fd = open(out_path,"w")
fd.write("%s" %text)
return out_file
os.environ['OMP_THREAD_LIMIT'] = '1'
def main():
path = input("Enter the path : ")
if os.path.isdir(path) == 1:
out_dir = "ocr_results//"
if not os.path.exists(out_dir):
os.makedirs(out_dir)
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
image_list = glob.glob(path+"\\*.*")
for img_path,out_file in zip(image_list,executor.map(ocr,image_list)):
print(img_path.split("\\")[-1],',',out_file,', processed')
if __name__ == '__main__':
start = time.time()
main()
end = time.time()
print(end-start)
如何将所有类型的图像文件转换为文本。请帮我处理上面的代码。
解决方案
函数中存在错误ocr
。
首先,以下确实将所有类型的图像文件转换为文本。
text = pytesseract.image_to_string(img,lang='eng',config='--psm 6'))
然而,下一段代码的作用是
- 使用正则表达式选择具有
.png
扩展名的文件 - 创建具有相同文件名和
.txt
扩展名的新路径 将 OCR 输出写入新创建的文本文件。
out_file = re.sub(".png",".txt",img_path.split("\\")[-1]) out_path = out_dir + out_file fd = open(out_path,"w") fd.write("%s" %text)
换句话说,所有类型的图像文件都已转换,但并非所有类型都正确写回。正则表达式匹配逻辑仅替换.png
为.txt
并分配给out_path
. 当没有.png
(其他图像类型)时,变量获得与原始文件名相同的值(例如sampe.jpg
)。接下来的代码行打开原始图像并用 OCR 结果覆盖。
一种解决方法是将要覆盖的所有图像格式添加到正则表达式中。
例如,
out_file = re.sub(".png|.jpg|.bmp|.tiff",".txt",img_path.split("\\")[-1])
推荐阅读
- sql - 基于 DATE_TRUNC 的 SQL 查询中的项目计数总和
- android - 如何从firebase预构建登录ui注销
- bash - Bash:运行命令的最有效方式(命令“可能”或“可能不”存在
- php - 删除与字符串上的模式匹配的单词
- matlab - Matlab随机数rng:选择种子
- javascript - 禁用提交按钮,直到重新获取 recaptcha3 g-recaptcha-response 值
- css - Squarespace 日历颜色更改的自定义 CSS
- r - R:将连续日期从单列转换为 2 列范围
- css - 弹性盒屏幕的 IE11 问题不适合 Angular8
- html - 如何在引导程序 4.3.1 中获取日期选择器