Beispiel #1
0
    def item_completed(self, results, item, info):
        print(item)
        print('thisis pix')
        conn = mysql.connector.connect(host='127.0.0.1',
                                       user='******',
                                       password='******',
                                       database='bigdata')
        db = conn
        image_paths = [x['path'] for ok, x in results if ok]  # ok判断是否下载成功
        if not image_paths:
            raise DropItem("Item contains no images")
        # item['image_paths'] = image_paths
        else:
            print('dowok')
            for ok, x in results:
                path = x['path']
            rootpath = os.path.abspath('..')
            filePath = rootpath + "\\images\\" + path
            print(filePath)
            aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY)
            imageType = "BASE64"
            options = {}
            options["face_field"] = "age,gender,beauty"
            with open(filePath, 'rb') as fp:
                content = base64.b64encode(fp.read())
                base64ss = content.decode('utf-8')
            result = aipFace.detect(base64ss, imageType, options)
            beauty = 0
            if result['error_code'] == 0:
                face = result['result']['face_list']
                beauty = face[len(face) - 1]['beauty']
            elif result['error_code'] == 18:
                aipFace1 = AipFace(APP_ID1, API_KEY1, SECRET_KEY1)
                result1 = aipFace1.detect(base64ss, imageType, options)
                if result1['error_code'] == 0:
                    face = result1['result']['face_list']
                    beauty = face[len(face) - 1]['beauty']
            img_url = item['image_urls']
            type = 1
            cursor = db.cursor()
            sql = "INSERT INTO pic (img_url,`type`,beauty) VALUES (%s,%s,%s)"
            val = (img_url, type, beauty)
            cursor.execute(sql, val)
            db.commit()
            cursor.close()
            print("1 条记录已插入, ID:", cursor.lastrowid)

        return item
Beispiel #2
0
def check_img(flag, path):  # 面部识别
    cli = AipFace(AppId, API_Key, Secret_Key)
    image, image_type = '', ''
    if flag == '1':
        image = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538151319150&di=196eda34652fd03b3335ec68aca74122&imgtype=0&src=http%3A%2F%2F01.minipic.eastday.com%2F20170306%2F20170306130710_4f981e8e34f472af11274a7cc68fa3bb_4.jpeg'
        image_type = 'URL'
    elif flag == '2':
        image = trans_base64(path)
        image_type = 'BASE64'
    options = {}
    options['face_field'] = 'age,beauty'
    options['max_face_num'] = 1     # 最多处理人脸的数目
    options['face_type'] = 'LIVE'   #人脸的类型 LIVE表示生活照:通常为手机、相机拍摄的人像图片、或从网络获取的人像图片等IDCARD表示身份证芯片照:二代身份证内置芯片中的人像照片 WATERMARK表示带水印证件照:一般为带水印的小图,如公安网小图 CERT表示证件照片:如拍摄的身份证、工卡、护照、学生证等证件图片 默认LIVE
    res = cli.detect(image, image_type, options)
    print(res)
    if res['error_code'] == 0:
        print('读取成功')
        face_num = res['result']['face_num']
        face_age = res['result']['face_list'][0]['age']
        face_beaty = res['result']['face_list'][0]['beauty']
        print('人脸数量', face_num)
        print('人脸年龄', face_age)
        print('颜值', face_beaty)
        return face_num, face_age, face_beaty
    else:
        print('读取失败')
Beispiel #3
0
    def ai_math_face(self):
        """ 你的 APPID AK SK """
        APP_ID = '14313252'
        API_KEY = 'g7bnDTUUK9SMzIsKIHMyqPTw'
        SECRET_KEY = 'sAxOW2M48QOmPUxQeEza3yYbdFyCGH0Y'

        client = AipFace(APP_ID, API_KEY, SECRET_KEY)

        """ 调用人脸比对 """
        result_json=client.match([
            {
                'image': str(base64.b64encode(open(self.label_img1_path, 'rb').read()),'utf-8'),
                'image_type': 'BASE64',
            },
            {
                'image': str(base64.b64encode(open(self.label_img2_path, 'rb').read()),'utf-8'),
                'image_type': 'BASE64',
            }
        ]);

        result = result_json['result']
        if result_json['error_code'] == 0:
            self.result_math.setText("相似度:" + str(result['score']) + '%') # 在结果框中显示数据
        else:
            self.result_math.setText("错误信息:" + str(result_json['error_msg'])) # 在结果框中显示数据
Beispiel #4
0
def face_score(link):
    # 图片名称
    pic_name = re.findall(r"public/(.+?)$", link)
    # 图片存储位置
    # 还能巧妙的避免重复!!!
    filePath = '/Users/zhaowenbo/Downloads/crawl_ouban/pictures/' + pic_name[0]
    # 根据图片的URL获取并保存图片
    urllib.request.urlretrieve(link, filePath)

    # 百度api的一些key
    APP_ID = '18072729'
    API_KEY = 'ZRQcBl5i4f6hlTML09h47vA9'
    SECRET_KEY = 'dimWQ2OhId6Z4AEnpUMdpvuZ4k1se3AR'

    # 使用百度人脸识别API
    aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY)

    def get_file_content(filePath):
        with open(filePath, 'rb') as fp:
            content = base64.b64encode(fp.read())
            return content.decode('utf-8')

    imageType = "BASE64"

    options = {}
    options["face_field"] = "age,gender,beauty"

    result = aipFace.detect(get_file_content(filePath), imageType, options)
    # result['result']['face_list'][0]['beauty']   float
    return result['result']['face_list'][0]['beauty']
Beispiel #5
0
def detect():
    global res
    global names
    APP_ID = '11304911'
    API_KEY = 'pbW5Gp5iw2EFY6KVs9bOjmWe'
    SECRET_KEY = 'Z3oXfUVfwAMmb5NZhq94mWs16pUMnO4c'
    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
    with open('test1.jpg', 'rb') as f:
        pic1 = f.read()
    res = client.search((b64encode(pic1)).decode(), 'BASE64', '1')
    # print(res['result']['user_list'][0])
    names = {
        'lhy': '刘恒宇',
        'wpf': '亲爱的温鹏飞学长',
        'wm': '亲爱的武萌学姐',
        'yk': '亲爱的杨柯学姐',
        'wdc': '亲爱的王栋才学长',
        'wmn': '亲爱的王美男学姐',
        'mxd': '亲爱的马旭东同学',
        'ljz':'亲爱的爸爸'
    }

    APP_ID = '11174193'
    API_KEY = '2OG012BvAtWdvzfWQGwscFzO'
    SECRET_KEY = 'lTD6LRVGDfewVsLadvhkH7cBixHkjnLL'
    client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
    result  = client.synthesis(recognize(), 'zh', 1, {
        'vol': 5,
        'per': 4,
        'spd': 4
    })
    if not isinstance(result, dict):
        with open('auido.mp3', 'wb') as f:
            f.write(result)
Beispiel #6
0
def face_information(img_path):
     """ 你的 APPID AK SK """
     APP_ID = '17151694'
     API_KEY = 'PVc6kFsF0Pk8ZPpGewaIhoK8'
     SECRET_KEY = '43XAsfZnkcezXDAjA4czgDirnpa4TudW'

     client = AipFace(APP_ID, API_KEY, SECRET_KEY)

     # 打开本地文件
     f = open(r'%s' % img_path, 'rb')

     # # 打开url地址
     # f = urllib.request.urlopen(img_path)


     pic = base64.b64encode(f.read())
     image = str(pic, 'utf-8')

     imageType = "BASE64"

     """ 如果有可选参数 """
     options = {}
     options["face_field"] = "age,beauty,gender,face_shape,quality"
     options["max_face_num"] = 1
     options["face_type"] = "LIVE"

     """ 带参数调用人脸检测 """
     a = client.detect(image, imageType, options)


     # for item in a['result']['face_list']:
     #      print("年龄:", item['age'], "容貌评分:", item['beauty'], "性别:", item['gender'],"脸型:",item['face_shape'])
     return a
Beispiel #7
0
    def FaceInfo(self):
        """ 你的 APPID AK SK """

        client = AipFace(APP_ID, API_KEY, SECRET_KEY)

        with open("Face.jpeg", "rb") as f:
            # b64encode是编码,b64decode是解码
            image = base64.b64encode(f.read())
            # base64.b64decode(base64data)
            image = str(image, encoding="utf-8")

        imageType = "BASE64"

        groupIdList = "user1"

        options = {}
        """ 调用人脸搜索 """
        list1 = client.search(image, imageType, groupIdList, options)
        scorelist = []
        if 'error_code' in list1:
            if list1['error_code'] == 0:
                for i in range(0, len(list1['result']['user_list'])):
                    scorelist.append(list1['result']['user_list'][i]['score'])
                maxscore = max(scorelist)
                if maxscore >= 90:
                    print(list1['result']['user_list'][scorelist.index(
                        maxscore)]['user_id'])  # 查询数据库验证用户合法性
                    self.FACEIMG.setText("欢迎回家")  # 发送开门指令
                    self.FACETIP.setText("")
                    self.onesecond.start(1500)
    def __init__(self):
        APP_ID = '18721308'
        API_KEY = 'lNQGdBNazTPv8LpSP4x0GQlI'
        SECRET_KEY = 'nW8grONY777n4I2KvpOVuKGDNiY03omI'
        self.client_face = AipFace(APP_ID, API_KEY, SECRET_KEY)
        self.client_body = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)
        self.image_type = "BASE64"
        filepath = "/Pictures/image.jpg"

        msg = reception_image()
        self.guest = Guest()
        # self.name = None
        # self.age = None
        # self.image = None
        # self.gender = None
        # self.drink = None

        self.options_body = {}
        self.options_body["type"] = "gender,upper_color,upper_wear_fg"
        self.options_face = {}
        self.options_face["face_field"] = "age,gender"
        self.options_face["max_face_num"] = 3
        self.options_face["face_type"] = "LIVE"
      

        #发布器
        self.roi_pub = rospy.Publisher('/image/roi',RegionOfInterest,queue_size=1)
        self.objpos_pub = rospy.Publisher('/image/object_position2d',String,queue_size=1)
        self.control_pub = rospy.Pubscriber("/control", reception, queue_size=1)
        self.speech_pub = rospy.Pubscriber('/speech/check_door',reception_image,self.find_people)
        #订阅器
        self.control_sub = rospy.Subscriber("/control", reception, self.controlCallback)
       
        self.ROI = RegionOfInterest()
Beispiel #9
0
def init_face_detective(app_id, api_key, secret_key):
    client = AipFace(app_id, api_key, secret_key)
    #人脸检测中,在响应中附带额外的字段。年龄 / 性别 / 颜值 / 质量
    options = {"face_fields": "age,gender,beauty,qualities"}

    def detective(image):
        r = client.detect(image, options)
        #如果没有检测到人脸
        if r["result_num"] == 0:
            return []
        scores = []
        for face in r["result"]:
            #人脸置信度太低
            if face["face_probability"] < 0.6:
                continue
            #真实人脸置信度太低
            if face["qualities"]["type"]["human"] < 0.6:
                continue
            #颜值低于阈值
            if face["beauty"] < BEAUTY_THRESHOLD:
                continue
            #性别非女性
            if face["gender"] != "female":
                continue
            scores.append(face["beauty"])
        return scores

    return detective
Beispiel #10
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    tmp_path = hass.config.path('www/baidu_face/')
    import os
    if not os.path.exists(tmp_path):
        os.makedirs(tmp_path)
    response = requests.get(DEFAULT_WAITING_PIC)
    path = tmp_path + 'waiting.gif'
    with open(path, 'wb') as fp:
        fp.write(response.content)
        fp.close()
    """ add sensor components """
    app_id = config.get(CONF_APP_ID)
    api_key = config.get(CONF_API_KEY)
    secret_key = config.get(CONF_SECRET_KEY)
    camera_entity_id = config.get(CONF_ENTITY_ID)
    group_list = config.get(CONF_GROUP_LIST)
    liveness = config.get(CONF_LIVENESS)
    name = config.get(CONF_NAME)
    port = config.get(CONF_PORT)
    token = config.get(CONF_ACCESS_TOKEN)
    score = config.get(CONF_SCORE)

    baidu_client = AipFace(app_id, api_key, secret_key)
    options = {}
    options["max_face_num"] = 10
    options["match_threshold"] = score
    options["quality_control"] = 'NONE'
    options["liveness_control"] = liveness
    options["max_user_num"] = 10
    add_devices([
        FaceSensor(name, camera_entity_id, port, token, baidu_client,
                   group_list, options, tmp_path)
    ])
Beispiel #11
0
 def __init__(self):
     """ 你的 APPID AK SK """
     APP_ID = '10207465'
     API_KEY = '6kGyHckLOnH9Y3TuLGbopLG9'
     SECRET_KEY = 'OReYFNrB9BB5eh0kwgj2OEssxe0aTROl'
     self.client = AipFace(APP_ID, API_KEY, SECRET_KEY)
     self.url = "https://api-cn.faceplusplus.com/facepp/v3/detect"
Beispiel #12
0
class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'xxxxxxxxxxx'
    CSRF_ENABLED = True
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_RECORD_QUERIES = True
    YB_IP = 'xx.xxx.xxx'
    # 导出文件目录
    SIGN_LOGS_CONTENS = basedir + '/file'
    # 百度AI第三方配置
    APP_ID = 'xxxxxx'
    API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxx'
    SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    CLIENT = AipFace(APP_ID, API_KEY, SECRET_KEY)
    GROUP_ID = 'xx'
    """ 如果有可选参数 """
    FYOPTIONS = {}
    FYOPTIONS["ext_fields"] = "faceliveness"
    FYOPTIONS["top_num"] = 3
    ADDOPTIONS = {}
    ADDOPTIONS["action_type"] = "replace"
    DETOPTIONS = {}
    DETOPTIONS["max_face_num"] = 1

    @staticmethod
    def init_app(app):
        pass
def init_face_detective(app_id, api_key, secret_key):
    client = AipFace(app_id, api_key, secret_key)
    # 人脸检测中,在响应中附带额外的字段。年龄 / 性别 / 颜值 / 质量
    options = {
        'max_face_num': 1,
        'face_field': 'age,beauty,expression,face_shape,gender,glasses,landmark,race,quality,face_type'
    }

    def detective(image):
        response = client.detect(image, "BASE64", options)
        # 如果没有检测到人脸
        result = response["result"]
        if response["error_code"] != 0 or result["face_num"] == 0:
            return []

        valid_faces = []
        for face in result["face_list"]:
            # 人脸置信度太低
            if face["face_probability"] < 0.6:
                continue
            # 人脸质量信息
            if face["quality"]["completeness"] != 1:
                continue
            # 颜值低于阈值
            if face["beauty"] < BEAUTY_THRESHOLD:
                continue
            valid_faces.append(face)

        return valid_faces

    return detective
Beispiel #14
0
def upload_face():
    male_group_id = 'celebrity_male_test'
    female_group_id = 'celebrity_female_test'

    app_id = Config().get("AipConfig", "APP_ID")
    api_key = Config().get("AipConfig", "API_KEY")
    secret_key = Config().get("AipConfig", "SECRET_KEY")
    client = AipFace(app_id, api_key, secret_key)

    cnx = mysql.connector.connect(user='******', password='******',
                                  host='127.0.0.1',
                                  database='chbb_facecompare')
    cursor = cnx.cursor()
    query_images = 'select c.name, c.gender, ci.imagePath, ci.uid from celebrity c join celebrityImage ci on ci.celebrity_id = c.id;'
    cursor.execute(query_images)

    for (name, gender, imagePath, uid) in cursor:
        group_id = ''
        # print(name, gender, imagePath, uid)
        if gender == '男':
            group_id = male_group_id
        elif gender == '女':
            group_id = female_group_id
        else:
            print(gender)

        image_path = directoryPath + imagePath
        options = {
            "action_type": "replace"
        }
        client.updateUser(uid, name, group_id, get_file_content(image_path), options)
        print(name, gender, 'uploaded.')

    cursor.close()
    cnx.close()
Beispiel #15
0
def detection(path):
    """ 你的 APPID AK SK """
    APP_ID = '16918274'
    API_KEY = '8LPSpFQpG1WTSTP77arZKTFG'
    SECRET_KEY = 'Me1HVHyWjm6sPSluFBGeNHGTYZQNbcyf'

    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
    with open(path, 'rb') as f:
        # print(f.read())
        data = base64.b64encode(f.read())
    # exit()
    image = data.decode()
    imageType = "BASE64"
    """ 调用人脸检测 """
    # client.detect(image, imageType);
    """ 如果有可选参数 """
    options = {}
    options["face_field"] = "beauty"
    # options["max_face_num"] = 2
    # options["face_type"] = "LIVE"
    # options["liveness_control"] = "LOW"
    """ 带参数调用人脸检测 """
    response = client.detect(image, imageType, options)
    # print(response)
    if response['error_code'] != 0:
        print('失败', response['error_code'])
    else:
        return response['result']['face_list'][0]['beauty']
Beispiel #16
0
def init_face_detective(app_id, api_key, secret_key):
    client = AipFace(app_id, api_key, secret_key)
    # 百度云 V3 版本接口,需要先获取 access token
    token = fetch_auth_token(API_KEY, SECRET_KEY)

    def detective(image):
        #r = client.detect(image, options)
        # 直接使用 HTTP 请求
        r = detect_face(image, token)
        #如果没有检测到人脸
        if r is None or r["face_num"] == 0:
            return []

        scores = []
        for face in r["face_list"]:
            #人脸置信度太低
            if face["face_probability"] < 0.6:
                continue
            #颜值低于阈值
            if face["beauty"] < BEAUTY_THRESHOLD:
                continue
            #性别非女性
            if face["gender"]["type"] != "female":
                continue
            scores.append(face["beauty"])

        return scores

    return detective
Beispiel #17
0
    def showResult(self):
        # 填入百度API信息
        APP_ID = ''
        API_KEY = ''
        SECRET_KEY = ''

        aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY)

        # 使用base64重新编码图片
        def get_file_content(filePath):
            with open(filePath, 'rb') as fp:
                content = base64.b64encode(fp.read())
                return content.decode('utf-8')
            pass

        imageType = "BASE64"

        options = {}
        options["face_field"] = "age,gender,beauty"

        result = aipFace.detect(get_file_content(path_), imageType, options)

        sex = result['result']['face_list'][0]['gender']['type']
        age = result['result']['face_list'][0]['age']
        beauty = result['result']['face_list'][0]['beauty']

        # 使用标签显示结果
        Label(root, text="sex: " + sex).place(x=260, y=30)
        Label(root, text="age: " + str(age)).place(x=260, y=60)
        Label(root, text="beauty: " + str(beauty)).place(x=260, y=90)
        pass
Beispiel #18
0
def Mactch(img1, img2):
    """ APPID AK SK """
    APP_ID = '*******'
    API_KEY = '************'
    SECRET_KEY = '**********************'
    client = AipFace(APP_ID, API_KEY, SECRET_KEY)

    name = img2[9:-4]  # obtain image filename
    dic[name] = 0

    f1 = open(img1, 'rb')
    f2 = open(img2, 'rb')

    img1 = base64.b64encode(f1.read())
    img2 = base64.b64encode(f2.read())
    image_1 = str(img1, 'utf-8')
    image_2 = str(img2, 'utf-8')

    #update the date to the baidu AI platform
    ptr = client.match([{
        'image': image_1,
        'image_type': 'BASE64',
    }, {
        'image': image_2,
        'image_type': 'BASE64',
    }])
    ptr = ptr['result']
    # print(ptr)
    dic[name] = ptr['score']
    sort = list(sorted(dic.items(), key=lambda x: x[1]))
    print(sort)
    return sort
Beispiel #19
0
def face_detection(image, imageType, *options):
    #################### Define by Baidu Document ####################
    # pip3 install baidu_aip - After installing Baidu-AI python package,
    # import Baidu face detection Python SDK client
    from aip import AipFace

    # create Aipface client
    """ 你的 APPID AK SK """
    APP_ID = '14325294'
    API_KEY = 'AsvKVw4Kb1Hk5aYiZifxihHh'
    SECRET_KEY = 'opAuwOddyUIfHgpkE4tdn3qf94PsaYAT'

    client = AipFace(APP_ID, API_KEY, SECRET_KEY)

    ########## detect face in picture and mark position ##########
    #image = "取决于image_type参数,传入BASE64字符串//或URL字符串//或FACE_TOKEN字符串"
    # Example:
    #### image = "http://pic5.newssc.org/upload/ori/20160413/1460515143090.jpg"
    #### imageType = "URL"
    image = image
    imageType = imageType
    """ 调用人脸检测 """
    #result = client.detect(image, imageType)
    """ 如果有可选参数 """
    options = {}
    options["face_field"] = "age"
    options["max_face_num"] = 10
    options["face_type"] = "LIVE"
    """ 带参数调用人脸检测 """
    result = client.detect(image, imageType, options)
    # return json format
    return result
Beispiel #20
0
def detection(APP_ID, API_KEY, SECRET_KEY, filename, maxnum):  
    ''''' 
 
    :param APP_ID: https://console.bce.baidu.com/ai/创建人脸检测应用对应的APP_ID 
    :param API_KEY: https://console.bce.baidu.com/ai/创建人脸检测应用对应的API_KEY 
    :param SECRET_ID: https://console.bce.baidu.com/ai/创建人脸检测应用对应的SECRET_ID 
    :param filename: 图片路径 
    :param maxnum: 最大检测数 
    :return: 
    '''  
    # 初始化AirFace对象  
    aipface = AipFace(APP_ID, API_KEY, SECRET_KEY)  
  
    # 设置  
    options = {  
        'max_face_num': 10,  # 检测人脸的最大数量  
        'face_fields': "age,beauty,expression,faceshape",  
    }  
  
    # 读取文件内容  
    def get_file_content(filePath):  
        with open(filePath, 'rb') as fp:  
            return fp.read()  
  
    result = aipface.detect(get_file_content(filename), options)  
    return result  
Beispiel #21
0
 def get_face_client(cls):
     if FaceClient.static_client:
         return FaceClient.static_client
     print("first initialize client")
     FaceClient.static_client = AipFace(FaceClient.APP_ID,
                                        FaceClient.API_KEY,
                                        FaceClient.SECRET_KEY)
     return FaceClient.static_client
Beispiel #22
0
def createapiface():

    APP_ID = '11211624'
    API_KEY = 'wo7nEAvyNrK30kWG38rTC1qg'
    SECRET_KEY = 'VcHeSeIARmfXI0TahrgtMyszMsljIKnB'

    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
    return client
Beispiel #23
0
def check_face_img(image_path):
    image_str = get_image_base64(image_path)
    client = AipFace(config.APP_ID, config.APP_KEY, config.SECRET_KEY)
    imageType = "BASE64"
    # print(client.detect(image_str, imageType)['error_code'] != 0)
    if client.detect(image_str, imageType)['error_code'] != 0:
        # print('没有人脸的图片===>' + image_path)
        delete_no_face(image_path)
Beispiel #24
0
def uploadUserInfo(user_avatar_url, userInfo):
    image = user_avatar_url
    imageType = 'URL'
    groupId = 'sp'
    user_id = userInfo['eNum']

    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
    result = client.addUser(image, imageType, groupId, user_id)
    print(result)
Beispiel #25
0
def baidu_init():
    '''
    百度ai初始化
    '''
    APP_ID = '14645910'
    API_KEY = 'ytLF4jOVsTSGP7BdcWGsfDb6'
    SECRET_KEY = 'K9TMBAWbWwHASZ0mQnw1UBTKXWVTMM1R'
    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
    return client
Beispiel #26
0
 def FaceInfo(self):
     client = AipFace(APP_ID, API_KEY, SECRET_KEY)
     with open("Face.jpeg", "rb") as f:
         image = base64.b64encode(f.read())
         image = str(image, encoding="utf-8")
     imageType = "BASE64"
     groupIdList = "user1"
     options = {}
     options["quality_control"] = QUALITY_CONTROL
     options["liveness_control"] = LIVENESS_CONTROL
     """ 调用人脸搜索 """
     list1 = client.search(image, imageType, groupIdList, options)
     scorelist = []
     if 'error_code' in list1:
         if list1['error_code'] == 0:
             for i in range(0, len(list1['result']['user_list'])):
                 scorelist.append(list1['result']['user_list'][i]['score'])
             maxscore = max(scorelist)
             if maxscore >= FACE_SCORE:
                 checkFACENAME = list1['result']['user_list'][scorelist.index(maxscore)]['user_id']
                 db = MySQLdb.connect(DBIP, DBID, DBPWD, DBNAME, charset='utf8')
                 cursor = db.cursor()
                 global SHEBEIID
                 cursor.callproc('CHECKFACE', args=(SHEBEIID, checkFACENAME))
                 # 提交到数据库执行
                 results = cursor.fetchall()
                 cursor.execute("select @_CHECKFACE_0")
                 res2 = cursor.fetchall()
                 # 关闭数据库连接
                 db.commit()
                 db.close()
                 USERFLAG = results[0][0]
                 if USERFLAG == 1:
                     self.FACEIMG.setText("欢迎回家")  # 发送开门指令
                     self.FACETIP.setText("")
                     self.onesecond.start(3500)
                 elif USERFLAG == 2:
                     self.FACEIMG.setText("红码禁入!")  # 发送拒绝指令
                     self.FACETIP.setText("")
                     self.onesecond.start(3500)
                 else:
                     self.FACEIMG.setText("人脸认证失败")
                     self.FACETIP.setText("")
                     self.onesecond.start(3500)  # 延迟3.5秒回到主页
             else:
                 self.FACEIMG.setText("人脸认证失败")
                 self.FACETIP.setText("")
                 self.onesecond.start(3500)  # 延迟3.5秒回到主页
         else:
             self.FACEIMG.setText("人脸认证失败")
             self.FACETIP.setText("")
             self.onesecond.start(3500)  # 延迟3.5秒回到主页
     else:
         self.FACEIMG.setText("人脸认证失败")
         self.FACETIP.setText("")
         self.onesecond.start(3500)  # 延迟3.5秒回到主页
Beispiel #27
0
class FaceDetector(object):
    client = AipFace(APP_ID, API_KEY, SECRET_KEY)

    @staticmethod
    def is_human_in_image(image_url):
        image_type = 'URL'
        options = dict()
        options['max_face_num'] = 2
        options["face_field"] = "quality,gender,face_type"
        dic = FaceDetector.client.detect(image_url, image_type, options)
        result = dic.get('result', None)
        if result is None:
            return False
        else:
            face_num = result['face_num']  # 脸的数量

            face_list = result['face_list']
            for face_info in face_list:
                gender_dic = face_info.get('gender', None)
                is_male = False
                if gender_dic is not None:
                    gender = gender_dic.get('type', None)  # 性别
                    gender_probability = gender_dic.get('probability',
                                                        None)  # 性别可信度
                    is_male = gender == 'male' and gender_probability > 0.8
                if not is_male:
                    continue

                face_type_dic = face_info.get('face_type', None)  # 脸的类型
                is_real_man = False
                if face_type_dic is not None:
                    face_type = face_type_dic[
                        'type']  # human: 真实人脸 cartoon: 卡通人脸
                    human_probability = face_type_dic['probability']
                    is_real_man = face_type == 'human' and human_probability > 0.7

                if not is_real_man:
                    continue

                qualities = face_info.get('quality', None)  # 人脸质量信息
                is_quality_pass = False
                if qualities is not None:
                    occlusion = qualities['occlusion']  # 遮挡范围
                    left_check = occlusion['left_cheek']  # 左脸颊被遮挡的阈值
                    right_check = occlusion['right_cheek']  # 右脸颊被遮挡的阈值
                    blur = qualities['blur']  # 模糊度范围
                    illumination = qualities['illumination']  # 光照范围
                    completeness = qualities['completeness']  # 人脸完整度
                    occlusion_quality = left_check * right_check  # 左右脸遮挡面积比例
                    is_quality_pass = completeness > 0.4 and illumination > 20 and blur < 0.5 and occlusion_quality < 0.36

                is_good_image = (face_num > 0 and is_quality_pass
                                 and is_real_man and is_male)
                if is_good_image:
                    return True
        return False
Beispiel #28
0
 def __init__(self):
     "your baidu ai APP_ID"
     self.APP_ID = '********'
     "your baidu ai API_KEY"
     self.API_KEY = '***************'
     "your baidu ai SECRET_KEY"
     self.SECRET_KEY = '*******************'
     self.aipFace = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY)
     self.photo_name = ''
     self.group = 'Door'
Beispiel #29
0
def detection(APP_ID, API_KEY, SECRET_KEY, filename, maxnum):
    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
    image = base64.b64encode(get_file_content(filename))
    image = str(image, 'utf-8')
    imageType = "BASE64"
    # 设置
    options = {}
    options['max_face_num'] = 10
    options["face_field"] = "age,beauty,expression,faceshape"
    result = client.detect(image, imageType, options)
    return result
Beispiel #30
0
def searchUserInfo(imageFilePath):
    img1 = base64.b64encode(
        open(imageFilePath, 'rb').read())
    pic1 = str(img1, 'utf-8')

    imageType = 'BASE64'
    groupIdList = 'sp'

    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
    result = client.search(pic1, imageType, groupIdList)
    return result['result']['user_list'][0]['user_id']