盒子
盒子
文章目录
  1. 言归正传:
  2. 使用
    1. 代码

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

# 前言**:

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

言归正传:

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

使用

下载sdk 我这里下载的是python的 ,地址:点击跳转
下完以后配置相关参数,在根据返回的参数完成图片展示即可 ,先看效果
效果图

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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完成该部分工作

希望对您有所帮助
May all the ordinary are great, all the ignoble bloom
  • smile