def detection(file_path): client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) image = get_file_content(file_path) client.carDetect(image) ret = client.carDetect(image, {'top_num': 10, 'baike_num': 5}) # 带参数调用车辆识别 pprint(ret) return ret
def index(): if request.method == 'GET': return render_template('index.html') else: img = request.files.get('img') if not img: # 没有上传图片则取url img_url = request.form.get('img_url') try: img = ur.urlopen(img_url) except Exception: return render_template('index.html', msg="请上传文件或URL地址") # 上传到百度接口 try: client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) options = {'top_num': 1, 'baike_num': 5} car_info = client.carDetect(img.read(), options) if car_info['result'][0]['name'] == '非车类': return render_template('index.html', msg="未识别到车类") car_index_name = car_info['result'][0]['name'] print(car_index_name) except Exception: return render_template('index.html', msg="接口繁忙,请稍后再试") try: cars_info = CarInfo.query.filter( CarInfo.index.ilike('%' + car_index_name + '%')) except Exception: cars_info = None if cars_info.count() != 0: return render_template('index.html', cars_info=cars_info) else: return render_template('index.html', msg="未识别到车类")
def chexing(): imageClassify = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) filepath = "1.png" def get_file_content(filepath): with open(filepath, 'rb') as fp: return fp.read() options = { 'baike_num': '0', } result = imageClassify.carDetect(get_file_content(filepath), options) return result """for i in range(len(result['result'])):
def car_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.carDetect(img, options=None) a = result.get('result') a = str(a) b = a.split(':') k = '可能植物:' for i in range(1, 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("}", '') b[i] = b[i].replace("year", '') 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) - 2, 3): plant_out = plant_out + plant_list[i] # plant_list[i+1] = plant_list[i+1].strip() # print() plant_out = plant_out + plant_list[i + 2].rjust( 30 - len(plant_list[i].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[1].strip()) read_data = plant_out print(plant_out) return read_data
def indentityxing(self): imageClassify = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) filepath = "1.png" def get_file_content(filepath): with open(filepath, 'rb') as fp: return fp.read() options = { 'baike_num': '0', } result = imageClassify.carDetect(get_file_content(filepath), options) self.textBrowser_2.setText(result['result'][0]['name'] + " " + '%.2f' % (result['result'][0]['score'] * 100) + "%\n" + result['result'][1]['name'] + " " + '%.2f' % (result['result'][1]['score'] * 100) + "%\n" + result['result'][2]['name'] + " " + '%.2f' % (result['result'][2]['score'] * 100) + "%\n")
SECRET_KEY = '8iYhDOgswCD8q6bcXbFGHE4DhGZ9sSwh ' 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(r'C:\Users\user98\Desktop\meishi.jpg') # """ 调用菜品识别 """ # json1=client.dishDetect(image)[u'result'] # for str in json1: # print str['name'] """ 如果有可选参数 """ options = {} options["top_num"] = 1 """ 带参数调用菜品识别 """ json = client.dishDetect(image, options)[u'result'] for str in json: print str['name'] image2 = get_file_content(r'C:\Users\user98\Desktop\car.jpg') optionscar = {} optionscar["top_num"] = 1 json2 = client.carDetect(image2, optionscar)[u'result'] for str in json2: print str['name']
from aip import AipImageClassify APP_ID = '11160858' API_KEY = "yk3QgeOs6o7F2lstKw8mKa0u" SECRET_KEY = "4X6GFZXYmn00FOfCLIw6aoOdvFtPrXQs" 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('luhu1.jpg') ''' 调用车辆识别 ''' print(client.carDetect(image, options={"top_num": 1})["result"][0]['name'])
SECRET_KEY = '1FQUf9D6qRYcd54ZEE0xKAVXYClKoXOb' client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() if __name__ == "__main__": filePath = input('输入图片的路径:') image = get_file_content(filePath) data = client.advancedGeneral(image) if data: print(data) result1 = data.get('result')[0] kind = result1.get('root') msg = result1.get('keyword') print(kind, msg) if '汽车' in kind: data = client.carDetect(image) if data: print(data) print('*' * 50) car1 = data.get('result')[0] carname = car1.get('name') color = data.get('color_result') print(carname, color)
def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) filename = secure_filename(file.filename) if os.path.exists("D:/CARS/"): file.save(os.path.join("D:/CARS/", filename)) fileurl = "D:/CARS/" + filename # time.strftime('%H:%M:%S', time.localtime(time.time())) strtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) APP_ID = '17061516' Type_client_id = '0aAPIpeYX7RbtFsEhSkzaFcY' Type_client_secret = 'W1jSIHOSa7zwVYnGyA2H4pmG3Y1tOpb1' get = get_type(fileurl) strtimefinal = datetime.datetime.strptime(strtime, '%Y-%m-%d %H:%M:%S') client = AipImageClassify(APP_ID, Type_client_id, Type_client_secret) image = get_file_content(fileurl) list = get_license_plate(fileurl) ctype = client.carDetect(image, options={"top_num": 1})["result"][0]["name"] db = MyDBHelper() db.addintime([strtimefinal, list]) print(type(strtime)) print(strtime) return jsonify({ 'str': list, 'time': strtime, 'type': ctype, "ctype": get }) else: os.makedirs("D:/CARS/") file.save(os.path.join("D:/CARS/", filename)) fileurl = "D:/CARS/" + filename get = get_type(fileurl) strtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) strtimefinal = datetime.datetime.strptime(strtime, '%Y-%m-%d %H:%M:%S') print(type(strtime)) APP_ID = '17061516' Type_client_id = '0aAPIpeYX7RbtFsEhSkzaFcY' Type_client_secret = 'W1jSIHOSa7zwVYnGyA2H4pmG3Y1tOpb1' client = AipImageClassify(APP_ID, Type_client_id, Type_client_secret) image = get_file_content(fileurl) list = get_license_plate(fileurl) ctype = client.carDetect(image, options={"top_num": 1})["result"][0]["name"] db = MyDBHelper() db.addintime([strtimefinal, list]) print(strtime) return jsonify({ 'str': list, 'time': strtime, 'type': ctype, "ctype": get }) return ''
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
#coding:utf-8 from aip import AipImageClassify import sys APP_ID = '17137507' API_KEY = 'h4tkLq9hM4r1XSM8NpoBq2Kw' SECRET_KEY = 'm1WEhso1O9rkwVv2UEpDx5N27iM1EV6W' filePath = sys.argv[1] """ 读取图片 """ def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() image = get_file_content(filePath) client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) """ 如果有可选参数 """ options = {} options["top_num"] = 3 options["baike_num"] = 5 """ 带参数调用车辆识别 """ res = client.carDetect(image, options) for i in res['result']: if i['baike_info']: print i['name'] print i['baike_info']['description'] else: print i['name']
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
def user_msg(msg): image_name = msg.file_name friend = msg.chat print(msg.chat) print('接收图片') msg.get_file(''+msg.file_name) #百度api车型识别参数初始化(具体请移步ai.baidu.com) APP_ID_type = '' API_KEY_type = '' SECRET_KEY_type = '' client_type = AipImageClassify(APP_ID_type,API_KEY_type,SECRET_KEY_type) #百度api车牌识别参数初始化(具体请移步ai.baidu.com) APP_ID_number = '' API_KEY_number = '' SECRET_KEY_number = '' client = AipOcr(APP_ID_number,API_KEY_number,SECRET_KEY_number) #读取图片 def file_extension(path): #定义一个取文件扩展名的函数 return os.path.splitext(path)[1] rootdir = os.path.dirname(os.path.realpath(__file__)) #获取当前路径 all_file = os.listdir(rootdir) #列出文件夹下所有的目录与文件 for file in all_file: #遍历所有文件 if file_extension(file)=='.py': continue #剔除本身的脚本文件 def get_file_content(file_Path): with open(file_Path,'rb') as fp: return fp.read() image = get_file_content(file) #调用百度api车型识别 car_type_result = client_type.carDetect(image,options = {'top_num':1})['result'][0]['name'] print(car_type_result) if car_type_result == '非车类': #判断是否是需要处理的车的照片 os.remove(file) else: #使用爬虫从汽车大全查找该车型价格 url = quote('http://sou.qichedaquan.com/qiche/'+car_type_result, safe=string.printable) #print(url) headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read() page_info = page_info.decode('utf-8') soup = BeautifulSoup(page_info, 'html.parser') #print(soup) title = soup.find('p','dealer_price') price = str(soup.find('em')) if price == 'None': #判断汽车大全网是否有该车型的信息 avg_price = 'Unkonwn' print(avg_price) else: price = ''.join(price.split()) #去除空格 min_price_list = [] a = 0 b = 0 for word in price: a = a+1 if word == '>': break for word in price: b = b+1 if word == '-': break c1 = a+1 #获取最低价第一个数字在字符串中的索引位置 c2 = b-1 #获取最低价最后一个数字在字符串中的索引位置 i = 0 for word1 in price: i = i+1 if i >= c1: min_price_list.append(word1) else: continue if i >= c2: break min_price = float(''.join(min_price_list)) #list转换float #min_price = np.float64(min_price_list) #print(min_price) max_price_list = [] a = 0 b = 0 for word in price: a = a+1 if word == '-': break for word in price: b = b+1 if word == '/': break c1 = a+1 #获取最高价第一个数字在字符串中的索引位置 c2 = b-3 #获取最高价最后一个数字在字符串中的索引位置 i = 0 for word1 in price: i = i+1 if i >= c1: max_price_list.append(word1) else: continue if i >= c2: break max_price = float(''.join(max_price_list)) #list转换float #max_price = np.float64(max_price_list) #print(max_price) avg_price = round((min_price + max_price)/2.0,2) #获取该车型平均价格 print('平均价格:',avg_price,'万元') avg_price_str = str(avg_price) #调用百度api车牌识别 ori = client.licensePlate(image) err = str('error_code'in ori) if err == 'True': car_number_result = '未检测到车牌' print(car_number_result) else: car_number_result = client.licensePlate(image)['words_result']['number'] print(car_number_result) print(type(car_number_result)) print(type(car_type_result)) print(type(avg_price_str)) message_all = '--------识别结果--------'+'\n车型:'+car_type_result+'\n车牌号:'+car_number_result+'\n参考价格'+avg_price_str print(message_all) #print(car_number_result,car_type_result,avg_price) #print('----------------------------------') #msg.reply('【本消息由机器自动发出,请勿回复】识别成功!!') msg.reply(message_all) os.remove(file)
def get_id(car): car_ret = [] for j in car["result"]: for k in j["List"]: for o in k["List"]: # t = {o["N"]: o["I"]} car_ret.append(o) return car_ret if __name__ == "__main__": image = get_file_content('static/1.jpg') url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1559819550562&di=2144b5c059daf2096558c9e05bf7da7e&imgtype=0&src=http%3A%2F%2Fpic.baike.soso.com%2Fp%2F20120114%2F20120114151019-1830199455.jpg" image = url_imgage(url) """ 调用车辆识别 """ client.carDetect(image) """ 如果有可选参数 """ options = {} options["top_num"] = 1 # options["baike_num"] = 5 """ 带参数调用车辆识别 """ out = client.carDetect(image, options) # print(out) # 车名 # print(out["result"][0]["name"]) # 搜索车名id和车系id # 车辆详细 # brand_api = "http://apis.haoservice.com/lifeservice/car/GetSeries" # serial_api = "http://apis.haoservice.com/lifeservice/car/GetModel/" # type_api = "http://apis.haoservice.com/lifeservice/car"