Ramils/softwareengineering1
0
1import os2os.system("pip install gradio==2.9b23")3import numpy as np4import math5import matplotlib.pyplot as plt6import onnxruntime as rt7import cv28import json9import gradio as gr10from huggingface_hub import hf_hub_download11import onnxruntime as rt12 13modele = hf_hub_download(repo_id="onnx/EfficientNet-Lite4", filename="efficientnet-lite4-11.onnx")14labels = json.load(open("labels_map.txt", "r"))15 16 17def pre_process_edgetpu(img, dims):18 output_height, output_width, _ = dims19 img = resize_with_aspectratio(img, output_height, output_width, inter_pol=cv2.INTER_LINEAR)20 img = center_crop(img, output_height, output_width)21 img = np.asarray(img, dtype='float32')22 # converts jpg pixel value from [0 - 255] to float array [-1.0 - 1.0]23 img -= [127.0, 127.0, 127.0]24 img /= [128.0, 128.0, 128.0]25 return img26 27def resize_with_aspectratio(img, out_height, out_width, scale=87.5, inter_pol=cv2.INTER_LINEAR):28 height, width, _ = img.shape29 new_height = int(100. * out_height / scale)30 new_width = int(100. * out_width / scale)31 if height > width:32 w = new_width33 h = int(new_height * height / width)34 else:35 h = new_height36 w = int(new_width * width / height)37 img = cv2.resize(img, (w, h), interpolation=inter_pol)38 return img39 40def center_crop(img, out_height, out_width):41 height, width, _ = img.shape42 left = int((width - out_width) / 2)43 right = int((width + out_width) / 2)44 top = int((height - out_height) / 2)45 bottom = int((height + out_height) / 2)46 img = img[top:bottom, left:right]47 return img48 49 50sess = rt.InferenceSession(modele)51 52def inference(img):53 img = cv2.imread(img)54 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)55 56 img = pre_process_edgetpu(img, (224, 224, 3))57 58 img_batch = np.expand_dims(img, axis=0)59 60 results = sess.run(["Softmax:0"], {"images:0": img_batch})[0]61 result = reversed(results[0].argsort()[-5:])62 resultdic = {}63 for r in result:64 resultdic[labels[str(r)]] = float(results[0][r])65 return resultdic66 67 68title="Я могу определить породу твоего животного!"69description="Просто перетащи нужное фото и я пробегусь по б"70examples=[['cat2.jpg'],['catonnx.jpg'],['popugai.jpg']]71 72 73gr.Interface(inference,gr.inputs.Image(type="filepath"),"label",title=title,description=description,examples=examples).launch()