「图像分类」是人工智能领域的一个热门话题,我们在实际生活中甚至业务的生产环境里,也经常遇到图像分类相似的需求,如何能快速搭建一个图像分类或者内容识别的 API 呢?
我们考虑使用 Serverless Framework 将图像识别模块部署到腾讯云云函数 SCF 上。
这里我们会用到一个图像相关的库:ImageAI
,官方给了一个简单的 demo:
from imageai.Prediction import ImagePrediction
import os
execution_path = os.getcwd()
prediction = ImagePrediction()
prediction.setModelTypeAsResNet()
prediction.setModelPath(os.path.join(execution_path, "resnet50_weights_tf_dim_ordering_tf_kernels.h5"))
prediction.loadModel()
predictions, probabilities = prediction.predictImage(os.path.join(execution_path, "1.jpg"), result_count=5 )
for eachPrediction, eachProbability in zip(predictions, probabilities):
print(eachPrediction + " : " + eachProbability)
接下来分四步进行:创建项目 → 安装依赖 → 配置 yml 文件 → 部署
本地创建 Python 项目
首先,我们在本地创建一个 Python 的项目:mkdir imageDemo`
然后新建文件:``vim index.py`
from imageai.Prediction import ImagePrediction
import os, base64, random
execution_path = os.getcwd()
prediction = ImagePrediction()
prediction.setModelTypeAsSqueezeNet()
prediction.setModelPath(os.path.join(execution_path, "squeezenet_weights_tf_dim_ordering_tf_kernels.h5"))
prediction.loadModel()
def main_handler(event, context):
imgData = base64.b64decode(event["body"])
fileName = '/tmp/' + "".join(random.sample('zyxwvutsrqponmlkjihgfedcba', 5))
with open(fileName, 'wb') as f:
f.write(imgData)
resultData = {}
predictions, probabilities = prediction.predictImage(fileName, result_count=5)
for eachPredict