# AUTOGENERATED! DO NOT EDIT! File to edit: telecom_object_detection.ipynb. # %% auto 0 __all__ = ['title', 'css', 'urls', 'imgs', 'img_samples', 'fig2img', 'custom_vision_detect_objects', 'set_example_url', 'set_example_image', 'detect_objects'] # %% telecom_object_detection.ipynb 2 import gradio as gr import numpy as np import os import io import requests from pathlib import Path # %% telecom_object_detection.ipynb 6 from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient from msrest.authentication import ApiKeyCredentials from matplotlib import pyplot as plt from PIL import Image, ImageDraw, ImageFont from dotenv import load_dotenv # %% telecom_object_detection.ipynb 11 def fig2img(fig): buf = io.BytesIO() fig.savefig(buf) buf.seek(0) img = Image.open(buf) return img def custom_vision_detect_objects(image_file: Path): dpi = 100 # 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=(w/dpi, h/dpi)) plt.axis('off') # Display the image with boxes around each detected object draw = ImageDraw.Draw(image) lineWidth = int(w/800) color = 'cyan' 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.annotate( prediction.tag_name + ": {0:.0f}%".format(prediction.probability * 100), (left, top-1.372*h/dpi), backgroundcolor=color, fontsize=max(w/dpi, h/dpi), fontfamily='monospace' ) plt.imshow(image) plt.tight_layout(pad=0) return fig2img(fig) outputfile = 'output.jpg' fig.savefig(outputfile) print('Resulabsts saved in ', outputfile) # %% telecom_object_detection.ipynb 15 title = """