-
Notifications
You must be signed in to change notification settings - Fork 3
/
ocrapi.py
53 lines (44 loc) · 1.82 KB
/
ocrapi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os
import base64
import requests
import json
# OCR API的URL
ocr_api_url = "http://127.0.0.1:1224/api/ocr"
# 图像文件夹的路径
image_folder_path = "output/test01"
# 遍历文件夹中的所有文件
for filename in os.listdir(image_folder_path):
# 检查文件是否是图像
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff')):
# 构建文件的完整路径
file_path = os.path.join(image_folder_path, filename)
# 读取图像文件并转换为Base64编码
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
# 构建请求数据
data = {
"base64": encoded_string,
}
headers = {"Content-Type": "application/json"}
data_str = json.dumps(data)
# 发送POST请求
response = requests.post(ocr_api_url, data=data_str, headers=headers)
# 检查响应状态
if response.status_code == 200:
# 解析响应内容
res_dict = json.loads(response.text)
# 检查返回的数据结构
if "data" in res_dict and isinstance(res_dict["data"], list):
# 遍历每一行的文本
for line in res_dict["data"]:
text = line.get("text", "")
score = line.get("score", 0)
end = line.get("end", "")
print(f"文本: {text}")
# 如果不是行尾,输出换行符
if end != "\n":
print()
else:
print("没有检测到文本行。")
else:
print(f"请求失败,状态码:{response.status_code}, 文件:{filename}")