Example #1
0
def test_t(a, b):
    from qcloud_image import Client
    from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers
    appid = cf.get("qq", "appid")
    secret_id = cf.get("qq", "secret_id")
    secret_key = cf.get("qq", "secret_key")
    bucket = 'BUCKET'
    client = Client(appid, secret_id, secret_key, bucket)
    client.use_http()
    client.set_timeout(30)

    print("compare {} and {}".format(a, b))

    print(client.face_compare(CIFile(a), CIFile(b)))
Example #2
0
 def find_pic(self, path):
     result = self.client.face_identify(self.__group, CIFile(path))
     if result['code'] == 0:
         result = result['data']['candidates']
     else:
         result = []
     return result
Example #3
0
 def face_diff(self):
     """Face-人脸对比"""
     client = self.get_client()
     if len(self.image_url) >= 0:
         # URL图片信息
         print(
             client.face_compare(CIFile(self.image_url[0]),
                                 CIFile(self.image_url[1])))
     if len(self.image_file) >= 0:
         # 文件图片信息
         print(
             client.face_compare(CIUrl(self.image_url[0]),
                                 CIUrl(self.image_url[1])))
     if len(self.image_url) >= 0 and len(self.image_file) >= 0:
         # URL图片信息和文件图片信息
         print(
             client.face_compare(CIUrl(self.image_url[0]),
                                 CIFile(self.image_file[0])))
Example #4
0
    def get_tags(self, path=None):
        appid = "1257930116"
        secret_id = "AKIDMXTCQT2n9rgJiape1HNiSdFgZHsSDR8d"
        secret_key = "RhFg4TwPkR5Zs362udyFSVVmySvRk1GQ"
        bucket = 'BUCKET'
        client = Client(appid, secret_id, secret_key, bucket)
        client.use_http()
        client.set_timeout(100)

        res = client.tag_detect(CIFile(path))
        # print(res)
        try:
            tags = res['tags']
        except KeyError:
            try:
                res = client.tag_detect(CIFile(path))
                tags = res['tags']
            except KeyError:
                print('Error {}: {}'.format(res['code'], res['message']))
                return None
        return tags
Example #5
0
 def add_new_pic(self, path):
     print(self.__person + str(self.__id))
     print(
         self.client.face_newperson(self.__person + str(self.__id), [
             self.__group,
         ], CIFile(path)))
     person_id = self.__person + str(self.__id)
     if person_id in self.picInfo:
         self.picInfo[person_id] = self.picInfo[person_id] + "," + path
     else:
         self.picInfo[person_id] = path
     self.__id = self.__id + 1
Example #6
0
 def id_card_diff_ocr(self):
     """OCR-身份证识别对比"""
     client = self.get_client()
     if len(self.image_url) >= 0:
         # 身份证URL图片信息
         print(
             client.face_idcardcompare('ID CARD NUM', 'NAME',
                                       CIUrl(self.image_url[0])))
     if len(self.image_file) >= 0:
         # 身份证文件图片信息
         print(
             client.face_idcardcompare('ID CARD NUM', 'NAME',
                                       CIFile(self.image_file[0])))
def main_handler(event, context):
    logger.info("start main handler")
    if "requestContext" not in event.keys():
        return {"code": 410, "errorMsg": "event is not come from api gateway"}
    if event["body"] == "":
        return {"code": 412, "errorMsg": "there is no file from api gateway"}

    # save api gateway file to local temp file
    logger.info("Start to download images from APIGW")
    time = datetime.datetime.now()
    file_name = '{}'.format(time) + "-test.jpg"
    logger.info("file_name is : %s" % file_name)
    local_path = u'/tmp/{}'.format(file_name)
    logger.info("local_path is : %s" % local_path)
    with open(local_path, 'w') as wfile:
        wfile.write(base64.b64decode(event['body']))

    # start to upload to cos
    logger.info("Start to upload images to cos")
    res_cos = client_cos.put_object_from_local_file(Bucket=bucket_upload,
                                                    LocalFilePath=local_path,
                                                    Key='{}'.format(file_name))
    logger.info("upload to cos result is : %s" % res_cos)

    # start to detection
    logger.info("Start to detection")
    client_ai = Client(appid, secret_id, secret_key, bucket_upload)
    client_ai.use_http()
    client_ai.set_timeout(30)
    res_ai = client_ai.word_detect(CIFile(local_path))
    res_text = "  "
    print len(res_ai["data"]["items"])
    for i in range(len(res_ai["data"]["items"])):
        res_text = res_text + str(
            res_ai["data"]["items"][i]["itemstring"].encode('utf-8'))

    delete_local_file(local_path)
    response = {
        "isBase64Encoded": False,
        "statusCode": 200,
        "headers": {
            "Content-Type": "text",
            "Access-Control-Allow-Origin": "*"
        },
        "body": res_text
    }

    return response
Example #8
0
def faceplus(filepath):
    # result = {
    #    'underLipTop':0,
    #    'mouthRight':0,
    #    'upperLipTop':0,
    #    'upperLipBottom':0,
    #    'mouthLeft':0,
    #    'underLipBottom':0
    # }
    # face_file = filepath
    # image = open(face_file, "rb")
    # image_body = image.read()

    client = Client(appid, secret_id, secret_key, bucket)
    client.use_http()
    client.set_timeout(30)
    result = []
    raw = client.face_shape(CIFile(filepath + '.jpg'), 1)
    rawData = raw["data"]
    if "face_shape" in rawData:
        if len(rawData["face_shape"]) != 0:
            result = rawData["face_shape"][0]['mouth']
    else:
        print(raw)

    # conn = http.client.HTTPSConnection('api.cognitive.azure.cn')
    # conn.request("POST", "/face/v1.0/detect?%s" % params, image_body, headers)
    # response = conn.getresponse()
    # rawData = response.read().decode()
    # if not json.loads(rawData)[0]:
    #    return False
    # print(json.loads(rawData))
    # rawData = json.loads(rawData)[0]['faceLandmarks']
    # conn.close()
    # for i in rawData:
    #    if 'Lip' in i or 'mouth' in i:
    #        result[i]=rawData[i]
    #        print(i)
    return result
Example #9
0
def qcloud_general(ttf):
    #控制台-访问管理-云API秘钥管理-新建或获取现有
    appid = 'your appid'
    secret_id = 'your secret_id'
    secret_key = 'your secret_key'
    #对象存储
    bucket = 'your bucket'

    client = Client(appid, secret_id, secret_key, bucket)
    client.use_http()
    client.set_timeout(30)
    # 通用印刷体识别
    ocr = client.general_detect(CIFile('./merge.png'))

    ocr_list = []
    if ocr['code'] == 0:
        if len(ocr['data']['items']) > 0:
            for i, item in enumerate(ocr['data']['items']):
                for word in item['words']:
                    if word['character'] != '':
                        ocr_list.append(word['character'])
                    if word['character'] == '':
                        print('第%d行,字符串"%s"中有空字符' % (i, item['itemstring']))

        ocr_ttf = {}
        for n in numbers:
            if n in ttf:
                ttf.remove(n)
        for i, t in enumerate(ttf):
            if i < len(ocr_list):
                print('%s --> %s' % (t, ocr_list[i]))
                ocr_ttf[t] = ocr_list[i]
            else:
                print('%s 没有被匹配' % t)
        print(ocr_ttf)

    else:
        print('ocr识别结果有误,错误码: %d' % ocr['code'])
Example #10
0
# -*- coding: utf-8 -*-
import os

from qcloud_image import Client
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers

appid = '#########'
secret_id = '##############'
secret_key = '#####################'
bucket = 'faceslib'

client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

result = client.face_identify('group1', CIFile('./10xxl2.jpeg'))
value_no=80
value_yes=96
person=client.face_getinfo(result['data']['candidates'][0]['person_id'])
person_name = person['data']['person_name']
confidence=result['data']['candidates'][0]['confidence']
print(confidence)
if confidence<value_no:
    print("不存在该顾客")
if value_no<=confidence<value_yes:
    print("该顾客可能是:")

    print(person_name)
if confidence>=value_yes:
    print('该顾客是:')
    print(person_name)
from qcloud_image import Client
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers

appid = '##############'
secret_id = '###################'
secret_key = '####################'
bucket = '#################'

client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

print(client.face_newperson('1', [
    'group2',
], CIFile('1刘德华.jpeg')))
print(client.face_setinfo('1', '刘德华'))
Example #12
0
def Face(filename):
    appid = '1256531249'
    secret_id = 'AKIDGK9iwx8IbgYCcoNW1IK8h27wVosg8ZfV'
    secret_key = 'iAMIxNxLTKuFJ7fx3uVqwlKdjbEcmhOq'
    bucket = 'ocrbucket-1256531249'
    client = Client(appid, secret_id, secret_key, bucket)
    client.use_http()
    client.set_timeout(30)
    print '人脸识别'

    if client.face_detect(CIFile(filename),
                          1).get('message') == 'OK':  #如果监测到人脸进行如下操作
        print 'indect face'
        # 数据库连接
        #conn = pymssql.connect('localhost', 'root', '123456', 'album')
        db = MySQLdb.connect("localhost",
                             "root",
                             "123456",
                             "album",
                             charset='utf8')
        cursor = db.cursor()

        # 数据库查询操作
        cursor.execute('SELECT name FROM names')
        row = cursor.fetchone()
        flag = 0

        id = 1
        # 对于每一个查询到的人名
        while row:
            id = id + 1
            # print("ID=%d, Name=%s" % (row[0], row[1]))
            if client.face_verify(row[0], CIFile(filename)).get('data').get(
                    'confidence') > 90:  # 若跟这个人置信度大于90
                print '\t\tget ' + row[0]
                client.face_addface(row[0], CIFiles([
                    filename,
                ]))  # 就加脸
                sql = "update picture set namelabel='" + row[
                    0] + "' where pictureid='" + filename.replace(
                        '/home/ubuntu/album/public/', "") + "'"
                try:
                    cursor.execute(sql)
                    db.commit()
                    print 'update namelabel success'
                except:
                    db.rollback()
                    print "update namelabel error"
                flag = 1
                break
            else:
                # 取下个人名继续判断
                row = cursor.fetchone()

        # 若判断完仍未找到对的人
        if flag == 0:
            client.face_newperson('people' + str(id), [
                'group1',
            ], CIFile(filename))  # 就添加新人
            try:
                # 并将其插入到数据库中
                cursor.execute("INSERT INTO names VALUES( '" + 'people' +
                               str(id) + "')")
                # 如果没有指定autocommit属性为True的话就需要调用commit()方法
                db.commit()
                print 'insert names success'
            except:
                db.rollback()
                print 'insert names error'

            try:
                cursor.execute(
                    "UPDATE picture SET namelabel ='" + 'people' + str(id) +
                    "' where pictureid='" +
                    filename.replace('/home/ubuntu/album/public/', "") + "'")
                db.commit()
                print 'update picture.namelabel success'
            except:
                db.rollback()
                print 'update picture.namelabel success'
        db.close()
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# 腾讯云获得
appid = '1256126369'
secret_id = 'AKIDENK7iBfpOn160lzxRk1FJEykOrPwn3Tu'
secret_key = 'c9VfecUExb7YwFXjpttnmkhZL1b6QccU'
bucket = 'test0'

client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

# //单个图片file,mode:1为检测最大的人脸 , 0为检测所有人脸
face = client.face_shape(CIFile('./test0.jpg'), 1)

# //单个图片Url,mode:1为检测最大的人脸 , 0为检测所有人脸
# face = client.face_shape(
#     CIUrl('https://xdimg.meiyezhushou.com/xiaomei/material_library/sample_face/2db161612335d559.jpg'), 1)

# 打印脸部数据
print(face["data"])

# 打印图片的高
print('image_height:', face["data"]["image_height"])
# 打印图片的宽
print('image_width:', face["data"]["image_width"])

# 打印轮廓数据(21个点)
print('face_profile', face["data"]["face_shape"][0]['face_profile'])
Example #14
0
import os
from GetphotoPath import xz
from qcloud_image import Client
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers

appid = '1255316848'
secret_id = 'AKIDkIacaJz26vZy83qAPO7anoZ4JI3ZDrdA'
secret_key = 'QbV9XfX8TYNvDF2auzpPjqiLjsmRr2yf'
bucket = 'faceslib'

client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

input_photopath='../photos/init.jpeg'
result = client.face_identify('group1', CIFile(input_photopath))
value_no=80
value_yes=96
person=client.face_getinfo(result['data']['candidates'][0]['person_id'])
person_id=person['data']['person_id']
person_name = person['data']['person_name']
original_photo_name=person_id+person_name+'.jpeg'
this_path = os.getcwd()
original_photopath = this_path+'/'+original_photo_name
print (input_photopath,original_photopath,person_name)

confidence=result['data']['candidates'][0]['confidence']

# print(confidence)
# if confidence<value_no:
#     print("不存在该顾客")
Example #15
0
        CIUrls([
            'http://jiangsu.china.com.cn/uploadfile/2015/1102/1446443026382534.jpg',
            'http://n.sinaimg.cn/fashion/transform/20160704/flgG-fxtspsa6612705.jpg'
        ])))
#单个或多个图片File
print(client.porn_detect(CIFiles([
    './test.jpg',
])))

# 图片标签
#单个图片url
print(
    client.tag_detect(
        CIUrl('http://img3.a0bi.com/upload/ttq/20160814/1471155260063.png')))
#单个图片file
print(client.tag_detect(CIFile('./hot2.jpg')))

#OCR-身份证识别
#单个或多个图片Url,识别身份证正面
print(
    client.idcard_detect(
        CIUrls(['http://imgs.focus.cn/upload/sz/5876/a_58758051.jpg']), 0))
#单个或多个图片file,识别身份证正面
print(client.idcard_detect(CIFiles(['./id4_zheng.jpg', './id1_zheng.jpg']), 0))
#单个或多个图片Url,识别身份证反面
print(
    client.idcard_detect(
        CIUrls([
            'http://www.csx.gov.cn/cwfw/bszn/201403/W020121030349825312574.jpg',
            'http://www.4009951551.com/upload/image/20151026/1445831136187479.png'
        ]), 1))
# -*- coding: utf-8 -*-
import os

from qcloud_image import Client
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers

appid = '1255955027'
secret_id = 'AKIDwnT9iA3caNyNbfqLJAqKdrxsdIm55URH'
secret_key = 'oUyY0LWQJCC81mLm3b3KPSN6e4IQNAmC'
bucket = 'nvrenlian'

c = Client(appid, secret_id, secret_key, bucket)
c.use_http()
c.set_timeout(30)

inf = c.face_detect(CIFile('../photos/init.jpg'))
gender = inf['data']['face'][0]['gender']
print(inf['data']['face'][0]['gender'])
print(type(gender))
if gender > 50:
    appid = '1255955027'
    secret_id = 'AKIDwnT9iA3caNyNbfqLJAqKdrxsdIm55URH'
    secret_key = 'oUyY0LWQJCC81mLm3b3KPSN6e4IQNAmC'
    bucket = 'nvrenlian'
    client = Client(appid, secret_id, secret_key, bucket)
    client.use_http()
    client.set_timeout(30)
else:
    appid = '1255316848'
    secret_id = 'AKIDkIacaJz26vZy83qAPO7anoZ4JI3ZDrdA'
    secret_key = 'QbV9XfX8TYNvDF2auzpPjqiLjsmRr2yf'
Example #17
0
        os.remove(filepath)
        print '\tdeleting from fs success'
        # 提交修改xxx
        db.commit()
    except:
        # 发生错误时回滚
        db.rollback()
        print '\trollback'
    sys.exit(1)

# 图片标签
#单个图片url
#print (client.tag_detect(CIUrl('YOUR URL')))
#单个图片file
print '图片标签'
b = client.tag_detect(CIFile(filepath))
tag = ''
print b['tags']
for c in b['tags']:
    if c['tag_confidence'] > 50:
        tag += c['tag_name'] + ','
tag = tag[:-1]
sql = 'update picture set label="' + tag + '" where picturename="' + filename + '"'
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
    print '\tupdate picture.label success'
except:
    # 发生错误时回滚