class BaiDuAPI(object):
    #定义一个类
    def __init__(self, filepath):
        target = configparser.ConfigParser()
        target.read(filepath, encoding='utf-8-sig')
        app_id = target.get('password', 'APP_ID')
        api_key = target.get('password', 'API_KEY')
        secret_key = target.get('password', 'SECRET_KEY')

        self.client = AipImageClassify(app_id, api_key, secret_key)

    #读取图片
    def get_file_content(self, filePath):
        with open(filePath, 'rb') as fp:
            return fp.read()

    def picture2Name(self, filepath):
        #读取图片
        images = self.get_file_content(filepath)
        alltexts = self.client.plantDetect(images)
        text = alltexts.get('result', '')
        print(text)
        name = []
        for word in alltexts['result']:
            name.append(word['name'])
        text = alltexts.get('result', '')
        return name
Esempio n. 2
0
def myplantDetect():

    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('static/images/test.jpg')

    """ 调用植物识别 """

    """ 如果有可选参数 """

    options = {}
    #options["top_num"] = 3
    #options["filter_threshold"] = "0.7"
    options["baike_num"] = 5

    """ 带参数调用植物识别 """
    result=client.plantDetect(image, options)

    print(json.dumps(result))
    return result #返回的是字典对象
Esempio n. 3
0
def main(arg):
    """ 你的 APPID AK SK """
    APP_ID = '23521368'
    API_KEY = 'ZsU4yX9sebQmW06s7xc3oaaG'
    SECRET_KEY = '94OsjVY5GwbaD8QZRLqzRGQgWhwdWcTq'

    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(arg[0])
    """ 调用通用物体识别 """

    res = client.advancedGeneral(image)
    sim_res = "\nGeneral:\n"
    poem_keys = ""
    for i in range(len(res["result"])):
        sim_res += res["result"][i]["keyword"] + ' '
        if len(res["result"][i]["keyword"]) > 4:
            res["result"][i]["keyword"] = res["result"][i]["keyword"][:4]
        if i < 3:
            poem_keys += res["result"][i]["keyword"] + ' '
        if i == 3:
            poem_keys += res["result"][i]["keyword"]

    res = client.animalDetect(image)
    sim_res += "\nAnimal:\n"
    for i in range(len(res["result"])):
        sim_res += res["result"][i]["name"] + ' '

    res = client.plantDetect(image)
    sim_res += "\nPlant:\n"
    for i in range(len(res["result"])):
        sim_res += res["result"][i]["name"] + ' '

    res = client.dishDetect(image)
    sim_res += "\nDish:\n"
    for i in range(len(res["result"])):
        sim_res += res["result"][i]["name"] + ' '

    sim_res += "\nPoem:\n"
    conn = s.connect(("59.78.8.125", 50010))

    s.send(('{"keys":"' + poem_keys + '","yun":"' + str(random.randint(0, 5)) +
            '","pattern_id":"' + str(random.randint(0, 3)) +
            '"}').encode('utf-8'))
    poem = s.recv(1024).decode('utf-8')
    sim_res += poem

    print(sim_res)
Esempio n. 4
0
    def post(self, request):
        from aip import AipImageClassify
        pic = request.FILES.get("pic")
        # 将前端提交来的图片保存本地
        # fs = FileSystemStorage()
        # fs.save(pic.name, pic)
        # print(os.path.join(BASE_DIR, "frontend/dist/static/media/test"))
        if pic:
            with open(
                    os.path.join(BASE_DIR,
                                 "frontend/dist/static/media/plant/%s") %
                    pic.name, 'wb') as f:
                for chunk in pic.chunks():
                    f.write(chunk)
            """ 你的 APPID AK SK """

            client = AipImageClassify(APP_ID_BAIDU, API_KEY_BAIDU,
                                      SECRET_KEY_BAIDU)
            """ 读取图片 """
            def get_file_content(filePath):
                with open(filePath, 'rb') as fp:
                    return fp.read()

            image = get_file_content(
                os.path.join(
                    BASE_DIR,
                    "frontend/dist/static/media/plant" + '/' + pic.name))
            #
            # """ 调用通用物体识别 """
            # resp = client.animalDetect(image)
            # print(resp)
            """ 如果有可选参数 """
            options = {}
            options["top_num"] = 3
            options["baike_num"] = 5
            """ 带参数调用通用植物识别 """
            try:
                resp = client.plantDetect(image, options)
                data = {
                    "name": resp['result'][0]['name'],
                    "description":
                    resp['result'][0]['baike_info']['description']
                }
                return JsonResponse(data=data,
                                    json_dumps_params={'ensure_ascii': False})
            except Exception as e:
                return HttpResponse('请提交植物图片')
        else:
            return HttpResponse('请先选择植物图片')
Esempio n. 5
0
def plant_rec(img):
    APP_ID = '11173506'
    API_KEY = 'pwcq1rBuPvGbrOi8ORqGUKKp'
    SECRET_KEY = 'SHguMaeswBLDOrKSbGyGtjfyasLt3kQo'
    # 初始化AipFace对象
    aipPlant = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)
    # 读取图片
    # 定义参数变量
    options = {
        'max_face_num': 1,
        'face_fields':
        "age,beauty,expression,faceshape,gender,glasses,type,race",
    }
    result = aipPlant.plantDetect(img, options=None)
    a = result.get('result')
    a = str(a)
    b = a.split(':')
    k = '可能植物:'
    for i in range(0, len(b)):
        b[i] = b[i].replace(',', '')
        b[i] = b[i].replace('[', '')
        b[i] = b[i].replace(']', '')
        b[i] = b[i].replace("'name'", '')
        b[i] = b[i].replace("'score'", '')
        b[i] = b[i].replace("'", '')
        b[i] = b[i].replace("{", '')
        b[i] = b[i].replace("}", '')
        k = k + b[i]
        k = k + '\n'
    # print(k)
    plant_list = k.split('\n')
    plant_out = '植物名称' + '可能性'.rjust(30 - len('植物名称'.encode('utf-8'))) + '\n'
    for i in range(1, len(plant_list) - 1, 2):
        plant_out = plant_out + plant_list[i + 1]
        # plant_list[i+1] = plant_list[i+1].strip()
        # print()
        plant_out = plant_out + plant_list[i].rjust(
            35 - len(plant_list[i + 1].encode('utf-8')))
        plant_out = plant_out + '\n'
    # print(plant_list[2])
    plant_out = plant_out + 'https://baike.baidu.com/item/' + parse.quote(
        plant_list[2].strip())
    read_data = plant_out
    return read_data
Esempio n. 6
0
def main(arg):
    """ 你的 APPID AK SK """
    APP_ID = '23521368'
    API_KEY = 'ZsU4yX9sebQmW06s7xc3oaaG'
    SECRET_KEY = '94OsjVY5GwbaD8QZRLqzRGQgWhwdWcTq'

    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(arg[0])

    """ 调用通用物体识别 """

    res = client.advancedGeneral(image)
    sim_res = "\nGeneral:\n"
    for i in range(len(res["result"])):
        sim_res += res["result"][i]["keyword"] + '; '

    res = client.animalDetect(image)
    sim_res += "\nAnimal:\n"
    for i in range(len(res["result"])):
        sim_res += res["result"][i]["name"] + '; '

    res = client.plantDetect(image)
    sim_res += "\nPlant:\n"
    for i in range(len(res["result"])):
        sim_res += res["result"][i]["name"] + '; '

    res = client.dishDetect(image)
    sim_res += "\nDish:\n"
    for i in range(len(res["result"])):
        sim_res += res["result"][i]["name"] + '; '

    print(sim_res)
Esempio n. 7
0
from aip import AipImageClassify

# 定义常量
APP_ID = '23942564'
API_KEY = '7uL42GlUO4mMYnVGxUp8GU8i'
SECRET_KEY = '5CxKfUO9412hbTueg9NMwajx82M3op52'
# 初始化AipFace对象
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('3.jpg')
#将左侧括号内hua.jpg替换为待识别的图片路径

result = client.plantDetect(image)['result']
for i in result:
    print(i['name'], i['score'])
Esempio n. 8
0
#coding:utf-8
from aip import AipImageClassify
""" 你的 APPID AK SK """
APP_ID = '10254191'
API_KEY = 'eHP1Ku9GhxgvhElbXNEkufhU'
SECRET_KEY = 'pe0BHWBhEiPB5cBwgARmdaPS4EWN02N5'

aipImageClassify = 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('12.jpg')

#result=aipImageClassify.carDetect(image) #汽车
#result=aipImageClassify.animalDetect(image)
result = aipImageClassify.plantDetect(image)
print(result)
print(result["result"][0]["name"])
Esempio n. 9
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
Esempio n. 10
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
Esempio n. 12
0
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']
print type(resultList)
print str(resultList)
print '++++++ get result name'
result = resultList[0]
print result['name']
Esempio n. 13
0
from aip import AipImageClassify
""" 你的 APPID AK SK """
APP_ID = '16042058'
API_KEY = 'AyuLyqu4FNB4klZvGAHSjVaQ'
SECRET_KEY = 'MI53Tuf71Xt4KoQiqT7G3lUH96DC3mZ8'

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('yueji.jpeg')
#
# """ 调用通用物体识别 """
# resp = client.animalDetect(image)
# print(resp)
""" 如果有可选参数 """
options = {}
options["top_num"] = 3
options["baike_num"] = 5
""" 带参数调用通用植物识别 """
resp = client.plantDetect(image, options)
print(resp)
print(resp['result'][0]['name'])
print(resp['result'][0]['baike_info']['description'])