目的
无需购买服务器搭建一个图片鉴黄接口 (Python语言)
Lambda介绍 : https://aws.amazon.com/cn/lambda/
AWS的Lambda控制台首页: https://console.aws.amazon.com/lambda/home
图片鉴黄文档:https://docs.aws.amazon.com/zh_cn/rekognition/latest/dg/procedure-moderate-images.html
1.创建函数
选择第一个:从头开始创作 --> 输入:函数名称 --> 运行时环境选择Python
AWS支持多种语言,.Net、Go、Java、Node.js、Python和Ruby
选择“创建具有基本Lambda权限的新角色”,如果你已经有了角色,就选择第二个吧。
2.权限配置
你可以编辑此无服务函数占用的最大内存数,通常256MB和512MB就可用了
然后去配置此Lambda函数可以访问哪些AWS的资源;先点击权限 --> 然后点击配置名称 ,就可以去配置角色了
现在,我们去添加此Lambda函数可访问的AWS服务,点击附加策略
添加AWS的识别服务策略 官方文档
如果此Lambda函数希望访问S3桶的数据,那就需要添加
3.代码编写
点击测试,会有以下输出
完整的代码如下:
import json
import boto3
def recognize_S3_image(photo, bucket):
# 识别图片源来自S3桶
client = boto3.client('rekognition')
response = client.detect_moderation_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}})
return handle_result(response)
def recognize_base64_image(image_base64_encoded):
# 识别图片源来自base64编码
client = boto3.client('rekognition')
response = client.detect_moderation_labels(Image={'Bytes':image_base64_encoded})
print("识别成功!")
return handle_result(response)
def handle_result(response):
max_confidence = 0
optimal_name = ""
parent_name = ""
for label in response['ModerationLabels']:
if label['Confidence'] > max_confidence:
max_confidence = label['Confidence']
optimal_name = label['Name']
parent_name = label['ParentName']
return max_confidence, optimal_name
def lambda_handler(event, context):
print("============================================")
print(event)
# 获取
# image_base64_encoded = event["image"]
# if image_base64_encoded is None and len(image_base64_encoded) < 0:
# return
# max_confidence, optimal_name = recognize_base64_image(image_base64_encoded)
# 识别S3桶图片
max_confidence, optimal_name = recognize_S3_image('test_porn.jpeg', 'yooul-recognition')
return {
'statusCode': 200,
'body': {
"confidence" : max_confidence,
"label" : optimal_name
}
}
4.公网访问
需要配置API Gateway