Exemple #1
0
def bidui(image_path):
	import sys
	reload(sys)
	sys.setdefaultencoding( "utf-8" )
	#将需要识别的图片和集合对比

	#------------------------------------------------------------------------------
	#准备阶段
	API_KEY = "a4OWmRJTir1XGFx6vZtwPvlf6nsYxErQ"
	API_SECRET = "Q1bR1pHjv7SGWa3xSN0tNivJ4lK0K8Tu"
	#国际版的服务器地址
	api_server_international = 'https://api-us.faceplusplus.com/facepp/v3/'
	# 导入系统库并定义辅助函数
	from pprint import pformat
	def print_result(hit, result):
		def encode(obj):
			if type(obj) is unicode:
				return obj.encode('utf-8')
			if type(obj) is dict:
				return {encode(v): encode(k) for (v, k) in obj.iteritems()}
			if type(obj) is list:
				return [encode(i) for i in obj]
			return obj
		print hit
		result = encode(result)
		print '\n'.join("  " + i for i in pformat(result, width=75).split('\n'))
	#导入SDK中的API类
	from facepp import API, File
	#创建一个API对象
	api = API(API_KEY, API_SECRET)

	#-----------------------------------------------------------------------------
	# 本地图片的地址
	face_search = image_path
	# 对待比对的图片进行检测
	Face = {}
	res = api.detect(image_file=File(face_search))
	#print_result("face_search", res)
	#搜索相似脸
	search_result = api.search(face_token=res["faces"][0]["face_token"], outer_id='finally')
	# 输出结果
	search_confidence = search_result['results'][0]['confidence']
	uers=search_result['results'][0]['user_id']
	print '置信度:', search_confidence
	if search_confidence >=80:
		print '你好!',uers.decode('utf-8')
		return 1
	else:
		return 0
Exemple #2
0
print_result("person_one", res)
Face['person_one'] = res["faces"][0]["face_token"]

res = api.detect(image_file=File(face_two))
print_result("person_two", res)
Face['person_two'] = res["faces"][0]["face_token"]

# 将得到的FaceToken存进Faceset里面
# save FaceToken in Faceset
api.faceset.addface(outer_id='test', face_tokens=Face.itervalues())

# 对待比对的图片进行检测,再搜索相似脸
# detect image and search same face
ret = api.detect(image_file=File(face_search))
print_result("detect", ret)
search_result = api.search(face_token=ret["faces"][0]["face_token"], outer_id='test')

# 输出结果
# print result
print_result('search', search_result)
print '=' * 60
for k, v in Face.iteritems():
    if v == search_result['results'][0]['face_token']:
        print 'The person with highest confidence:', k
        break


# 删除无用的人脸库
# delect faceset because it is no longer needed
api.faceset.delete(outer_id='test', check_empty=0)
Exemple #3
0
print_result("person_one", res)
Face['person_one'] = res["faces"][0]["face_token"]

res = api.detect(image_file=File(face_two))
print_result("person_two", res)
Face['person_two'] = res["faces"][0]["face_token"]

# 将得到的FaceToken存进Faceset里面
# save FaceToken in Faceset
api.faceset.addface(outer_id='test', face_tokens=Face.itervalues())

# 对待比对的图片进行检测,再搜索相似脸
# detect image and search same face
ret = api.detect(image_file=File(face_search))
print_result("detect", ret)
search_result = api.search(face_token=ret["faces"][0]["face_token"],
                           outer_id='test')

# 输出结果
# print result
print_result('search', search_result)
print '=' * 60
for k, v in Face.iteritems():
    if v == search_result['results'][0]['face_token']:
        print 'The person with highest confidence:', k
        break

# 删除无用的人脸库
# delect faceset because it is no longer needed
api.faceset.delete(outer_id='test', check_empty=0)

# 恭喜!您已经完成了本教程,可以继续阅读我们的API文档并利用Face++ API开始写您自
Exemple #4
0
class FaceDectect:
    def __init__(self,
                 id='test',
                 API_KEY='w1s9SPlbJkhetEnq-BD8puseCT2LDTyj',
                 API_SECRET='a8uEA_hK6lzuRHAY-LiqhlNcoDmS3I7A'):
        self.api = API(API_KEY, API_SECRET)
        self.Face = {}
        self.id = id
        self.search_result = {}

    def changeFaceset(self, id):
        try:
            ret = self.api.faceset.create(outer_id=id)
        except Exception as e:
            print "id already exists"
        self.id = id

    def delete_Faceset(self, id):
        self.api.faceset.delete(outer_id=id, check_empty=0)

    def addFaceToSet(self, image_file, info):
        res = self.api.detect(image_file=File(image_file))
        self.Face['%s' % info] = res["faces"][0]["face_token"]
        print "add to Face sucess"

    def addFaceToInternet(self):
        print[i for i in self.Face.itervalues()]
        self.api.faceset.addface(outer_id=self.id,
                                 face_tokens=self.Face.itervalues())
        print "add to internet face sucess"

    def getFaceInfo(self, input_file):
        ret = self.api.detect(image_file=File(input_file))
        self.search_result = self.api.search(
            face_token=ret["faces"][0]["face_token"], outer_id=self.id)
        for k, v in self.Face.iteritems():
            if v == self.search_result['results'][0]['face_token']:
                print 'The person with highest confidence:', k
                return k
                break

    def save_Face(self, face_file="default_face.txt"):
        face_file = open(face_file, 'wb')
        pickle.dump(self.Face, face_file)
        face_file.close()

    def load_Face(self, face_file="default_face.txt"):
        face_file = open(face_file, 'rb')
        self.Face = pickle.load(face_file)
        face_file.close()

    def print_result(hit, result):
        def encode(obj):
            if type(obj) is unicode:
                return obj.encode('utf-8')
            if type(obj) is dict:
                return {encode(v): encode(k) for (v, k) in obj.iteritems()}
            if type(obj) is list:
                return [encode(i) for i in obj]
            return obj

        print hit
        result = encode(result)
        print '\n'.join("  " + i
                        for i in pformat(result, width=75).split('\n'))
Exemple #5
0
print_result("person_two", res)
Face['person_two'] = res["faces"][0]["face_token"]
"""

# save FaceToken in Faceset
api.faceset.addface(outer_id=FACESET_ID, face_tokens=[target_token])

for i in range(1, 500):
    face_search = '/Users/zhiminhe/wbq/out' + str(i) + '.png'
    print face_search,
    found = False
    # detect image and search same face
    ret = api.detect(image_file=File(face_search))
    # print_result("detect", ret)
    for face in ret["faces"]:
        search_result = api.search(face_token=face["face_token"],
                                   outer_id=FACESET_ID)

        # print result
        # print_result('search', search_result)
        # print '=' * 60
        for result in search_result['results']:
            if target_token == result[
                    'face_token'] and result['confidence'] > threshold:
                found = True
                break
        if found:
            break
    if found:
        print 'found'
    else:
        print 'not found'
Exemple #6
0
# with open(face_two, 'rb') as f:
#     content = f.read()
# ret = api.detect(image_file=File(content=content))
# print_result("detect", ret)
again = True
while (again):
    again = False
    try:
        ret = api.detect(image_file=File(face_search))
        print_result("detect", ret)

        # time.sleep(5)
        # search_result = api.search(face_token=ret["faces"][0]["face_token"], faceset_token='468d4f8ba70bddbf41aa9b3d2deeb04a')
        search_result = api.search(
            image_url=face_one,
            faceset_token='468d4f8ba70bddbf41aa9b3d2deeb04a')
    except APIError as e:
        print "error happen:", str(e.body)
        again = True
        time.sleep(2)
# 输出结果
print_result('search', search_result)
print '=' * 60
for k, v in Face.iteritems():
    if v == search_result['results'][0]['face_token']:
        print 'The person with highest confidence:', k
        break

# 删除无用的人脸库
# delect faceset because it is no longer needed
Exemple #7
0
'''
res = api.detect(image_file=File(face_four))
print_result("person_four", res)
Face['person_four'] = res["faces"][0]["face_token"]

# 将得到的FaceToken存进Faceset里面
# save FaceToken in Faceset
api.faceset.update(outer_id='mingxing', face_tokens=Face.itervalues())

print(" Faceset is already prepared!! ")

# 对待比对的图片进行检测,再搜索相似脸
# detect image and search same face
ret = api.detect(image_file=File(face_search))
print_result("detect", ret)
search_result = api.search(face_token=ret["faces"][0]["face_token"],
                           outer_id='mingxing')

# 输出结果
# print result
print_result('search', search_result)
print '=' * 60
for k, v in Face.iteritems():
    if v == search_result['results'][0]['face_token']:
        print 'The person with highest confidence:', k
        break

# 删除无用的人脸库
# delect faceset because it is no longer needed
###api.faceset.delete(outer_id='mingxing', check_empty=0)
Exemple #8
0

#导入SDK中的API类
from facepp import API, File
#创建一个API对象
api = API(API_KEY, API_SECRET)

#-----------------------------------------------------------------------------
# 本地图片的地址
face_search = './foo.jpg'
# 对待比对的图片进行检测
Face = {}
res = api.detect(image_file=File(face_search))
#print_result("face_search", res)
#搜索相似脸
search_result = api.search(face_token=res["faces"][0]["face_token"],
                           outer_id='gtl')
# 输出结果
search_confidence = search_result['results'][0]['confidence']
uers = search_result['results'][0]['user_id']
print '置信度:', search_confidence
if search_confidence >= 80:
    #print '你好!',uers.decode('utf-8')

    text = '你好! %s!%s'% \
           (uers.decode('utf-8'),get_weather())
    print(text)
    #text2voice(text)
    #mp3path1 = os.path.join(os.path.dirname(__file__), '1.mp3')
    #os.system('mplayer %s' % mp3path1)
    #os.remove(mp3path1)
Exemple #9
0
class FaceTask(object):

    def __init__(self, dbpath=SHELVE_DB):
        self.api = API(API_KEY, API_SECRET)
        if RASPBERRYPI:
            GPIO.setmode(GPIO.BCM)
            GPIO.setup(BCM_PIN4_SHOW_TAKE_PHOTO, GPIO.OUT)
            GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, True)
        try:
            self.api.faceset.create(outer_id = 'default')
        except APIError as e:
            """如果 'default' 已创建, 忽略改错误。"""
            pass
        self.camera_lock = threading.Lock()

    def delete_faceset(self, outer_id):
        try:
            return self.api.faceset.delete(outer_id=outer_id, check_empty=0)
        except APIError as e:
            return str(e)

    def add_faceset(self, outer_id):
        try:
            return self.api.faceset.create(outer_id=outer_id)
        except APIError as e:
            return str(e)

    def get_facesets(self):
        """获取所有的faceset"""
        try:
            facesets = self.api.faceset.getfacesets()['facesets']
        except KeyError:
            return None

        return [faceset['outer_id'] for faceset in facesets]

    def get_faceset(self, outer_id='default'):
        """获取指定faceset中的face."""
        faces = []
        try:
            detail = self.api.faceset.getdetail(outer_id = outer_id)
            faces_tokens = detail['face_tokens']
        except ValueError:
            return None
        except APIError:
            return None

        def get_faces_name(face_token):
            face_detail = self.api.face.getdetail(face_token = face_token)
            return face_detail.get('user_id', None)

        tmp_executor = ThreadPoolExecutor()
        return list(tmp_executor.map(get_faces_name, faces_tokens))

    def upload_faces(self, outer_id='default', **kwargs):
        """上传face到指定的faceset
            keyword args  image_file or  image_url
        """
        name = kwargs.pop('name', None)
        if name == None:
            name = raw_input('Please enter the picture name:')
        try:
            face_token = self.api.detect(**kwargs)["faces"][0]["face_token"]
        except (KeyError, IndexError): 
            return None
        self.api.faceset.addface(outer_id=outer_id, face_tokens=face_token)
        self.api.face.setuserid(face_token=face_token, user_id=name)
        
        img = db.models.Image(name=name, path=kwargs.pop('image_path'), token=face_token)
        img.save()
        
        return face_token, name

    def search_faces(self,  face_token, outer_id='default'):
        """ 根据face_token在指定的faceset中进行匹配搜索
        """
        try:
            results = self.api.search(face_token=face_token, outer_id=outer_id)['results']
        except (KeyError):
            return None

        return [face['user_id'] for face in results if face['confidence'] > CONFIDENCE]

    def search_people_from_camera(self, outer_id='default'):
        if not RASPBERRYPI:
            return None
        image_name = '%s.jpg' % time.time()
        GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, 1)
        cmd = 'sudo raspistill -t 2000 -o %s -p 100,100,300,200 -q 5' % image_name
        GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, 0)
        with self.camera_lock:
            os.system(cmd)
        ret = self.api.detect(image_file=File(image_name))
        
        try:
            face_token=ret["faces"][0]["face_token"]
        except (IndexError, KeyError):
            if isinstance(ret, dict) and ('error_message' in ret.keys()):
                return ret['error_message']
            return 'The picture is invalid.'

        return self.search_faces(face_token, outer_id=outer_id)

    def update_faces_from_camera(self, outer_id='default'):
        if not RASPBERRYPI:
            return None
        image_name = '%s.jpg'%time.time()
        cmd = 'sudo raspistill -t 2000 -o %s -p 100,100,300,200 -q 5' % image_name
        GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, True)
        with self.camera_lock:
            os.system(cmd)
        GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, False)
        return self.upload_faces(outer_id, image_file=File(image_name), image_path=image_name)

    def clear(self):
        if RASPBERRYPI:
            GPIO.cleanup()