def model_predict(img_path): ENDPOINT = "https://drclass-prediction.cognitiveservices.azure.com/" prediction_key = "5412cdf1a9bb4c8d8df7f42a24c28cbf" prediction_resource_id = '9147ebd0-f315-4c8b-9e76-1ecf5a92ffe5' prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) predictor = CustomVisionPredictionClient(ENDPOINT, prediction_credentials) # Now there is a trained endpoint that can be used to make a prediction prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) predictor = CustomVisionPredictionClient(ENDPOINT, prediction_credentials) # Now there is a trained endpoint that can be used to make a prediction prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) predictor = CustomVisionPredictionClient(ENDPOINT, prediction_credentials) project_id = '97dbe87d-c6e3-4f0f-8103-f71b5bd281ed' publish_iteration_name = 'Iteration1' with open(img_path, "rb") as image_contents: results = predictor.classify_image(project_id, publish_iteration_name, image_contents.read()) # Display the results. for prediction in results.predictions: return prediction.tag_name + ' ' + prediction.probability * 100
def __init__(self, endpoint, key, resource_id, project_id=None): """ Class Constructor, takes the id from Azure Custom Vision. Here the key will be used both for training and predicition Args: ---- endpoint: str key: str resource_id: str project_id: str """ training_credentials = ApiKeyCredentials( in_headers={"Training-key": key}) prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": key}) self.trainer = CustomVisionTrainingClient(endpoint, training_credentials) self.predictor = CustomVisionPredictionClient(endpoint, prediction_credentials) self.project_id = project_id self.tags = {} if project_id is not None: for t in self.trainer.get_tags(project_id): self.tags[t.name] = t.id return
def getPredictionBatch(ENDPOINT, publish_iteration_name, prediction_key, prediction_resource_id, file, training_key, project_name): # Now there is a trained endpoint that can be used to make a prediction prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) training_credentials = ApiKeyCredentials( in_headers={"Training-key": training_key}) predictor = CustomVisionPredictionClient(ENDPOINT, prediction_credentials) trainer = CustomVisionTrainingClient(ENDPOINT, training_credentials) projects = trainer.get_projects() res_batch = {} js_res = {} #Retrieve the object dection project and its tags #Current assumes one tag for p in projects: if p.name == project_name: project = trainer.get_project(p.id) tags = trainer.get_tags(project.id) print('Project Found') for url in file: info = url.split() name = info[0] url = info[1] try: response = requests.get(url) except: print("error retrieving image: " + url) exit(-1) # Open the sample image and get back the prediction results. results = predictor.detect_image(project.id, publish_iteration_name, response.content) # Display the results. js_res["vehicle"] = [] for prediction in results.predictions: x = { "confidence": "{0:.2f}%".format(prediction.probability * 100), "bbox_left": "{0:.2f}".format(prediction.bounding_box.left), "bbox_right": "{0:.2f}".format(prediction.bounding_box.top), "bbox_width": "{0:.2f}".format(prediction.bounding_box.width), "bbox_height": "{0:.2f}".format(prediction.bounding_box.height) } x = json.dumps(x) js_res[prediction.tag_name].append(x) res_batch[name] = js_res return res_batch
def main(): from dotenv import load_dotenv try: # Get Configuration Settings load_dotenv() prediction_endpoint = os.getenv('PredictionEndpoint') prediction_key = os.getenv('PredictionKey') project_id = os.getenv('ProjectID') model_name = os.getenv('ModelName') # Authenticate a client for the training API credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) prediction_client = CustomVisionPredictionClient( endpoint=prediction_endpoint, credentials=credentials) # Classify test images for image in os.listdir('test-images'): image_data = open(os.path.join('test-images', image), "rb").read() results = prediction_client.classify_image(project_id, model_name, image_data) # Loop over each label prediction and print any with probability > 50% for prediction in results.predictions: if prediction.probability > 0.5: print( image, ': {} ({:.0%})'.format(prediction.tag_name, prediction.probability)) except Exception as ex: print(ex)
def main(): """ Image classification """ args = parse_args() config = json.load(open(args.config, "r")) # Get the predictor prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": config["prediction_key"]} ) predictor = CustomVisionPredictionClient(config["ENDPOINT"], prediction_credentials) # ====================================================================================== # Open the sample image and get back the prediction results. project_id = get_project_id(config) with open(args.image, "rb") as image_contents: results = predictor.classify_image( project_id, config["publish_iteration_name"], image_contents.read(), ) # Display the results. for prediction in results.predictions: print( "{0}: {1:.2f}%".format( prediction.tag_name, prediction.probability * 100 ) )
def success(): image = request.args.get('name', None) ENDPOINT = "https://southcentralus.api.cognitive.microsoft.com/" prediction_key = "4c99a663c6984df6b912025e2c7e1dee" my_project_id = "c9f9158e-e82d-4541-926a-15699c59a4b4" publish_iteration_name = "Iteration3" test_data = urlopen(image).read() prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) predictor = CustomVisionPredictionClient(ENDPOINT, prediction_credentials) results = predictor.detect_image(project_id=my_project_id, published_name=publish_iteration_name, image_data=test_data) first_value = 0 maximum = 0 print(first_value) for prediction in results.predictions: next_value = int(prediction.probability * 100) if maximum <= next_value: maximum = next_value tag = prediction.tag_name print(int(prediction.probability * 100)) print(maximum) print(tag) print( "\t" + prediction.tag_name + ": {0:.2f}% bbox.left = {1:.2f}, bbox.top = {2:.2f}, bbox.width = {3:.2f}, bbox.height = {4:.2f}" .format(prediction.probability * 100, prediction.bounding_box.left, prediction.bounding_box.top, prediction.bounding_box.width, prediction.bounding_box.height)) return tag
def azure_request(img_by): project_ID = "xxx" iteration_name = "xxx" key = "xxx" endpointurl = "xxx" prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": key} ) predictor = CustomVisionPredictionClient( endpointurl, prediction_credentials ) results = predictor.classify_image( project_ID, iteration_name, img_by ) predict = {} for prediction in results.predictions: predict[prediction.tag_name] = prediction.probability return predict # 予測を辞書で返却
def resultado(request): font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 0.7 fontColor = (0,0,255) lineType = 2 name=request.GET["namefile"] credentials = ApiKeyCredentials(in_headers={"Prediction-key": "<Prediction Key Aquí>"}) predictor = CustomVisionPredictionClient("<Zona regional aqui>", credentials) blob = BlobClient.from_connection_string(conn_str=connection_string, container_name="images", blob_name=f"{name} training.png") url = request.GET["link"] urllib.request.urlretrieve(url, "python.png") imagen=cv2.imread("python.png") height, width, channels = imagen.shape Resultado = predictor.detect_image_url("<Prediction Key>", "<Iteration>", url) for prediction in Resultado.predictions: if prediction.probability > 0.4: bbox = prediction.bounding_box tag = prediction.tag_name probabilidad= int(prediction.probability * 100) result_image = cv2.rectangle(imagen, (int(bbox.left * width), int(bbox.top * height)), (int((bbox.left + bbox.width) * width), int((bbox.top + bbox.height) * height)), (0, 255, 0), 3) bottomLeftCornerOfText = (int(bbox.left*width),int(((bbox.top*height)+(bbox.height*height)))) cv2.putText(result_image,str(probabilidad)+"% "+tag, bottomLeftCornerOfText, font, fontScale, fontColor, lineType) cv2.imwrite('result.png', result_image) with open("result.png","rb") as data: blob.upload_blob(data) return render(request,"resultado.html",{"imagen":blob.url,"namefile":name})
def detect_weight_region(image): # top_left_corner = (21,120) # bottom_right_corner = (217, 210) # cv2.imshow("image",image) image_shape = image.shape print(image_shape) credentials = ApiKeyCredentials(in_headers = {"Prediction-Key":"bf595a2cb1854d988a1f9d26834cd4e2"}) predictor = CustomVisionPredictionClient("https://pankaj.cognitiveservices.azure.com/", credentials) cv2.imwrite('detect_weight_region.png', image) digit = "" with open("detect_weight_region.png", mode ='rb') as captured_image: # print("load digit image... and predict ") results = predictor.detect_image("de960dda-1a51-444e-9fe9-84f8fbc4eff1", "Iteration2", captured_image) maxm_percentage = 0.0 ans = [] for prediction in results.predictions: if(prediction.probability > maxm_percentage): maxm_percentage = prediction.probability ans = [image_shape[0]*prediction.bounding_box.left, image_shape[1]*prediction.bounding_box.top, image_shape[0]*prediction.bounding_box.width, image_shape[1]*prediction.bounding_box.height] print("\t" + prediction.tag_name + ": {0:.2f}% bbox.left = {1:.2f}, bbox.top = {2:.2f}, bbox.width = {3:.2f}, bbox.height = {4:.2f}".format(prediction.probability * 100, prediction.bounding_box.left, prediction.bounding_box.top, prediction.bounding_box.width, prediction.bounding_box.height)) # for prediction in results.predictions: # if(prediction.probability> maxm_percentage): # digit = prediction.tag_name # maxm_percentage = prediction.probability return ans
def main(): from dotenv import load_dotenv global training_client global custom_vision_project try: # Get Configuration Settings load_dotenv() training_endpoint = os.getenv('TrainingEndpoint') training_key = os.getenv('TrainingKey') project_id = os.getenv('ProjectID') # Authenticate a client for the training API credentials = ApiKeyCredentials( in_headers={"Training-key": training_key}) training_client = CustomVisionTrainingClient(training_endpoint, credentials) # Get the Custom Vision project custom_vision_project = training_client.get_project(project_id) # Upload and tag images Upload_Images('more-training-images') # Train the model Train_Model() except Exception as ex: print(ex)
def __init__(self) -> None: """ Reads configuration file Initializes connection to Azure Custom Vision predictor and training resources. Parameters: blob_service_client: Azure Blob Service interaction client Returns: None """ self.ENDPOINT = Keys.get("CV_ENDPOINT") self.project_id = Keys.get("CV_PROJECT_ID") self.prediction_key = Keys.get("CV_PREDICTION_KEY") self.training_key = Keys.get("CV_TRAINING_KEY") self.base_img_url = Keys.get("BASE_BLOB_URL") self.prediction_resource_id = Keys.get("CV_PREDICTION_RESOURCE_ID") self.prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": self.prediction_key}) self.predictor = CustomVisionPredictionClient( self.ENDPOINT, self.prediction_credentials) self.training_credentials = ApiKeyCredentials( in_headers={"Training-key": self.training_key}) self.trainer = CustomVisionTrainingClient(self.ENDPOINT, self.training_credentials) connect_str = Keys.get("BLOB_CONNECTION_STRING") self.blob_service_client = BlobServiceClient.from_connection_string( connect_str) try: # get all project iterations iterations = self.trainer.get_iterations(self.project_id) # find published iterations puplished_iterations = [ iteration for iteration in iterations if iteration.publish_name != None ] # get the latest published iteration puplished_iterations.sort(key=lambda i: i.created) self.iteration_name = puplished_iterations[-1].publish_name with api.app.app_context(): models.update_iteration_name(self.iteration_name) except Exception as e: logging.info(e) self.iteration_name = "iteration1"
def call_custom_vision(image_url): prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": custom_vision_prediction_key}) predictor = CustomVisionPredictionClient(custom_vision_endpoint, prediction_credentials) results = predictor.detect_image_url(project_id, publish_iteration_name, image_url) return results
def __init__(self, prediction_key, endpoint, iteration_id, iteration_name): """Makes a call to custom vision api and use trained model to detect people """ credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) self._predictor = CustomVisionPredictionClient(endpoint, credentials) self._iteration_id = iteration_id self._iteration_name = iteration_name
def process_image(): file = request.files['file'] file.save("predict") # Read the image via file.stream #img = Image.open(file.stream) #test_img_file = os.path.join('data', 'object-detection', 'ofr.jpg') test_img_file = 'predict' test_img = Image.open(test_img_file) imgbin = open(test_img_file,mode="rb") test_img_h, test_img_w, test_img_ch = np.array(test_img).shape print('Ready to predict using model {} in project {}'.format(model_name, project_id)) # Get a prediction client for the object detection model credentials = ApiKeyCredentials(in_headers={"Prediction-key": cv_key}) predictor = CustomVisionPredictionClient(endpoint=cv_endpoint, credentials=credentials) print('Detecting objects in {} using model {} in project {}...'.format(test_img_file, model_name, project_id)) # Detect objects in the test image with open(test_img_file, mode="rb") as test_data: results = predictor.detect_image(project_id, model_name, test_data) # Create a figure to display the results fig = plt.figure(figsize=(10, 12)) #fig = plt.figure(figsize=(test_img_h,test_img_w)) plt.axis('off') # Display the image with boxes around each detected object draw = ImageDraw.Draw(test_img) lineWidth = int(np.array(test_img).shape[1]/100) object_colors = { "bebida": "lightgreen", "calavera_completa": "yellow", "calavera_de_dulce": "yellow", "cempasuchil": "orange", "comida": "blue", "cruz": "gold", "fruta": "magenta", "pan_de_muerto": "darkcyan", "papel_picado": "red", "retrato": "cyan" } found = [] for prediction in results.predictions: color = 'white' # default for 'other' object tags if (prediction.probability*100) > 50: if prediction.tag_name in object_colors: color = object_colors[prediction.tag_name] found.append(prediction.tag_name) left = prediction.bounding_box.left * test_img_w top = prediction.bounding_box.top * test_img_h height = prediction.bounding_box.height * test_img_h width = prediction.bounding_box.width * test_img_w points = ((left,top), (left+width,top), (left+width,top+height), (left,top+height),(left,top)) draw.line(points, fill=color, width=lineWidth) #plt.annotate(prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100),(left,top), backgroundcolor=color) plt.annotate(prediction.tag_name,(left,top), backgroundcolor=color) test_img.save("./static/Imagenes/out.jpg") return jsonify(found)
def get_trainer_obj(self) -> CustomVisionTrainingClient: """get_trainer_obj. Returns: CustomVisionTrainingClient: """ credentials = ApiKeyCredentials(in_headers={"Training-key": self.training_key}) return CustomVisionTrainingClient( credentials=credentials, endpoint=self.endpoint )
def get_project_id(config): """ Get project ID list """ credentials = ApiKeyCredentials( in_headers={"Training-key": config["training_key"]}) trainer = CustomVisionTrainingClient(config["ENDPOINT"], credentials) project_id = next(proj.id for proj in trainer.get_projects() if proj.name == config["project_name"]) return project_id
def __init__(self): PREDICTION_KEY = os.environ["COGNITIVE_CUSTOM_VISION_PREDICTOR_KEY"] ENDPOINT = os.environ["COGNITIVE_CUSTOM_VISION_PREDICTOR_ENDPOINT"] self.PROJECT_ID = os.environ["COGNITIVE_CUSTOM_VISION_PROJECT_ID"] self.ITERATION = os.environ[ "COGNITIVE_CUSTOM_VISION_PROJECT_ITERATION"] prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": PREDICTION_KEY}) super(MaskClassifier, self).__init__(ENDPOINT, prediction_credentials)
def main(): """ Training for object detection with Azure Custom Vision """ args = parse_args() config = json.load(open(args.config, "r")) credentials = ApiKeyCredentials(in_headers={"Training-key": config["training_key"]}) trainer = CustomVisionTrainingClient(config["ENDPOINT"], credentials) print("Creating project...") # Find the object detection domain obj_detection_domain = next( domain for domain in trainer.get_domains() if domain.type == "ObjectDetection" and domain.name == "General" ) project = trainer.create_project( config["project_name"], domain_id=obj_detection_domain.id ) # ====================================================================================== print("Adding images...") image_folder = config["image_folder"] annotations = json.load(open("annotation.json", "r")) tagged_images_with_regions = [] for label in annotations.keys(): tagged_images_with_regions += add_image( trainer, label, project.id, annotations[label], image_folder ) upload_result = trainer.create_images_from_files( project.id, ImageFileCreateBatch(images=tagged_images_with_regions) ) if not upload_result.is_batch_successful: print("Image batch upload failed.") for image in upload_result.images: print("Image status: ", image.status) # ====================================================================================== print("Training...") publish_iteration_name = config["publish_iteration_name"] prediction_resource_id = config["prediction_resource_id"] iteration = trainer.train_project(project.id) while iteration.status != "Completed": iteration = trainer.get_iteration(project.id, iteration.id) print("Training status: " + iteration.status) time.sleep(1) # The iteration is now trained. Publish it to the project endpoint trainer.publish_iteration( project.id, iteration.id, publish_iteration_name, prediction_resource_id ) print("Done!")
def getPrediction(ENDPOINT, publish_iteration_name, prediction_key, prediction_resource_id, img, training_key, project_name): # Now there is a trained endpoint that can be used to make a prediction prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) training_credentials = ApiKeyCredentials( in_headers={"Training-key": training_key}) predictor = CustomVisionPredictionClient(ENDPOINT, prediction_credentials) trainer = CustomVisionTrainingClient(ENDPOINT, training_credentials) projects = trainer.get_projects() #Retrieve the object dection project and its tags #Current assumes one tag for p in projects: if p.name == project_name: project = trainer.get_project(p.id) tags = trainer.get_tags(project.id) print('Project Found') # Open the sample image and get back the prediction results. results = predictor.detect_image(project.id, publish_iteration_name, img) drawBounds(img, results.predictions) # Display the results. js_res = defaultdict(list) for prediction in results.predictions: print(prediction) x = { "confidence": "{0:.2f}%".format(prediction.probability * 100), "bbox_left": "{0:.2f}".format(prediction.bounding_box.left), "bbox_right": "{0:.2f}".format(prediction.bounding_box.top), "bbox_width": "{0:.2f}".format(prediction.bounding_box.width), "bbox_height": "{0:.2f}".format(prediction.bounding_box.height) } js_res[prediction.tag_name].append(x) return js_res
def main(): from dotenv import load_dotenv try: # Get Configuration Settings load_dotenv() prediction_endpoint = os.getenv('PredictionEndpoint') prediction_key = os.getenv('PredictionKey') project_id = os.getenv('ProjectID') model_name = os.getenv('ModelName') # Authenticate a client for the training API credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key}) prediction_client = CustomVisionPredictionClient(endpoint=prediction_endpoint, credentials=credentials) # Load image and get height, width and channels image_file = 'produce.jpg' print('Detecting objects in', image_file) image = Image.open(image_file) h, w, ch = np.array(image).shape # Detect objects in the test image with open(image_file, mode="rb") as image_data: results = prediction_client.detect_image(project_id, model_name, image_data) # Create a figure for the results fig = plt.figure(figsize=(8, 8)) plt.axis('off') # Display the image with boxes around each detected object draw = ImageDraw.Draw(image) lineWidth = int(w/100) color = 'magenta' for prediction in results.predictions: # Only show objects with a > 50% probability if (prediction.probability*100) > 50: # Box coordinates and dimensions are proportional - convert to absolutes left = prediction.bounding_box.left * w top = prediction.bounding_box.top * h height = prediction.bounding_box.height * h width = prediction.bounding_box.width * w # Draw the box points = ((left,top), (left+width,top), (left+width,top+height), (left,top+height),(left,top)) draw.line(points, fill=color, width=lineWidth) # Add the tag name and probability plt.annotate(prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100),(left,top), backgroundcolor=color) plt.imshow(image) outputfile = 'output.jpg' fig.savefig(outputfile) print('Results saved in ', outputfile) except Exception as ex: print(ex)
def main(): """ Object Detection with Azure Custom Vision """ args = parse_args() config = json.load(open(args.config, "r")) # Get the predictor prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": config["prediction_key"]}) predictor = CustomVisionPredictionClient(config["ENDPOINT"], prediction_credentials) # ====================================================================================== # Open the sample image and get back the prediction results. project_id = get_project_id(config) with open(args.image, "rb") as test_data: results = predictor.detect_image( project_id, config["publish_iteration_name"], test_data, ) # ====================================================================================== # Draw the bounding boxes on the image img = Image.open(args.image) draw = ImageDraw.Draw(img) font = ImageFont.truetype("../static/TaipeiSansTCBeta-Regular.ttf", size=int(5e-2 * img.size[1])) for prediction in results.predictions: if prediction.probability > 0.5: bbox = prediction.bounding_box.as_dict() left = bbox['left'] * img.size[0] top = bbox['top'] * img.size[1] right = left + bbox['width'] * img.size[0] bot = top + bbox['height'] * img.size[1] draw.rectangle([left, top, right, bot], outline=(255, 0, 0), width=3) draw.text( [left, abs(top - 5e-2 * img.size[1])], "{0} {1:0.2f}".format(prediction.tag_name, prediction.probability * 100), fill=(255, 0, 0), font=font, ) img.save("output.png") print("Done!") print("Please check ouptut.png")
def __init__(self): # Load credentials from environment # Authenticate the training client credentials = ApiKeyCredentials( in_headers={"Training-key": TRAINING_KEY}) trainer = CustomVisionTrainingClient(TRAINING_ENDPOINT, credentials) # Authenticate the prediction client prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": PREDICTION_KEY}) self.predictor = CustomVisionPredictionClient(PREDICTION_ENDPOINT, prediction_credentials) project_name = "car_seal_train_and_validation" self.publish_iteration_name = "Iteration3" self.max_byte_size = 4000000 projects = trainer.get_projects() project_id = next((p.id for p in projects if p.name == project_name), None) print("Connecting to existing project...") self.project = trainer.get_project(project_id)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') try: data = req.get_json() farmid, runid = data['farmid'], data['runid'] feedback_list = data['feedback'] #Decide on the correct split for feedback in feedback_list: feedback["split"] = "train" if random.random() < 0.5 else "dev" #Get Project ID and CustomVision Trainer logging.info("Get Project with Project ID : " + CVTrainConstants.PROJECT_ID) credentials = ApiKeyCredentials( in_headers={"Training-key": CVTrainConstants.TRAINING_KEY}) trainer = CustomVisionTrainingClient(CVTrainConstants.ENDPOINT, credentials) #Get list of tags in the current project tag_dict = {} for tag in trainer.get_tags( CVTrainConstants.PROJECT_ID): ##Can modify dictionary later tag_dict[tag.name] = tag.id train_image_list = add_train_dev_images(farmid, runid, feedback_list, tag_dict) #train_image_list = add_train_dev_images("1", "2", [{"grid_id": "3", "label": "Charlock", "split": "dev"}, \ #{"grid_id": "7", "label": "Fat Hen", "split": "train"}], tag_dict) #Upload to Custom Vision with new tags from train if len(train_image_list) != 0: # IF not empty upload_result = trainer.create_images_from_urls( CVTrainConstants.PROJECT_ID, images=train_image_list) if not upload_result.is_batch_successful: logging.error("Image batch upload failed.") else: logging.info("Image batch upload Success") best_iteration(trainer) except Exception as e: logging.error( "Exception while trying to get data from HTTP Request: " + str(e)) return func.HttpResponse(f"Failure !") return func.HttpResponse(f"Trained Sucessfully")
def digit_number(image): credentials = ApiKeyCredentials(in_headers = {"Prediction-Key":"bf595a2cb1854d988a1f9d26834cd4e2"}) predictor = CustomVisionPredictionClient("https://pankaj.cognitiveservices.azure.com/", credentials) cv2.imwrite('capture.png', image) digit = "" with open("capture.png", mode ='rb') as captured_image: # print("load digit image... and predict ") results = predictor.classify_image("c22b7174-dd80-457b-829e-4d05496aee33", "Iteration3", captured_image) maxm_percentage = 0.0 for prediction in results.predictions: if(prediction.probability> maxm_percentage): digit = prediction.tag_name maxm_percentage = prediction.probability # print("\t" + prediction.tag_name +": {0:.2f}%".format(prediction.probability * 100)) return digit
def prediction(): #Prise de la photo #Lancez les fonctions concernant la prise de photo #Sauvegarde de l'image # Now there is a trained endpoint that can be used to make a prediction prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": prediction_key}) predictor = CustomVisionPredictionClient(ENDPOINT, prediction_credentials) with open(base_image_url + "/triof/camera/couvert-plastique.jpg", "rb") as image_contents: results = predictor.classify_image(project_id, publish_iteration_name, image_contents.read()) # Display the results. resultat = [] for prediction in results.predictions: print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100)) resultat.append((str(prediction.tag_name), str(round(prediction.probability * 100, 2)))) #resultat_json = jsonify({'reponse': resultat}) #Define variables bouteille_name = resultat[0][0] bouteille_pred = resultat[0][1] gobelet_name = resultat[1][0] gobelet_pred = resultat[1][1] couverts_name = resultat[2][0] couverts_pred = resultat[2][1] #Define the context context = { "bouteille_name": bouteille_name, "bouteille_pred": bouteille_pred, "gobelet_name": gobelet_name, "gobelet_pred": gobelet_pred, "couverts_name": couverts_name, "couverts_pred": couverts_pred } return render_template('pred.html', **context)
def test_apikey_auth(self): auth = ApiKeyCredentials(in_headers={'testheader': 'testheadervalue'}) session = auth.signed_session() prep_req = session.prepare_request(self.request) self.assertDictContainsSubset({'testheader': 'testheadervalue'}, prep_req.headers) auth = ApiKeyCredentials(in_query={'testquery': 'testparamvalue'}) session = auth.signed_session() prep_req = session.prepare_request(self.request) assert "testquery=testparamvalue" in prep_req.path_url
def customvision_predict(blob_url): prediction_credentials = ApiKeyCredentials( in_headers={ "Prediction-key": CustomVisionPredConstants.PREDICTION_KEY }) predictor = CustomVisionPredictionClient( CustomVisionPredConstants.ENDPOINT, prediction_credentials) results = predictor.classify_image_url( CustomVisionPredConstants.PROJECT_ID, CustomVisionPredConstants.ITERATION_NAME, blob_url) prediction_dict = {} for prediction in results.predictions: prediction_dict[prediction.tag_name] = round( prediction.probability * 100, 2) return prediction_dict
def callAPI(uploadFile): # 予測用インスタンスの作成 credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key}) predictor = CustomVisionPredictionClient(ENDPOINT, credentials) with open(uploadFile, mode='rb') as f: # 予測実行 results = predictor.classify_image(projectID, publish_iteration_name, f.read()) result = [] for prediction in results.predictions: if len(get_fish_data(prediction.tag_name)) != 0: # 確率がしきい値より大きいものを採用する if prediction.probability * 100 > threshold: result.append(get_fish_data(prediction.tag_name)) return result
def forecast(meter): from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient from msrest.authentication import ApiKeyCredentials # Now there is a trained endpoint that can be used to make a prediction credentials = ApiKeyCredentials( in_headers={"Prediction-key": "5cebf412b5504687bbbe08255e810e88"}) predictor = CustomVisionPredictionClient( endpoint="https://uksouth.api.cognitive.microsoft.com/", credentials=credentials) with open(meter, mode="rb") as image_contents: results = predictor.detect_image( "b667b9c2-2604-4f86-be8e-818852441327", "Iteration8", image_contents) # Display the results. #for prediction in results.predictions: # print("\t" + prediction.tag_name + ": {0:.2f}% bbox.left = {1:.2f}, bbox.top = {2:.2f}, bbox.width = {3:.2f}, bbox.height = {4:.2f}".format(prediction.probability * 100, prediction.bounding_box.left, prediction.bounding_box.top, prediction.bounding_box.width, prediction.bounding_box.height)) return results.predictions
def process_custom_vision(custom_vision_url): if(custom_vision_url is not ''): # Prediction API prediction_credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key}) predictor = CustomVisionPredictionClient(custom_vision_endpoint, prediction_credentials) # Create a placeholder for messages messages = [] # Create a random number filename for images random_number_filename = random.randint(1, 1000) random_number_filename = str(random_number_filename) print("Random number type: ", type(random_number_filename)) # Save image to static folder test_save_image = custom_vision_render_image_url(random_number_filename, custom_vision_url) saved_image_file = "/static/" + random_number_filename + ".png" # Add your path to the static folder images_folder = '' with open(images_folder + random_number_filename + ".png", "rb") as image_contents: results = predictor.classify_image( project_id, publish_iteration_name, image_contents.read()) # Display the results. for prediction in results.predictions: print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100)) messages.append(("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100))) print("MESSAGES", messages) return messages else: messages = ['Please enter an image URL'] return messages