调用百度人体分析api 实现人体分析

这个是调用百度ai平台的人体分析方法。
调用前需要在百度AI平台上注册账号,获得APP_ID,API_KEY ,SECRET_KEY这些。
下面这段代码的思路是,首先读取本地图片,之后将图片传入百度接口,百度运算完毕后返回一组json格式的信息段,其中包括识别出几个人物,每个人物信息,位置。百度的人体分析可以识别出很多东西,比如带没带口罩,男的还是女的。我这里就用到了位置信息。

通过返回每个点的位置,从图像上勾画出人物位置。这里图像方面的操作用到的opencv。
画矩形框函数用的是:cv2.rectangle(image, first_point, last_point, (0, 255, 0), 2)
最后,点击s键,退出程序。

from aip import AipBodyAnalysis
import cv2


""" 你的 APPID AK SK ""

APP_ID = 'xxx'
API_KEY = 'xxx'
SECRET_KEY = 'xxx'

client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)

""" 读取图片 """
image_path = r'./person/1.jpg'


def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


image = get_file_content(image_path)

""" 调用人体检测与属性识别 """
client.bodyAttr(image)

""" 如果有可选参数 """
options = {"type": "gender"}

""" 带参数调用人体检测与属性识别 """
r = client.bodyAttr(image, options)
print(r)

image = cv2.imread(image_path)
person_num = r['person_num']
pinfo = r['person_info']
image_path2 = r'./person/2.jpg'
for i in range(0, person_num):
    p = pinfo[i]
    pl = p['location']
    first_point = (int(pl['left']), int(pl['top']))
    last_point = ( int(pl['left'])+ int(pl['width']),int(pl['top']) + int(pl['height']) )
    cv2.rectangle(image, first_point, last_point, (0, 255, 0), 2)
cv2.namedWindow('image', cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
cv2.imshow('image', image)
k = cv2.waitKey(0)

if k == ord('s'):
    cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/jayandchuxu/article/details/106975405