#coding:utf-8 #! C:\Developer\python36\python3.exe import aip from aip import AipNlp from aip import AipFace """ 你的 APPID AK SK """ APP_ID = '10253494' API_KEY = 'NAh5KkgrKTPyxzUBewCAakvm' SECRET_KEY = 'nTrHzPhh0CQP9H9Idz3jftsji9NgVdvF' aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY) # 读取图片 def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() options = { 'max_face_num': 1, 'face_fields': "age,beauty", } # 调用人脸属性检测接口 result = aipFace.detect(get_file_content('1.jpg'), options) print('年龄:' + str(int(result['result'][0]['location']['age']))) print('颜值:' + str(result['result'][0]['location']['beauty'])) print(result)
import cv2 from aip import AipFace import utils client = AipFace(utils.BAIDU_AI_APP_ID, utils.BAIDU_AI_API_KEY, utils.BAIDU_AI_SECRET_KEY) image_type = "BASE64" group_id = "ahojcn" user_id = "fancheng" options = {"user_info": "范程"} image = cv2.imread("./img/fancheng.jpg") image_base64 = utils.image_to_base64(image) # print(client.addUser(image_base64, image_type, group_id, user_id, options)) import requests, json # host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={utils.BAIDU_AI_API_KEY}&client_secret={utils.BAIDU_AI_SECRET_KEY}' # response = requests.get(host) # if response: # print(response.json()) access_token = '24.e4265a7b77a8cadbdb194334fa9b5cbf.2592000.1611411456.282335-18145377' request_url = 'https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add' data = { "image": image_base64, "image_type": "BASE64", "group_id": "ahojcn", "user_id": "fancheng",
from aip import AipFace from requests.api import options import base64 APP_ID = '16850595' API_KEY = '6uhScb0HHcPHLGXFMYUOglEp' SECRET_KEY = 'TiTuvl5mUupxxvsBTq9HH6R6tCZZcMf8' client = AipFace(APP_ID, API_KEY, SECRET_KEY) def get_file_content(image): with open(image, 'rb') as fp: content = base64.b64encode(fp.read()) return content.decode('utf-8') for i in range(1, 50): image = (str(i) + ".jpg") imageType = "BASE64" options = {} options['face_field'] = 'age,gender,beauty' # options = {} # options["face_field"] = "age" # options["max_face_num"] = 2 # options["face_type"] = "LIVE" # options["liveness_control"] = "LOW" """ 调用人脸检测 """
# 人脸识别评分,python3.6.6(代码比较乱,不喜欢迎来喷,谢谢) # 需要安装pip install baidu-aip from aip import AipFace import base64 # 百度开发者官网获取key、id注册后就可以获取。 APP_ID = '' API_KEY = '' SECRET_KEY = ' ' # 初始化AipFace对象 aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY) imageType = "BASE64" options = {} options["face_field"] = "age,gender,beauty" def get_file_content(filePath): with open(filePath, 'rb') as fp: content = base64.b64encode(fp.read()) return content.decode('utf-8')
def run(self): # Initialize some variables face_locations = [] face_encodings = [] face_names = [] time.sleep(3) global frame_of_stream, mutex global g_face_locations, g_face_names, mutex1 APP_ID = '11155090' API_KEY = "rG3P2789bywKHfGN0OnEwAgg" SECRET_KEY = "yTjcZQ92dwGBl3zDY1yWzEz9fb4FeYMc" client = AipFace(APP_ID, API_KEY, SECRET_KEY) options = { "ext_fields": "faceliveness", "detect_top_num": 10, # 检测多少个人脸进行比对,默认值1(最对返回10个) "user_top_num": 1 # 返回识别结果top人数”当同一个人有多张图片时,只返回比对最高的1个分数 } Group_Id = "test" while True: if mutex.acquire(): loc_frame = frame_of_stream mutex.release() # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(loc_frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] # Find all the faces and face encodings in the current frame of video face_locations = face_recognition.face_locations( rgb_small_frame) face_encodings = face_recognition.face_encodings( rgb_small_frame, face_locations) face_names = [] face_baidu_loc = [] if len(face_locations) == 0: if mutex1.acquire(): g_face_locations = [] g_face_names = [] mutex1.release() continue else: # Use the KNN model to find the best matches for the test face closest_distances = self.knn_clf.kneighbors(face_encodings, n_neighbors=1) matches = [ closest_distances[0][i][0] <= self.distance_threshold for i in range(len(face_locations)) ] print(g_face_locations) # Use Baidu API to find the best matches for the test face cv2.imwrite('face.jpg', loc_frame) with open("face.jpg", 'rb') as fp: image = fp.read() Res = client.multiIdentify(Group_Id, image, options) try: Res['result'] except KeyError: continue else: for i in range(len(Res['result'])): res = Res['result'][i]['uid'] print('res:', res) pos = Res['result'][i]['position']['left'] print('pos:', pos) face_names.append(res) face_baidu_loc = self.judge_pos( face_locations=face_locations, baidu_Res=Res, _range=range(len(Res['result']))) if mutex1.acquire(): g_face_locations = face_baidu_loc g_face_names = face_names mutex1.release()
from flask import Flask, render_template, request from aip import AipFace import random, time, sys, datetime # 百度API配置 APP_ID = '24096837' API_KEY = '4EkfjzDIVIdC47wrdkgcQwK8' SECRET_KEY = 'e3mgFT9uROQ24UYOCUygGQmx1YRhfydK' # 初始化client client = AipFace(APP_ID, API_KEY, SECRET_KEY) app = Flask(__name__) # 单注模式 def create_lucky(seed): LUCKY_SEED = int(seed) redball = list(range(1, 36)) blueball = list(range(1, 13)) redball_left = 35 blueball_left = 12 lucky_ball = 0 redball_pool = [] blueball_pool = [] random.shuffle(redball) random.shuffle(blueball) for i in range(5): time.sleep(random.randint(1, LUCKY_SEED) / LUCKY_SEED) for j in range(random.randint(1, LUCKY_SEED) % redball_left): random.shuffle(redball)
from aip import AipFace import base64 APP_ID = '15926606' API_KEY = 'IDpHxZLsVhUtv6XErETilME5' SECRET_KEY = 'kPf8gtTfmkzLDArHmkRs48R4bacAURbY' client = AipFace(APP_ID, API_KEY, SECRET_KEY) for i in range(1,10): #range表示每次循环i从1到10,这里代表上传10个用户 filePath ="user"+ "%04d" % i +".jpg" with open(filePath,"rb") as f: base64_data = base64.b64encode(f.read()) image = str(base64_data,'utf-8') imageType = "BASE64" groupId = "student" userId = "user"+ "%04d" % i print(userId) client.addUser(image, imageType, groupId, userId); pass
if __name__ == '__main__': """ 完成利用多个百度云帐号实现图片批量分析 """ # 扫描本地人脸相册 util.print_a('正在扫描本地人脸相册') file_list = os.listdir(config.ALBUM) util.print_t('相册中包含{}张照片'.format(len(file_list))) # 批量创建AIP连接对象 util.print_a('正在批量创建AIP连接对象') aip_list = [] for aip_key in config.AIPFace: aip_list.append(AipFace(**aip_key)) if len(aip_list) == 0: util.print_w('没有AIP帐号怎么识别鸭') exit() util.print_a('正在进行识别前的初始化') # 建立线程池,当连接对象过多时需要改写为线程池!! all_work = [] # 线程管理数组 executor = ThreadPoolExecutor(max_workers=len(aip_list)) # 建立MongoDB数据库连接 mongo_conn = dao.mongo_conn() mongo_set = mongo_conn[config.MONGO_SET] exclude_list = [] # 检索需要排除的任务编号 for face in mongo_set.find({}, {'_id': False, 'face_plus': False}): if 'aip_face' in face and len(face['aip_face'].keys()) != 0:
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 百度图像识别基础服务 """ from aip import AipFace, AipOcr, AipImageClassify # 文字识别 char_APP_ID = "10683930" char_API_KEY = "KWupRWsdl3zgmy01HBSgVqup" char_SECRET_KEY = "hNVMDcsLnPenwyx4XGOa7v3ne8cdOvUy" ocr = AipOcr(char_APP_ID, char_API_KEY, char_SECRET_KEY) # 图像识别 image_APP_ID = "15066160" image_API_KEY = "eIftSwlyrBcECm0T4hDlB3R5" image_SECRET_KEY = "1Xq85wRk7YRl8M1nnm6xKqP7rzPf6PN4" image = AipImageClassify(image_APP_ID, image_API_KEY, image_SECRET_KEY) # 人脸识别 face_APP_ID = "15066160" face_API_KEY = "4h5hph54DK2kYWwN2mfVe6cZ" face_SECRET_KEY = "x9LbeBxKrPGqg7b4vzek56sB7tyK6aw1" face = AipFace(face_APP_ID, face_API_KEY, face_SECRET_KEY)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from aip import AipFace Ak = 'TBPtvVXmPoAnSX4ljiTkrpji' Sk = '2wRiOMvA1yEvY09GRm4v6fSvW9H0Kzcj' Ai = '9647392' aipFace = AipFace(Ai, Ak, Sk) aipFace.setConnectionTimeoutInMillis(2000) aipFace.setSocketTimeoutInMillis(60000) options = { 'max_face_num': 5, 'face_fields': "age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities" } # 读取图片 def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() path = 'F:\\KwDownload\\3.jpg' response = aipFace.detect(get_file_content(path), options) print(response)
@author: Administrator """ import base64 import cv2 from aip import AipFace """ 你的 APPID AK SK """ APP_ID = '11406086' API_KEY = 'ayMYdnBIf6Q5BwsDw2aTs6va' SECRET_KEY = 'EkVpE7ao8ssPBAMGjI6ZgPxtmhdxZCeR' imageType = "BASE64" """ 如果有可选参数 """ options = {} options["max_face_num"] = 10 client = AipFace(APP_ID, API_KEY, SECRET_KEY) cap = cv2.cv2.VideoCapture(0) #fourcc=cv2.cv2.VideoWriter_fourcc(*'XVID') #out=cv2.cv2.VideoWriter('output.avi',fourcc,20.0,(640,480)) while True: ret, frame = cap.read() if ret: cv2.cv2.imwrite('D:/12/l66l.JPEG', frame) with open("D:/12/l66l.JPEG", "rb") as f: # b64encode是编码,b64decode是解码 base64_data = base64.b64encode(f.read())
# -*- coding: utf-8 -*- from aip import AipFace """ 你的 APPID AK SK """ APP_ID = '14844983' API_KEY = 'XV5SI5ejk8UGWP8igRkvE3Wa' SECRET_KEY = '2L4VoMk3sUfj8Fs0p2mliT1gsGe1htAI' client = AipFace(APP_ID, API_KEY, SECRET_KEY) """ 读取图片 """ def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() image = get_file_content( 'C:\Users\Administrator\Desktop\WebCrawler\day17\\6.jpg') """ 如果有可选参数 """ options = {} options["max_face_num"] = 2 options["face_fields"] = "age,beauty" """ 带参数调用人脸检测 """ final = client.detect(image, options) print(final)
def run(self): # Initialize some variables save_pic_count = 0 db = pymysql.connect("139.199.124.196", "hawuser", "1504030521Lqt?", "hawDB", charset='utf8') cursor = db.cursor() face_locations = [] face_encodings = [] face_names = [] time.sleep(1) global frame_of_stream, mutex global g_face_locations, g_face_names, mutex1 global g_stu_uid, mutex2 APP_ID = '11155090' API_KEY = "rG3P2789bywKHfGN0OnEwAgg" SECRET_KEY = "yTjcZQ92dwGBl3zDY1yWzEz9fb4FeYMc" client = AipFace(APP_ID, API_KEY, SECRET_KEY) options = { "ext_fields": "faceliveness", "detect_top_num": 10, # 检测多少个人脸进行比对,默认值1(最对返回10个) "user_top_num": 1 # 返回识别结果top人数”当同一个人有多张图片时,只返回比对最高的1个分数 } Group_Id = "test" while True: if mutex.acquire(): loc_frame = frame_of_stream mutex.release() # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(loc_frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] # Find all the faces and face encodings in the current frame of video face_locations = face_recognition.face_locations( rgb_small_frame) face_encodings = face_recognition.face_encodings( rgb_small_frame, face_locations) face_names = [] if len(face_locations) == 0: if mutex1.acquire(): g_face_locations = [] g_face_names = [] mutex1.release() continue else: # Use the KNN model to find the best matches for the test face closest_distances = self.knn_clf.kneighbors(face_encodings, n_neighbors=1) matches = [ closest_distances[0][i][0] <= self.distance_threshold for i in range(len(face_locations)) ] print(g_face_locations) # Use Baidu API to find the best matches for the test face cv2.imwrite('face.jpg', loc_frame) with open("face.jpg", 'rb') as fp: image = fp.read() Res = client.multiIdentify(Group_Id, image, options) # pandeku de daima if 'error_msg' in Res: print(Res['error_msg']) else: for i in range(Res['result_num']): uid = Res['result'][i]['uid'] info = str( Res['result'][i]['user_info'] ) + "," + str(Res['result'][i]['uid']) + "," + str( Res['result'][i]['group_id']) + "," + str( Res['result'][i]['scores']) with open("right_result_time_ues.txt", 'a') as f: f.write(info + "\n") # pandeku de daima try: Res['result'] except KeyError: continue else: for i in range(len(Res['result'])): if Res['result'][i]['scores'][0] > 70: res = Res['result'][i]['uid'] face_names.append(res) else: face_names.append('0') save_path = '/Users/liuqingtong/Desktop/PycharmProjects/Haw/Haw/DB/Dataset/%s_%d.jpg' % ( res, save_pic_count) save_pic_count += 1 print('save_path', save_path) cv2.imwrite(save_path, small_frame) print('res:', res) if mutex1.acquire(): g_face_locations = face_locations g_face_names = face_names mutex1.release() for uid in face_names: times = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') sql = "UPDATE stu_info SET Is_Attend='%s' WHERE User_Id = '%s'" % ( "已签到!", uid) # sql1 = "UPDATE login_register_attend_user SET Attend_Time=CURRENT_TIMESTAMP WHERE User_Id = '%s'" % (uid) sql1 = "UPDATE stu_info SET Attend_Time='%s' WHERE User_Id = '%s'" % ( times, uid) try: cursor.execute(sql) # 执行更新 cursor.execute(sql1) # 执行更新 db.commit() # 提交 except: db.rollback() # 发生错误,回滚 print("Error: unable to update data") print('DB Operation Done!') print( '_______________________________________________' )
from aip import AipFace import cv2 import base64 """ 你的 APPID AK SK """ APP_ID = '10454819' API_KEY = 'q2bA1wTuhPtoGRoYp0ROXUwQ' SECRET_KEY = '0T37uW8DXMCftWSPboo5ZjGd3QgYYpqo' image = 'D:/pproject/ppop/image/xcc.jpg' imageType = "BASE64" groupIdList = "kaifa" """ 调用人脸搜索 """ client = AipFace(APP_ID, API_KEY, SECRET_KEY) with open(image, mode='rb') as f: image_base64 = bytes.decode(base64.b64encode(f.read())) print(client.search(image_base64, imageType, groupIdList)) # face_token人脸标志 # user_list 匹配的用户信息列表 # +group_id用户所属的group_id # +user_id 用户的user_id # +user_info 注册用户时携带的user_info # score 用户的匹配得分 """ 如果有可选参数 """ options = {} options[ "quality_control"] = "NORMAL" #图片质量控制 NONE: 不进行控制 LOW:较低的质量要求 NORMAL: 一般的质量要求 HIGH: 较高的质量要求 默认 NONE options[ "liveness_control"] = "LOW" #活体检测控制 NONE: 不进行控制 LOW:较低的活体要求(高通过率 低攻击拒绝率) NORMAL: 一般的活体要求(平衡的攻击拒绝率, 通过率) HIGH: 较高的活体要求(高攻击拒绝率 低通过率) 默认NONE options["user_id"] = "002" #当需要对特定用户进行比对时,指定user_id进行比对。即人脸认证功能。 options["max_user_num"] = 3 #查找后返回的用户数量。返回相似度最高的几个用户,默认为1,最多返回20个。