使用百度api与oenpcv完成图片人脸检测并显示

前言

  • 最近花了点时间搭建了一个个人博客,hh! 还是挺开心的!欢迎各位访问
    www.guokangjie.cn
  • 其实快大二的时候,我就学了一部分opencv。但那时自己实在是太菜!! hh
    使用百度api与oenpcv完成图片人脸检测并显示
    最近看到bi站一个可爱的女博主的视频,使用python和opencv画出非常奈斯的图片,我知道必须使用一波opencv了 哈哈!!(地址: 点击跳转
    关于语言的使用,呃呃,选择使用一下当下上升趋势最快的 python 感受一下hh

言归正传:

其实关于opencv自己本身就可以做出人脸识别了,但是这里先不说,使用一下百度提供的免费人脸检测API 地址:点击跳转,免费的,直接注册,再申请一个应用即可

使用

下载sdk 我这里下载的是python的 ,地址:点击跳转
下完以后配置相关参数,在根据返回的参数完成图片展示即可 ,先看效果
使用百度api与oenpcv完成图片人脸检测并显示

代码

import base64
import cv2 as cv
from aip import AipFace


# 你的 APPID AK SK
def get_api_client():
    APP_ID = '你的 App ID'
    API_KEY = '你的 Api Key'
    SECRET_KEY = '你的 Secret Ke'
    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
    return client


#将图片转为base64编码格式
def img2base64(path: str):
    f = open(path, 'rb')
    image = base64.b64encode(f.read())
    image64 = str(image, 'utf-8')
    return image64


def show_image(face_list, path: str):
    left = int(face_list[0]['location']['left'])
    top = int(face_list[0]['location']['top'])
    width = int(face_list[0]['location']['width'])
    height = int(face_list[0]['location']['height'])
    img = cv.imread(path)                                  # 426 71 98 85  height = 400  640
    print("%d %d %d %d %d %d" % (left, top, width, height, img.shape[0], img.shape[1]))
    cv.rectangle(img, (left, top), (left+width, top+height), (0, 0, 255), 3)
    cv.imshow("check face", img)


# 如果有可选参数
options = {}
options["face_field"] = "age"
options["max_face_num"] = 2
options["face_type"] = "LIVE"


image_type = "BASE64"
client = get_api_client()
image64 = img2base64('image/002.jpg')
res = client.detect(image64, image_type, options)

if res['error_code'] == 0:
    face_list = res['result']['face_list']
    show_image(face_list,'image/002.jpg')
    cv.waitKey(0)
    cv.destroyAllWindows()
else:
    print("调用api失败")

写到这里我不禁感叹一句API大法好!!! 过几天下次博客使用opencv完成该部分工作