【python】人脸检测与属性分析-检测人脸并框出来

该博客介绍了如何使用Python进行人脸检测,通过OpenCV库找出图片中的人脸位置,并将其框出来,实现对人脸区域的精准定位。
摘要由CSDN通过智能技术生成

1、检测图片是否有人脸,有的话打印人脸范围区域

# encoding:utf-8
import base64
import json

import requests

'''
获取access_token函数
'''


def get_access_token(client_id="3bbdU8i9o7bMg4Wg0KSbNamr", client_secret="GvesuaedzQucRZdvgf9FikS57yc00xMd"):
    # client_id 为官网获取的AK, client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=3bbdU8i9o7bMg4Wg0KSbNamr&client_secret=GvesuaedzQucRZdvgf9FikS57yc00xMd'
    print(host)
    response = requests.get(host)
    if response:
        print(response.json(), type(response.json()))
        # 访问服务器所给的令牌口令
        print(response.json()["access_token"])
        return response.json()["access_token"]


'''
人脸检测与属性分析
'''
# 请求的网址
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
# 图片处理的方式
img_file = open("lyf.jpg", "rb")
img_base64 = base64.b64encode(img_file.read())
# print(img_base64,type(img_base64))
# 请求参数
params = {
    "image": str(img_base64,'utf-8'),  # 强转str序列化,记得加编码格式
    "image_type": "BASE64",
    "max_face_num": 2
}
params = json.dumps(params)
access_token = get_access_token()
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}

response = requests.post(request_url, data=params, headers=headers)
if response:
    # print(response.json())

    result=response.json()['result']
    #  如果result存在,表示有人脸
    if result:
        # 拿到人脸区域范围
        print(result['face_list'][0]['location'])
        left=result['face_list'][0]['location']['left']
        top = result['face_list'][0]['location']['top']
        width = result['face_list'][0]['location']['width']
        height = result['face_list'][0]['location']['height']
        print(left,top,width,height)

 2、利用opencv框出人脸区域

# 框出人脸范围
    img_mat=cv2.imread("lyf.jpg")#读取图片
    cv2.rectangle(img_mat,(left,top),(left+width,top+height),(0,0,255),2)
    cv2.imshow("img_lyf",img_mat)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值