def __init__(self, conf_path): config = configparser.ConfigParser() config.read(conf_path) self.__app_id = config["image"]["app_id"] self.__api_key = config["image"]["api_key"] self.__secret_key = config["image"]["secret_key"] self.__client = AipImageClassify(self.__app_id, self.__api_key, self.__secret_key)
def recv_picture(conn, addr): client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) with open('pic.jpeg', 'wb') as fp: first=conn.recv(BUFF_SIZE) file_size, first = first.split(bytes('<SEPARATOR>', 'utf-8')) file_size = int(file_size) print(file_size) fp.write(first) file_size -= len(first) while file_size > 0: data = conn.recv(BUFF_SIZE) if not data: break fp.write(data) file_size -= len(data) print('picture received') fp.close() img = get_file_content("pic.jpeg") res = client.advancedGeneral(img) name = res['result'][0]['keyword'] kind = get_kind(name) kind_list = ['可回收垃圾', '有害垃圾', '厨余垃圾', '其他垃圾', '无法识别'] kind_name = kind_list[int(kind)] print('类型:%s' % (kind_name)) # res=recognize.application() conn.send(bytes(str(kind)+'\r', 'utf-8')) conn.close()
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 __init__(self, url=None, file_path=None): self.file_path = file_path self.client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) self.param = None self.url = url self.img = None self.response = None
def query_api(self, filePath, options=None): image = self.get_file_content(filePath) client = AipImageClassify(self.id, self.key, self.secret) res = client.advancedGeneral(image)['result'] res = sorted(res, key=lambda x: x['score'], reverse=True) if len(res) >= 3: res = res[:3] for r in res: r['score'] = float('%.2f' % (r['score'] * 100)) print(res) return res # path="D:/GitHub/animaltest/animaltest/static/uploads/188.jpg" # animalAPI=animalAPI(APP_ID,API_KEY,SECRET_KEY) # animalAPI.query_api(path) # image = get_file_content('D:/GitHub/animaltest/animaltest/static/uploads/188.jpg') # """ 调用通用物体识别 """ # client.advancedGeneral(image) # """ 如果有可选参数 """ # options = {} # options["baike_num"] = 3 # """ 带参数调用通用物体识别 """ # print(client.advancedGeneral(image))
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 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 #返回的是字典对象
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 _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
def baidu_image(image_path): # content = '' options = dict() options['baike_num'] = 1 client = AipImageClassify(BAIDU['IMAGE']['WECHAT']['APP_ID'], BAIDU['IMAGE']['WECHAT']['API_KEY'], BAIDU['IMAGE']['WECHAT']['SECRET_KEY']) def get_file_content(file_path): with open(file_path, 'rb') as fb: return fb.read() image = get_file_content(image_path) response = client.advancedGeneral(image, options) # print(response) if 'error_code' not in response: if response['result'][0]['baike_info'] and response['result'][0][ 'root'] != '非自然图像-屏幕截图': keyword = response['result'][0]['keyword'] description = response['result'][0]['baike_info']['description'] image_url = response['result'][0]['baike_info']['image_url'] reply_image_path = ".\\grp_img\\reply_%s.jpg" % image_path.split( '\\')[2][:-4] with open(reply_image_path, 'wb') as f: f.write(requests.get(image_url).content) content = '%s\n%s' % (keyword, description) return content, reply_image_path else: return None
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/animal/%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() filePath = os.path.join( BASE_DIR, "frontend/dist/static/media/animal" + '/' + pic.name) # print(filePath) image = get_file_content( os.path.join( BASE_DIR, "frontend/dist/static/media/animal" + '/' + pic.name)) # # """ 调用通用物体识别 """ # resp = client.animalDetect(image) # print(resp) """ 如果有可选参数 """ options = {} options["top_num"] = 3 options["baike_num"] = 5 """ 带参数调用通用动物识别 """ try: resp = client.animalDetect(image, options) # print(resp) name = resp['result'][0]['name'] desc = resp['result'][0]['baike_info']['description'] # print(resp['result'][0]['name']) # save_path = image_biaozhu(filePath, name) # print(save_path) data = {"name": name, "description": desc} # 返回图片给前端显示 return JsonResponse(data=data, json_dumps_params={'ensure_ascii': False}) except Exception as e: # print(e) return HttpResponse('请提交动物图片') else: return HttpResponse('请先提交动物图片')
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' }))
def tag_recognition(url, APP_ID, API_KEY, SECRET_KEY): APP_ID = APP_ID API_KEY = API_KEY SECRET_KEY = SECRET_KEY client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) img_response = requests.get(url) response = client.advancedGeneral(img_response.content) return response
def __init__(self): super().__init__() self.APP_ID = secure.DU_CV_API_ID self.API_KEY = secure.DU_CV_API_KEY self.SECRET_KEY = secure.DU_CV_SECRET_KEY # this is the source object to be wrapped self.baidu_client = AipImageClassify(self.APP_ID, self.API_KEY, self.SECRET_KEY)
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 baidu_img_realize(filepath): APP_ID = APP_ID API_KEY = API_KEY SECRET_KEY = SECRET_KEY aipimg = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) options = {} image = get_file_content(filepath) aipimg.advancedGeneral(image) result = aipimg.advancedGeneral(image, options) return result
def query_api(self,filePath,options=None): image=self.get_file_content(filePath) client = AipImageClassify(self.id, self.key, self.secret) res=client.advancedGeneral(image)['result'] res=sorted(res,key=lambda x:x['score'],reverse=True) if len(res)>=3: res=res[:3] for r in res: r['score']=float('%.2f' % (r['score']*100)) print(res) return res
def image_labels(filePath): APP_ID = '16562491' API_KEY = 'RjFLMA41ELxZG0A07A3UgxDV' SECRET_KEY = '4Kk6jdzfNliYwEVFCOrjwtUee7Ylu6QP' filePath = "/home/lwf/scan_recognition/" + filePath client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) image = get_file_content(filePath) client.advancedGeneral(image) options = {} options["baike_num"] = 5 ret = client.advancedGeneral(image, options) return ret['result'][0]['root'] + ret['result'][0]['keyword']
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 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 get_pic_detail(): """ 你的 APPID AK SK """ APP_ID = '10327698' API_KEY = 'xe7uEVwG7aPfIwrYdCpbBBke' SECRET_KEY = 'rEdBGcYjOPmq8ZZG2GVF4XXjkvva3UGC' 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('00.jpg') options = {} print(aipImageClassify.objectDetect(image, options))
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]) """ 调用通用物体识别 """ print(client.advancedGeneral(image))
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
class ClassifyApi: def __init__(self): APP_ID = "11455535" API_KEY = "oGUA2c9R2CjWFnrKTCSHLbTY" SECRET_KEY = "qy6QqdUsfNs5cmRys9RX2cECo0H2vjX3" self.client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) # 识别图片有可能叫什么 def classify(self, url): try: image = open(url, 'rb').read() msg = self.client.advancedGeneral(image) rets = [] result = msg.get("result") if result != None: # 会存在 api调用次数上线,不返回数据了 for i in result: temp = { "root": i.get("root").encode("utf-8"), "keyword": i.get("keyword").encode("utf-8"), "score": float(i.get("score")) } rets.append(temp) return rets else: return None except Exception, e: print e raise RuntimeError("百度api调用异常")
class ImageClassify: def __init__(self,app_id,api_key,secret_key): self.image_client = AipImageClassify(app_id,api_key,secret_key) self.words_client = AipOcr(app_id,api_key,secret_key) def _get_token(self): url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+self.api_key+'&client_secret='+self.secret_key response = requests.get(url) if response and response.status_code == 200: content = response.json() token = content.get('access_token') or '' return token return None def _get_file_content(self,file_path): with open(file_path, 'rb') as fp: return fp.read() def resolve_image(self,file_path): image = self._get_file_content(file_path) contents = self.image_client.advancedGeneral(image) result = contents.get('result')[0] return result.get('keyword') def resolve_words(self,file_path): words = self._get_file_content(file_path) contents = self.words_client.basicGeneral(words) result = contents.get('words_result')[0] return result.get('words')
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 content_find_file(): img_list = globalvar.get_value('img_list_global') show_img = img_list[len(img_list) - 1] global APP_ID, API_KEY, SECRET_KEY client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) # print(type(show_img)) #PIL Image # 1 保存 2 读文件流 show_img.save('baidu_ai_temp.jpg') baidu_ai_temp = open('baidu_ai_temp.jpg', 'rb').read() r = client.advancedGeneral(baidu_ai_temp) # jpg png图片的二进制 # print(r) t = r['result'][0]['keyword'] # print(t) messagebox.showinfo(title='信息', message=('这可能是' + t + '!')) # return ok
class BaiduAPi: appId = "" apiKey = "" secretKey = "" client = AipImageClassify(appId, apiKey, secretKey) @staticmethod def get_plant_name(image): return BaiduAPi.client.plantDetect(image)["result"][0]["name"]
def sss(img_url): APP_ID = '17926029' API_KEY = 'dvzmdFFaMFidNass4pZcYals' SECRET_KEY = 'GTRmEpFHT1zXVNEhWX3rzzfLgXFkLREf' client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY) print(img_url) def get_file_content(img): with open(img, 'rb') as fp: return fp.read() image = get_file_content(img_url) # 调用通用物体识别 client.advancedGeneral(image) # 如果有可选参数 options = {} options["baike_num"] = 5 # 带参数调用通用物体识别 result = client.advancedGeneral(image, options) return result
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