image和程序一个文件夹内,如何使用image和相对路径修改以下程序,payload = 'image=%2AQJ3AAEC6' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) print(response.text) ,使得打印{"words_result":[{"words":"<body>"},{"words":"<div class=\"ui three column grid\">"},{"words":"<div class=\"two wide column\"></div>"},{"words":"<div class=\"twelve wide column\">"},{"words":"<img class=\"ui image\" src=\"banner. jpg\">"},{"words":"</div>"},{"words":"<div class=\"two wide column\"></div>"},{"words":"</div>"}],"words_result_num":8,"log_id":1667814198721364785}中words所有内容,打印的内容请按行排列
时间: 2023-07-12 10:55:32 浏览: 79
你可以按照以下方法修改代码,使用相对路径来读取图片:
```
import os
import requests
import urllib.parse
import pytesseract
from PIL import Image
# 定义图片路径变量
image_path = os.path.join(os.path.dirname(__file__), 'image.jpg')
# 读取图片二进制数据
with open(image_path, 'rb') as f:
image_data = f.read()
# 构造请求头和请求体
url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
data = {
'image': image_data
}
payload = urllib.parse.urlencode(data)
# 发送POST请求
response = requests.post(url, headers=headers, data=payload)
# 解析响应并输出识别结果
result = response.json()
words_result = result['words_result']
for words in words_result:
print(words['words'])
```
这里使用了`os.path.dirname(__file__)`来获取当前文件所在目录的路径,然后和图片文件名拼接成完整路径。然后使用`open()`函数打开文件并读取二进制数据,将其作为请求体的内容。
最后使用`response.json()`将响应内容解析为JSON格式,然后遍历`words_result`列表,输出其中的`words`字段。输出的结果会按行排列,每一行对应一个`words`字段。
阅读全文