在批量处理图片文件时可能存在如图情况:希望使用图片中人名等特定字符作为文件名取代原文件名。
本文使用Python实现该功能,主要步骤为以下两步:
一、安装Tesseract及PIL
1. 参照此教程安装Tesseract。
pip install pytesseract
2. 安装PIL
pip install Pillow
二、功能实现
from PIL import Image
import pytesseract
from os import listdir
file_name = listdir('E:/ocr/path') #获取目标目录下所有文件名
for f_name in file_name:
try:
f_name = f_name.strip('.jpg')
im = Image.open(f'E:/ocr/path/{f_name}.jpg')
text = pytesseract.image_to_string(im, lang='chi_sim')
subtext = "XXX" #选择目标文字附近的定位字符
text = text.replace(" ","")
name = text[text.rfind(subtext):][4:7] #获取目标文字