Exemplo n.º 1
0
    def _get_contact_from_aipimageclassify(self, image):
        try:
            from aip import AipImageClassify
        except ImportError:
            _logger.error(
                _('Odoo module e2yun_cards_ocr depends on the baidu-aip python module.'
                  ))
            raise UserError(
                _('Odoo module e2yun_cards_ocr depends on the baidu-aip python module.'
                  ))

        result = {}
        if AipImageClassify:
            APP_ID = self.env['ir.config_parameter'].sudo().get_param(
                'baidu_image_app_id', '16288732')

            API_KEY = self.env['ir.config_parameter'].sudo().get_param(
                'baidu_image_app_key', 'WhPQFWBWpzNtb3Y23xBIaXyW')

            SECRET_KEY = self.env['ir.config_parameter'].sudo().get_param(
                'baidu_image_secret_key', 'ibuLCnBoUVAdsAYID8ApA6XcQDsLHkLp')
            options = {}
            options["custom_lib"] = "false"
            client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)
            result = client.logoSearch(image, options)
        return result
Exemplo n.º 2
0
def detect_logos(path):
    client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)
    f = open(path, 'rb')
    image = f.read()
    f.close()
    print(client.logoSearch(image, {
        'custom_lib': 'true'
    }))
Exemplo n.º 3
0
class Image(object):
    def __init__(self, filename, regs):
        app_id, app_key, secret_key = regs
        #        self.app_id, self.app_key, self.secret_key = app_id, app_key, secret_key
        self.filename = filename
        self.image = get_img_content(filename)
        self.base64 = img2base64(self.image)
        self.client = AipImageClassify(app_id, app_key, secret_key)

    def is_same_as(self, image):
        return self.base64 == image.base64

    '''
    def _find_logo(self):
        res = None
        token = access_token(url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + self.app_key + '&client_secret=' + self.secret_key,
            key='access_token')
        params = {"custom_lib":True, "image":self.base64}
        url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/logo?access_token=" + token
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        data = json.loads(post_json(url, data=params, headers=headers))
        print(data)
        if data is not None:
            res = data.get('result')
        return res
    '''

    #    def _result(self, result_num, result):
    #        for i in range(result_num):
    #            r = result[i]

    def find(self, options=None):
        if options is None:
            options = {}
        return self.client.advancedGeneral(self.image, options)

    def find_logo(self, options=None):
        if options is None:
            options = {}
        r = self.client.logoSearch(self.image, options)
        result_num = r.get('result_num')
        result = r.get('result')
        return result_num, result
Exemplo n.º 4
0
def BaiDu_image_recognize(file_path, recognize_type):
    """
    图像识别
    :param file_path: 文件路径
    :param recognize_type: 识别类型,共12种:
                1. 通用图像识别
                2. 菜品识别
                3. 车辆识别
                4. logo商标识别
                5. 动物识别
                6. 植物识别
                7. 图像主体检测
                8. 地标识别
                9. 食材识别
                10. 红酒识别
                11. 货币识别
    :return:
    """
    # TODO 隐私信息
    """ 你的 APP_ID API_KEY SECRET_KEY """
    app_id = '23899102'  # '你的 App ID'
    api_key = 'GKHIEq6gVOfp2AeRxfUopSDM'  # '你的 Api Key'
    secret_key = 'dLrlMlGemQ1oan2OS8GogLDD0dt1HuVI'  # '你的 Secret Key'

    # 获取百度云操作类对象
    client = AipImageClassify(app_id, api_key, secret_key)
    image = get_file_content(file_path)

    # """ 调用通用物体识别 """
    # result = client.dishDetect(image)
    # print(result)
    """ 如果有可选参数 """
    options = {"baike_num": 5}
    """ 带参数调用通用物体识别 """
    if recognize_type == 1:  # 通用图像识别
        response = client.advancedGeneral(image, options)
    elif recognize_type == 2:  # 菜品识别
        response = client.dishDetect(image, options)
    elif recognize_type == 3:  # 车辆识别
        response = client.carDetect(image, options)
    elif recognize_type == 4:  # logo商标识别
        response = client.logoSearch(image)
    elif recognize_type == 5:  # 动物识别
        response = client.animalDetect(image, options)
    elif recognize_type == 6:  # 植物识别
        response = client.plantDetect(image, options)
    elif recognize_type == 7:  # 图像主体检测
        response = client.objectDetect(image)
    elif recognize_type == 8:  # 地标识别
        response = client.landmark(image)
    # 花卉识别已经移除
    # elif recognize_type == 9:   # 花卉识别
    #     response = client.flower(image)
    elif recognize_type == 9:  # 食材识别
        response = client.ingredient(image, options)
    elif recognize_type == 10:  # 红酒识别
        response = client.redwine(image)
    elif recognize_type == 11:  # 货币识别
        response = client.currency(image)
    else:
        response = None
    response = response['result'][0]
    return response
Exemplo n.º 5
0
class BaiduDetector(object):
    def __init__(self, image_path):
        self.image_path = image_path
        self.image = get_file_content(image_path)
        self.client = AipImageClassify(baidu_appid, baidu_apikey,
                                       baidu_secretkey)
        self.object_class = ''
        self.object_classkeyword = ''
        self.result_string = ''
        self.cls_string = ''
        self.object_keyword = ''
        self.baike_des = ''
        self.ignore_reply = 0

    def config_result(self, result):
        print('二级识别')
        print(result)
        result_arr = result['result']
        self.object_keyword = '按照' + self.cls_string + '属性进行二级识别:'
        for obj in result_arr:
            probability = 0
            if 'probability' in obj.keys():
                probability = float(obj['probability'])
            elif 'score' in obj.keys():
                probability = float(obj['score'])
            percent = probability * 100.0

            if percent == 0:
                self.object_keyword = self.object_keyword + '\n' + '可能是:' + obj[
                    'name']
            else:
                self.object_keyword = self.object_keyword + '\n' + str(
                    round(percent, 0)) + '%的可能是:' + obj['name']

        # result_best = result_arr[0]
        # self.object_keyword = result_best['name']
        # baike_info = result_best['baike_info']
        # self.baike_des = baike_info['description']

    def label_detect(self, label, general_result):

        result_arr = general_result['result']
        result_best = result_arr[0]

        if '车' in label:
            print('车')
            self.cls_string = '汽车'
            result = self.client.carDetect(self.image)
            self.config_result(result)
        elif '食物' in label:
            print('食物')
            self.cls_string = '食物'
            result = self.client.dishDetect(self.image)
            self.config_result(result)
        elif 'Logo' in label:
            print('Logo')
            self.cls_string = 'Logo'
            result = self.client.logoSearch(self.image)
            self.config_result(result)
        elif '动物' in label:
            print('动物')
            self.cls_string = '动物'
            result = self.client.animalDetect(self.image)
            self.config_result(result)
        elif '植物' in label:
            print('植物')
            self.cls_string = '植物'
            result = self.client.plantDetect(self.image)
            self.config_result(result)
        elif '地标' in label or '建筑' in label:
            print('地标')
            self.cls_string = '地标'
            result = self.client.landmark(self.image)
            print('二级属性')
            print(result)
            self.object_keyword = ''

            result_obj = result['result']
            if (result_obj is list):
                for obj in result_obj:
                    self.object_keyword = self.object_keyword + obj[
                        'landmark'] + '?'
            elif (result_obj is dict):
                self.object_keyword = self.object_keyword + result_obj[
                    'landmark'] + '?'

        elif '人物' in label:
            print('人物')
            self.cls_string = '人物'
            self.object_keyword = result_best['keyword']
        else:
            self.object_keyword = result_best['keyword']

    def womengrade(self):
        f = open("./react_words.json", encoding='utf-8')
        map = json.load(f)
        womengrade = map['womengrade']
        index = random.randint(0, len(womengrade) - 1)
        return womengrade[index]

    def general_detect(self):
        result = self.client.advancedGeneral(self.image)
        print('通用识别')
        print(result)
        result_arr = result['result']
        result_best = result_arr[0]

        # baike_info = result_best['baike_info']
        # self.baike_des = baike_info['description']

        label_str = ''
        result_str = '图像识别大类:'
        self.ignore_reply = 0
        for obj in result_arr:
            #如果大于20%的几率是文字图,屏幕截图,不回答
            score = float(obj['score'])
            percent = score * 100.0
            keyword = obj['keyword']
            if percent > 20 and ('屏幕截图' in keyword or '文字图' in keyword):
                self.ignore_reply = 1
            result_str = result_str + '\n' + str(round(
                percent, 0)) + '%的可能是:' + keyword + '(' + obj['root'] + ')'
            label_str = label_str + obj['root'] + '?' + obj['keyword'] + '?'

        print('label = ' + label_str)

        if self.ignore_reply == 0:
            self.result_string = result_str
            self.object_class = result_best['root']
            self.object_classkeyword = result_best['keyword']
            self.label_detect(label_str, result)
        else:
            print('要忽略显示')

    def answer(self):

        if self.ignore_reply == 1:
            return ''

        cls_arr = self.object_class.split('-')

        # 二级属性
        second_att = ''
        if self.object_keyword != '':
            second_att = '\n' + self.object_keyword
        # answer = '这是'+ self.object_classkeyword +'吧,一种' + cls_arr[len(cls_arr)-1] + second_att
        answer = self.result_string + second_att

        if '女人' in answer or '美女' in answer:
            return self.womengrade()
        else:
            return answer


# if __name__ == '__main__':
#     dectector = BaiduDetector('./car.jpeg')
#     dectector.general_detect()
#     print(dectector.object_class)
#     print(dectector.object_classkeyword)
#     print(dectector.object_keyword)
#     print(dectector.baike_des)
class IR:
    def __init__(self, app_id, api_key, secret_key):
        self.client = AipImageClassify(app_id, api_key, secret_key)
        self.options = {}

    def do_image_recognition(self, image_file):
        image = get_file_content(image_file)
        contents = self.distinguish_general(image)
        type = contents.get("result")[0].get("root")
        keyword = contents.get("result")[0].get("keyword")
        if type in ["商品-食物"]:
            dishes = self.distinguish_dishes(image)
            print(dishes)
            message = "图片为食品:"
            for dishe in dishes.get("result"):
                if message == "图片为食品:":
                    message += "\n"
                else:
                    message += "\n或者 "
                if dishe.get("has_calorie"):
                    calorie = dishe.get("calorie")
                else:
                    calorie = 0
                message += "名称:" + dishe.get(
                    "name") + ",每100克含有" + calorie + "千卡的卡路里"
            return message
        elif type in ["交通工具-汽车"]:
            cars = self.distinguish_cars(image)
            color = cars.get("color_result")
            if color is None:
                color = "无法识别"
            message = "图片中车体为" + color + ",可能为以下车型:"
            for car in cars.get("result"):
                score = str(round(car.get("score") * 100))
                name = car.get("name")
                year = car.get("year")
                description = car.get("baike_info").get("description")
                if description is None:
                    description = "无描述"
                message += "\n" + name + ",出厂年份:" + year + ",(" + "可信度" + score + "%)\n" + description
            return message
        elif "动物" in type:
            animals = self.distinguish_animals(image)
            message = "图片为" + type + ",可能为以下品类:"
            for animal in animals.get("result"):
                score = str(round(float(animal.get("score")) * 100))
                name = animal.get("name")
                description = animal.get("baike_info").get("description")
                if description is None:
                    description = "无描述"
                message += "\n" + name + ":(" + "可信度" + score + "%)\n" + description
            return message
        elif "植物" in type:
            plants = self.distinguish_plants(image)
            message = "图片为" + type + ",可能为以下品类:"
            for plant in plants.get("result"):
                score = str(round(plant.get("score") * 100))
                name = plant.get("name")
                description = plant.get("baike_info").get("description")
                if description is None:
                    description = "无描述"
                message += "\n" + name + ":(" + "可信度" + score + "%)\n" + description
            return message
        else:
            message = "图片可能为以下内容:"
            for content in contents.get("result"):
                print(content)
                keyword = str(content.get("keyword"))
                score = str(round(content.get("score") * 100))
                description = content.get("baike_info").get("description")
                if description is None:
                    description = "无描述"
                message += "\n" + keyword + ":(" + "可信度" + score + "%)\n" + description
            return message

    def distinguish_general(self, image):
        self.options["baike_num"] = 5
        results = self.client.advancedGeneral(image, self.options)
        print(results)
        return results

    def distinguish_dishes(self, image):
        """ 如果有可选参数 """
        self.options["top_num"] = 3
        self.options["filter_threshold"] = "0.7"
        self.options["baike_num"] = 5
        """ 带参数调用菜品识别 """
        results = self.client.dishDetect(image, self.options)
        print(results)
        return results

    def distinguish_cars(self, image):
        """ 如果有可选参数 """
        self.options["top_num"] = 3
        self.options["baike_num"] = 5
        """ 带参数调用车辆识别 """
        results = self.client.carDetect(image, self.options)
        print(results)
        return results

    def distinguish_logos(self, image):
        self.options["custom_lib"] = "true"
        """ 带参数调用logo商标识别 """
        results = self.client.logoSearch(image, self.options)
        print(results)
        return results

    def distinguish_animals(self, image):
        self.options["top_num"] = 3
        self.options["baike_num"] = 5
        """ 带参数调用动物识别 """
        results = self.client.animalDetect(image, self.options)
        print(results)
        return results

    def distinguish_plants(self, image):
        self.options["baike_num"] = 5
        """ 带参数调用植物识别 """
        results = self.client.plantDetect(image, self.options)
        print(results)
        return results
Exemplo n.º 7
0
from aip import AipImageClassify

APP_ID = '10833639'
API_KEY = 'U6gxjm6SXgbO9xvvnl0FzXOQ'
SECRET_KEY = '716Sk3F86ThEOG48Bxu5wz8a96iDKO8S'

client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)


def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


image = get_file_content('./xtl.jpg')
reply = client.logoSearch(image)

print str(reply)
print '+++++ get resultList'
resultList = reply['result']
print type(resultList)
print str(resultList)
print '++++++ get result name'
result = resultList[0]
print result['name']

image = get_file_content('./xigua.jpg')
plant = client.plantDetect(image)
print str(plant)
print '+++++ get resultList'
resultList = plant['result']