识别文件夹里面所有图片的数字,在文本中显示,按001,002,003依次到9999。代码
时间: 2024-09-23 21:07:48 浏览: 74
在Python中,你可以使用`os`模块来遍历文件夹,`PIL`库读取图片内容,然后利用`pytesseract`库进行OCR识别。这里提供一个基本的示例,假设你已经安装了`opencv-python`, `pytesseract`和`tqdm`库:
```python
import os
from PIL import Image
import pytesseract
import cv2
# 定义OCR识别函数
def ocr_image(img_path):
gray = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2GRAY)
text = pytesseract.image_to_string(gray, lang='chi_sim') # 使用中文语言模型
return text.strip()
# 定义目标目录
folder_path = 'your_folder_path'
# 初始化结果文本列表
image_numbers = []
# 遍历文件夹内的所有.jpg或.png图片
for filename in os.listdir(folder_path):
if filename.endswith(('.jpg', '.jpeg', '.png')):
img_path = os.path.join(folder_path, filename)
number = ocr_image(img_path)
if number.isdigit() and len(number) == 4: # 检查识别出的是4位数字
image_numbers.append(number)
# 将数字按序排列并输出到文本文件
image_numbers.sort(key=int)
with open('output.txt', 'w', encoding='utf-8') as f:
for num in image_numbers:
f.write(f'{num}\n')
print("识别完成并保存到output.txt文件中")
```
注意,此代码假定图片中的数字清晰易读,且大部分是正向的。实际应用中可能需要进行额外的预处理,如旋转校正、增强对比度等。此外,`pytesseract`的识别效果可能会受到图片质量和文字布局的影响。
阅读全文
相关推荐



















