python图片审核
程序员文章站
2022-03-03 22:00:43
图片文字提取需求需要,上传商品时不可上传不可私营产品,例如香烟、食盐等,以下仅供参考,如想放入生产环境,需要谨慎import requestsimport base64def get_word_token(): url = 'https://aip.baidubce.com/oauth/2.0/token' data = { 'grant_type': 'client_credentials', # 固定值 'client_id': 'Su6KS...
图片文字提取
需求需要,上传商品时不可上传不可私营产品,例如香烟、食盐等,以下仅供参考,如想放入生产环境,需要谨慎
import requests
import base64
def get_word_token():
url = 'https://aip.baidubce.com/oauth/2.0/token'
data = {
'grant_type': 'client_credentials', # 固定值
'client_id': 'Su6KSI9M7cTs9****A93dg3Z', # 在开放平台注册后所建应用的API Key
'client_secret': 'aCbgVGLLc0f****VD4LcqRwHZmf1Ee4E' # 所建应用的Secret Key
}
res = requests.post(url, data=data)
res = res.json()
print(res)
access_token = res['access_token']
return access_token
def distinguish_word():
"""提取图片上的文字进行判断"""
try:
dis_word_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic" # 通用文字识别接口(还可以提高识别精度有另外接口)
# 二进制方式打开图片文件
f = open('文字图片/c.jpg', 'rb')
word_img = base64.b64encode(f.read())
params = {"image":word_img, "language_type":"CHN_ENG"}
dis_token = get_word_token()
request_url = dis_word_url + "?access_token=" + dis_token
# print(request_url)
headers = {'content-type': 'text/html;charset=UTF-8'}
response = requests.post(request_url, data=params, headers=headers)
res = response.json()
print("请求信息:",res)
if response:
res = response.json()["words_result"]
mg = []
for i in res:
msg = i["words"]
mg.append(msg)
if any("烟" in s for s in mg):
print("香烟不可上传")
elif any("盐" in s for s in mg):
print("食盐不可上传")
except:
pass
if __name__ == '__main__':
distinguish_word()