人脸检索 M:N(视频,摄像头),调用百度API

目录

创建百度智能云账号

代码部分:


创建百度智能云账号

网址:

 百度智能云-云智一体深入产业

点击导航栏中的产品,再选择人脸与人体

再选择人脸搜索

进入后,可以先去领取免费资源,如果不领取,后面是无法调用api的,建议是把所有的免费资源都领取,我是全部都领取了。

然后就是创建应用,按照要求填写就好。

创建成功后,可以在应用列表看到自己创建好的应用。下图用红色方框圈起来的在后续代码中需要填写。

接着我们可以创建我们的可视化人脸库。

按照要求创建即可,下图是我已经创建成功的。

再点进自己创建好的人脸库,创建分组,这里我已经创建好了四个分组,接着就是进入分组,创建用户,添加图片

这一切完成后,就有了自己的人像数据库。

代码部分:

完整代码:

import cv2
from aip import AipFace
from io import BytesIO
import base64
from PIL import Image,ImageDraw, ImageFont
import threading
import numpy as np
import imutils
import time# 在图像上绘制文本
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))# 创建一个可以在给定图像上绘图的对象draw = ImageDraw.Draw(img)# 字体的格式fontStyle = ImageFont.truetype("simsun.ttc", textSize, encoding="utf-8")# 绘制文本draw.text((left, top), text, textColor, font=fontStyle)# 转换回OpenCV格式return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)# 将图像格式转换为base64格式
def frame2base64(frame):img = Image.fromarray(frame)  # 将每一帧转为Imageoutput_buffer = BytesIO()  # 创建一个BytesIOimg.save(output_buffer, format='JPEG')  # 写入output_bufferbyte_data = output_buffer.getvalue()  # 在内存中读取base64_data = base64.b64encode(byte_data)  # 转为BASE64return base64_data  # 转码成功 返回base64编码def process(image,ls):""" 调用人脸检测 """""" 如果有可选参数 """# 换成自己的百度appidAPP_ID = ''API_KEY = ''SECRET_KEY = ''groupIdList = ''imageType = 'BASE64'base64 = frame2base64(image)base64 = str(base64,'UTF-8')options = {}options["max_face_num"] = 10options["face_type"] = "LIVE"options["match_threshold"] = 0#options["liveness_control"] = "NORMAL"client = AipFace(APP_ID, API_KEY, SECRET_KEY)""" 如果有可选参数 """options = {}options["max_face_num"] = 10options["match_threshold"] = 0options["quality_control"] = "LOW"options["liveness_control"] = "LOW"options["max_user_num"] = 7start3 = time.time()json1 = client.multiSearch(base64, imageType, groupIdList, options)print("*******:", time.time() - start3)print("json1:", json1)if json1['error_msg'] == 'SUCCESS':face_num = json1['result']['face_num']for i in range(face_num):x = max(int(json1['result']['face_list'][i]['location']['left']), 0)y = max(int(json1['result']['face_list'][i]['location']['top']), 0)width = int(json1['result']['face_list'][i]['location']['width'])height = int(json1['result']['face_list'][i]['location']['height'])cv2.rectangle(image, (x, y), (x + width, y + height), (0, 0, 255), 2)print("$$$$$$$$$$$$$$$$$$$$$$$$$")print("json1:", json1)if json1['result']['face_list'][i]['user_list'][0]['score']>70:print(json1['result']['face_list'][i]['user_list'][0]['user_id'])image = cv2ImgAddText(image, json1['result']['face_list'][i]['user_list'][0]['user_id'],max(x - 20, 0), max(y - 20, 0), (255, 0, 0), 60)else:image = cv2ImgAddText(image, "访客",max(x - 20, 0), max(y - 20, 0), (255, 0, 0), 60)ls.append(image)else:print("************************")print("没有检测到人脸:", json1)def main():# 使用摄像头检测# video_capture = cv2.VideoCapture(0)# 使用本地视频文件检测video_capture = cv2.VideoCapture('test6.mp4')fps_time =0f = 0start = time.time()while True:f += 1ls = []if f == 30:print("时间到:", time.time()-start)breakret, frame = video_capture.read()# t = threading.Thread(target=process, args=(frame, ls))  # 使用线程# t.start()# t.join()process(frame, ls)frame = ls[0] if ls else frameframe = imutils.resize(frame, width=400)frame = cv2.putText(frame, '%d, FPS: %f' % (f, 1.0 / (time.time() - fps_time)),(10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)fps_time = time.time()cv2.imshow('wx', frame)if cv2.waitKey(1) & 0xFF == ord('Q'):cv2.destroyAllWindows()video_capture.release()break
if __name__ == "__main__":main()

后续写了一点 注册,更新人脸数据库的代码:

from aip import AipFace
from PIL import Image
from io import BytesIO
import base64def frame2base64(image_path):# img = Image.fromarray(frame)  # 将每一帧转为Imageimg = Image.open(image_path)output_buffer = BytesIO()  # 创建一个BytesIOimg.save(output_buffer, format='JPEG')  # 写入output_bufferbyte_data = output_buffer.getvalue()  # 在内存中读取base64_data = base64.b64encode(byte_data)  # 转为BASE64return base64_data  # 转码成功 返回base64编码def user_register(image,groupId, userId):""" 你的 APPID AK SK """APP_ID = ''API_KEY = ''SECRET_KEY = ''client = AipFace(APP_ID, API_KEY, SECRET_KEY)# 将图片转换为 base64 类型image = frame2base64(image)image = str(image, 'UTF-8')# 图片类型imageType = "BASE64"# 分组groupId = groupId# 用户iduserId = userId""" 调用人脸注册 """json1 = client.addUser(image, imageType, groupId, userId)while json1['error_msg'] == 'Open api qps request limit reached':json1 = client.addUser(image, imageType, groupId, userId)print("jason1:", json1)# """ 如果有可选参数 """# options = {}# options["user_info"] = "user's info"# options["quality_control"] = "NORMAL"# options["liveness_control"] = "LOW"# options["action_type"] = "REPLACE"## """ 带参数调用人脸注册 """# client.addUser(image, imageType, groupId, userId, options)def user_update(image, groupId,userId):""" 你的 APPID AK SK """APP_ID = ''API_KEY = ''SECRET_KEY = ''client = AipFace(APP_ID, API_KEY, SECRET_KEY)# 将图片转换为 base64 类型image = frame2base64(image)image = str(image, 'UTF-8')imageType = "BASE64"# 分组IdgroupId = groupId# 用户IduserId = userId""" 调用人脸更新 """jason2 = client.updateUser(image, imageType, groupId, userId)print("jason2:", jason2)# """ 如果有可选参数 """# options = {}# options["user_info"] = "user's info"# options["quality_control"] = "NORMAL"# options["liveness_control"] = "LOW"# options["action_type"] = "REPLACE"## """ 带参数调用人脸更新 """# client.updateUser(image, imageType, groupId, userId, options)if __name__ == "__main__":image = "L1.JPG"groupId = "group"userId = "2020"user_register(image, groupId, userId)

百度也提供了 详细的 Python-SDK 供大家学习使用。

创作不易,求点赞,求收藏!,如有问题欢迎留言。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/156283.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何快速绘制网络拓扑图

关于网络拓扑 网络拓扑能直观明了的展示网络中各网元之间的关系,极大方便运维人员对网络进行实时监测、优化配置、故障排查等操作。 传统采用Visiot或PowerPoint的方式存在耗时耗力且无法实现动态更新,维护及使用成本高;可展现的内容有限&a…

小红书穿搭类种草营销怎么做?纯干货

在众多营销方式中,穿搭类种草营销以其独特的优势在小红书平台上崭露头角。穿搭类种草营销,以其独特的优势,成为了品牌和商家推广产品的重要方式。其优势主要体现在以下几个方面: 1. 高度相关性:小红书平台的用户主要是…

【Cargo Therapeutics】申请1亿美元纳斯达克IPO上市

来源:猛兽财经 作者:猛兽财经 猛兽财经获悉,美国生物制药公司【Cargo Therapeutics】近期已向美国证券交易委员会(SEC)提交招股书,申请在纳斯达克IPO上市,股票代码为(CRGX),Cargo Therapeutics…

Unity2D中瓦片地图的创建与绘制教程

Unity2D中瓦片地图的创建与绘制 素材切割创建地图创建瓦片绘制地图瓦片调色板画笔拓展素材资源链接 素材切割 选中以下素材,以Tiles为例(素材链接在文章最下方) 修改素材属性。 将Sprite Mode属性改为Multiple多张(不然切割不了&…

针对实体商家技术开发一体化营销工具都包含那些功能呢?

1.批量剪辑技术研发 做的数学建模算法,数学阶乘的组合乘组形式,采用两套查重机制,一套针对素材进行查重抽帧素材,一套针对成片进行抽帧素材打分制度查重,自动滤重计入打分。 2.账号矩阵分发开发 多平台,…

echarts 画散点图, x周,y周在指定位置标志一下

文章目录 echarts 画散点图, x周,y周在指定位置标志一下示例一例子二示例三 echarts 画散点图, x周,y周在指定位置标志一下 示例一 let scatterData {data: [[[-0.2, -0.6],[0.4, 0.3],[0.1, 0.4],[0.3, 0.5],[0.09, 0.1],[0.7,…

vue2:路由前置守卫无法获取到this.$store.state.xxx

在获取到vuex的数据时候,想在router目录下的index.js文件去获取到vuex仓库中声明的全局变量,但是通过this.$store.stote.xxx去获取的时候,报错提示:$store未定义 一、store/index.js const store new Vuex.Store({state: {// 属…

AI图像识别初次尝试

1.人形识别结果 2.代码 pythonOpenCVyolov3训练库,代码如下: #!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np import osimgFiles["pic03.jpg", "pic04.jpg"]netNone classesNone colorsNonedef r…

Windows电脑怎么下载桌面便签小工具?

Windows电脑是日常办公中常用的工具,电脑上可以安装许多软件来辅助日常办公,其中桌面便签工具可以为大家记录很多日常办公中的各项工作计划,而且便签软件通常可以悬挂于电脑桌面显示,方便大家一边工作一边查看备忘记录。 谈及Win…

Python的web自动化学习(六)Selenium第一个网页操作

引言: 前面我们系统的介绍了一个各种selenium的工作原理、环境配置与准备、各种元素定位的方法,现在让我们一起来实践吧,以哔哩哔哩登录为例子说明: Selenium自动登录B站(通过QQ登录) 为什么使用qq登录&…

Mozilla Firefox 119 现已可供下载

导读Mozilla Firefox 119 开源网络浏览器现在可以下载了,是时候先看看它的新功能和改进了。 Firefox 119 改进了 Firefox View 功能,现在可以提供更多内容,如最近关闭的标签页和浏览历史,你可以按日期或网站排序,还支…

huggingface离线模式及默认保存路径

T5Tokenizer.from_pretrained()函数会在线下载huggingface上的模型,并自动保存在C盘的.cache路径下: C:\Users\xxxxx\.cache\huggingface\hub\models--google--t5-v1_1-base # 这里xxxxx代表自己电脑用户名huggingface离线下载 以google/t5-v1_1-base为…