百度AI人体关键点识别跑跑跑

百度AI人体关键点识别跑跑跑

首先,本代码基于这篇博客,感谢大佬详尽的步骤说明,他是在原来基础功能之上增加了:

  • 单图片处理时间
  • 将识别出来的关键点标注在图片上并输出

在此基础上我加了两个改动:

  • 在图像上标注好的每个点旁边增加点名称
  • 仅显示我需要的关键点
import urllib
import base64
import json
import time
from PIL import Image, ImageDraw, ImageFont
import re
import cv2 as cv
import os

from aip import AipBodyAnalysis

#client_id 为官网获取的AK, client_secret 为官网获取的SK
client_id = '你的AK'
client_secret = '你的SK'

#获取token
def get_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
    request = urllib.request.Request(host)
    request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = urllib.request.urlopen(request)
    token_content = response.read()
    if token_content:
        token_info = json.loads(token_content)
        token_key = token_info['access_token']
    return token_key
#画出人体识别结果
def draw_bodys(originfilename,bodys,resultfilename,pointsize):
 
    image_origin = Image.open(originfilename)
    draw =ImageDraw.Draw(image_origin)
    
    for body in bodys:
        x=0
        for body_part in body['body_parts'].values():
            #print(body_part)
            draw.ellipse((body_part['x']-pointsize,body_part['y']-pointsize,body_part['x']+pointsize,body_part['y']+pointsize),fill = "blue")
            font = ImageFont.truetype("consola.ttf", 20, encoding="unic")#设置字体
            draw.text((body_part['x'], body_part['y']), str(list(body['body_parts'].keys())[x]), 'fuchsia', font)
            x=x+1
            # draw.text(image_origin,str(list(body['body_parts'].keys())[x]), (body_part['x'],body_part['y']), cv.FONT_HERSHEY_SIMPLEX,1,(0,0,255), 1, cv.LINE_AA)
        gesture = body['location'] 
        draw.rectangle((gesture['left'],gesture['top'],gesture['left']+gesture['width'],gesture['top']+gesture['height']),outline = "red")
 
    image_origin.save(resultfilename, "JPEG")
      
#人体识别
#filename:原图片名(本地存储包括路径)
def body_analysis(filename,resultfilename,pointsize):
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_analysis"
    print(filename)
    # 二进制方式打开图片文件
    f = open(filename, 'rb')
    img = base64.b64encode(f.read())
    
    params = dict()
    params['image'] = img
    params = urllib.parse.urlencode(params).encode("utf-8")
    #params = json.dumps(params).encode('utf-8')
    
    access_token = get_token()
    begin = time.perf_counter()
    request_url = request_url + "?access_token=" + access_token
    request = urllib.request.Request(url=request_url, data=params)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    response = urllib.request.urlopen(request)
    content = response.read()
    end = time.perf_counter()
 
    print('处理时长:'+'%.2f'%(end-begin)+'秒')
    if content:
        #print(content)
        content=content.decode('utf-8')
        
        #下面这些就是把我不需要的什么鼻子啊,左右嘴角啊,脖子啊这种点给去掉了,但仅仅是不标,并没有不识别
        #去掉的方式就是在已经识别出来的这些点的这个content里找到这些点的名字,在他们后面一个点前面加上“www”字符串,然后识别出要删除的点的名字作为起点,“,www”作为终点,把从起点到终点(包含起点终点)的字符串删掉。这是个笨办法,因为我不知道咋删除字典里的一个键……
        content=add_content(content, '"right_knee"', 'www')
        content=remove_identifiers_and_content(content, '"nose"', ',www', )
        content=add_content(content, '"right_elbow"', 'www')
        content=remove_identifiers_and_content(content, '"left_mouth_corner"', ',www', )
        content=add_content(content, '"left_elbow"', 'www')
        content=remove_identifiers_and_content(content, '"neck"', ',www', )
        content=add_content(content, '"left_ankle"', 'www')
        content=remove_identifiers_and_content(content, '"right_mouth_corner"', ',www', )
        
        print(content)
        data = json.loads(content)
        f2 = open('new_json.json', 'w')
        f2.write(content)
        f2.close()
        #print(data)
        #print(data)
        result=data['person_info']
        
        draw_bodys(filename,result,resultfilename,pointsize)

#下面这俩函数就是为了在content里增减一些字符
def remove_identifiers_and_content(original_string, identifier_A, identifier_B):
    # 将标识符A和B转换为正则表达式,以匹配它们及其之间的任何内容
    pattern = f"{identifier_A}.*?{identifier_B}"
 
    # 使用re.sub()函数替换掉匹配的模式
    modified_string = re.sub(pattern, "", original_string, flags=re.DOTALL)
 
    return modified_string

def add_content(original_string, identifier_A, identifier_B):
    str_index = original_string.find(identifier_A)
    new_str = original_string[:str_index] + identifier_B + original_string[str_index:]
 
    return new_str

base_path = '图片路径,用/这个斜线'
files = os.listdir(base_path)
for path in files:
    print(path)
    body_analysis(base_path+path,'1'+path,2)

接着学吧,真是任重道远呢

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值