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 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 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 find_seal(image_path, angle): predictor = CustomVisionPredictionClient(prediction_key, endpoint=endpoint) project_id = None if angle == 'wet-head-right': project_id = config.HEAD_RIGHT if angle == 'wet-head-left': project_id = config.HEAD_LEFT if angle == 'bottling-left': project_id = config.BOTTLING_LEFT if angle == 'bottling-straight': project_id = config.BOTTLING_STRAIGHT if angle == 'bottling-right': project_id = config.BOTTLING_RIGHT # Open the image and get back the prediction results. with open(image_path, mode="rb") as image_contents: results = predictor.classify_image(project_id, iteration_name, image_contents.read()) image_predictions = {} for prediction in results.predictions: image_predictions[prediction.tag_name] = prediction.probability print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100)) return image_predictions
def predict_face(image: list): """ permet de predire lidentité de l'etudiant """ # Byte image_contents = cv2.imencode('.jpg', image)[1].tostring() # Now there is a trained endpoint that can be used to make a prediction predictor = CustomVisionPredictionClient(config.prediction_key, endpoint=config.ENDPOINT) #with open(base_image_url + "images/Test/test_image.jpg", "rb") as image_contents: results = predictor.classify_image(config.projet_id, config.publish_iteration_name, image_contents) # hight probability prediction = results.predictions[0] """for prediction in results.predictions: if prediction.probability > prob: tag_name = prediction.tag_name prob = prediction.probability print ("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100)) """ return prediction
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 find_seal(image_path): predictor = CustomVisionPredictionClient(prediction_key, endpoint=endpoint) # Open the image and get back the prediction results. with open(image_path, mode="rb") as image_contents: results = predictor.classify_image(project_id, iteration_name, image_contents.read()) return results
def predictWithID(self, database, modelID, inputDataIDs, onFinished): # load model record session = database.cursor() session.execute( "SELECT remote_id FROM " + self._datatableName + " WHERE id = %s", (modelID, )) result = session.fetchone() session.close() if result: projectID = result[0] predictOK = True resultMap = {} if len(inputDataIDs) > 0: try: # Now there is a trained endpoint that can be used to make a prediction trainer = CustomVisionTrainingClient( self._trainingKey, endpoint=self._endPoint) predictor = CustomVisionPredictionClient( self._predictionKey, endpoint=self._endPoint) project = trainer.get_project(projectID) # load photos for photoID in inputDataIDs: image, _, err = self._serverAPI.getResource( database, photoID) if err is None: isOK, encodedImage = cv2.imencode('.png', image) predictResponse = predictor.classify_image( project.id, projectID, encodedImage) predictResult = predictResponse.predictions if len(predictResult) > 0: resultMap[photoID] = { "CLASS": predictResult[0].tag_name, "SCORE": predictResult[0].probability } except Exception as err: predictOK = False resultMap = {} print("ERROR (", self._datatableName, ") Model", modelID, "failed to predict: " + str(err)) #raise err onFinished({"ISOK": predictOK, "RESULT": resultMap}) else: print("ERROR (", self._datatableName, ") Model", modelID, "failed to predict, model record not found by plugin.") onFinished({"ISOK": False})
def predict_project(subscription_key): predictor = CustomVisionPredictionClient( subscription_key, "https://westeurope.api.cognitive.microsoft.com") # Find or train a new project to use for prediction. project = find_or_train_project() with open(os.path.join(IMAGES_FOLDER, "Test", "test_image.jpg"), mode="rb") as test_data: results = predictor.classify_image(project.id, PUBLISH_ITERATION_NAME, test_data.read()) # Display the results. for prediction in results.predictions: print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100))
def callAPI(uploadFile): predictor = CustomVisionPredictionClient(prediction_key, endpoint=base_url) 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 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 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 getListOfPredictions(frameDir): # Now there is a trained endpoint that can be used to make a prediction predictor = CustomVisionPredictionClient(prediction_key, endpoint) l = [] # "images/frame73.jpg" with open(frameDir, "rb") as image_contents: results = predictor.classify_image(projectID, publish_iteration_name, image_contents.read()) # Display the results. for prediction in results.predictions: tag = "\t" + prediction.tag_name + ":{0:.2f}%".format( prediction.probability * 100) l.append(tag) print(tag) li = parse(l) return li
def predict_class(): """ To make prediction of an image """ print("Predicting the bird class...") # Now there is a trained endpoint that can be used to make a prediction predictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT) fig = plt.figure(figsize=(12, 8)) with plt.style.context('seaborn-whitegrid'): ax2 = fig.add_subplot(122) ax1 = fig.add_subplot(121) plt.rcParams.update({'font.size': 16}) img_file = sg.PopupGetFile('Please enter a file name') print("Image file:", img_file) img = Image.open(img_file).resize((499, 499), Image.LANCZOS) ax1.imshow(img, cmap='gray', interpolation='bicubic') ax1.set_xticks([]), plt.yticks([]) # to hide tick values on X and Y axis latest_iter_id, latest_iter_name = get_latest_iter() print("Prediction done on the latest iteration: %s (id:%s)" % (latest_iter_name, latest_iter_id)) with open(img_file, "rb") as image_contents: #local images results = predictor.classify_image(project_id, latest_iter_name, image_contents.read()) #azure api #display the top 5 probabilities list_tag, list_prob = [], [] for i, prediction in zip(range(5), results.predictions): if i < 5: list_tag.append(prediction.tag_name) list_prob.append(round(prediction.probability, 2)) #print(list_tag[i], list_prob[i]) else: break cplt.plot_bar_prob(list_tag, list_prob, 'Bird classification', 'Top 5', ax2) plt.show() return None
def classify(image_path): # Replace with a valid key prediction_key = "c3741dd758584195b3bcd4331c4ba6c0" #prediction_resource_id = "/subscriptions/bad6784e-798e-4bbc-89cf-cb5149375471/resourceGroups/Ecolab(Group)/providers/Microsoft.CognitiveServices/accounts/Ecolab-Prediction" training_key = 'd898f79af8f84520994849cf82d4a6be' ENDPOINT = "https://ecolab-prediction.cognitiveservices.azure.com/" publish_iteration_name = "Ecolab3" test_image = image_path trainer = CustomVisionTrainingClient(training_key, endpoint=ENDPOINT) predictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT) project = trainer.get_projects()[0] # Now there is a trained endpoint that can be used to make a prediction with open(test_image, "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
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
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 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" # TODO: Add the folder you will download to image to images_folder images_folder = '' # Create a placeholder for messages messages = [] with open(images_folder + random_number_filename + ".png", "rb") as image_contents: results = predictor.classify_image(project_id, publish_iteration_name, image_contents.read()) """ TODO: 1. Loop through results.predictions and 2. Append prediction.tag_name and prediction.probability to messages 3. Return messages. """ return messages else: messages = ['Please enter an image URL'] return messages
class CustomVisionAPI(object): def __init__(self, training_key='', prediction_key='', prediction_resource_id='', project_id=''): self.ENDPOINT = "https://southcentralus.api.cognitive.microsoft.com" self.training_key = training_key #"<Replace with training key>" self.prediction_key = prediction_key #"<Replace with prediction key>" self.prediction_resource_id = prediction_resource_id #"<Replace with prediction ressource id>" self.publish_iteration_name = "Iteration1" self.trainer = CustomVisionTrainingClient(training_key, endpoint=self.ENDPOINT) self.predictor = CustomVisionPredictionClient(prediction_key, endpoint=self.ENDPOINT) self.project = self.trainer.get_project( project_id) #'<Replace with project id>' def classify_photo(self, url): with open(url, "rb") as image_contents: #print(url) results = self.predictor.classify_image( self.project.id, self.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)) return results.predictions[0].tag_name # Exemple #CustomVisionAPI().classify_photo(r'C:\Projet\PhotoClassifier\data\Photos\animal\IMG_20180510_112719_1.jpg')
def main(): while (True): # time.sleep(5) print('Taking Picture') camera_port = 0 ramp_frames = 30 camera = cv2.VideoCapture(camera_port) def get_image(): retval, im = camera.read() return im for i in range(ramp_frames): temp = camera.read() camera_capture = get_image() filename = "webcam-picture.png" cv2.imwrite(filename, camera_capture) del (camera) PREDICTION_KEY = os.environ.get('VISION_PREDICTION_KEY') ENDPOINT = os.environ.get('VISION_ENDPOINT') PROJECT_ID = os.environ.get('VISION_PROJECT_ID') predictor = CustomVisionPredictionClient(PREDICTION_KEY, endpoint=ENDPOINT) publish_iteration_name = os.environ.get( 'VISION_PUBLISHED_ITERATION_NAME') # Open the sample image and get back the prediction results. with open("webcam-picture.png", mode="rb") as test_data: results = predictor.classify_image(PROJECT_ID, publish_iteration_name, test_data) # Display the results. for prediction in results.predictions: print(str(prediction)) time.sleep(25)
def index(): if request.method == "POST": if request.form["submit"] =='add': f = request.files['file'] print(f.filename) f.save(secure_filename(f.filename)) ENDPOINT = "https://eastus2.api.cognitive.microsoft.com/" training_key = "2d973f1217ca449b804c689d9d02b635" prediction_key = "2d973f1217ca449b804c689d9d02b635" prediction_resource_id = "/subscriptions/710cff9e-6696-4d9f-944d-eac6dcff9965/resourceGroups/RAHULGARG/providers/Microsoft.CognitiveServices/accounts/RAHULGARG" publish_iteration_name = "classifyModel" trainer = CustomVisionTrainingClient(training_key, endpoint=ENDPOINT) # Create a new project print ("Creating project...") #project = trainer.create_project("incubate") # Replace with a valid key prediction_key = "2d973f1217ca449b804c689d9d02b635" predictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT) base_image_url = f.filename #print(project.id) with open(base_image_url, "rb") as image_contents: results = predictor.classify_image( "285fbf98-b8ac-4dcf-8f7a-d67358836965", "Iteration2", image_contents.read()) # Display the results. ls=[] for prediction in results.predictions: ls.append({prediction.tag_name : ": {0:.2f}%".format(prediction.probability * 100)}) return render_template('pred.html',t=ls) return render_template('index.html')
def check_results(): # Get the JSON passed to the request and extract the image body = request.get_json() image_bytes = base64.b64decode(body['image_base64'].split(',')[1]) # image = io.BytesIO(image_bytes) predictor = CustomVisionPredictionClient(PREDICTION_KEY, endpoint=ENDPOINT) results = predictor.classify_image(PROJECT_ID, PUBLISH_ITERATION_NAME, image_bytes) predictions = { prediction.tag_name: prediction.probability for prediction in results.predictions } predicted = max(predictions.keys(), key=(lambda k: predictions[k])) return jsonify({ 'predicted': predicted, 'probability': predictions[predicted], 'opponent': LABELS[random.randint(0, 4)] })
def pick_type(): close_waste_slot() show = session.get('show') prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": "***keycode1***"}) predictor = CustomVisionPredictionClient( "https://***.cognitiveservices.azure.com/", prediction_credentials) with open("./camera/" + show, "rb") as image_contents: results = predictor.classify_image("**keycode2***", "Iteration2", image_contents.read()) # Display the results. for prediction in results.predictions: print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100)) categ = prediction.tag_name proba = prediction.probability * 100 break data = {'image': show, 'categorie': categ, 'probabilite': proba} return render_template('type.html', data=data)
# 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!") # </snippet_train> # <snippet_publish> # 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!") # </snippet_publish> # <snippet_test> # 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_location + "images/Test/test_image.jpg", "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)) # </snippet_test>
firebase.put('/item',"item","no") # initial classification print("Please press button to continue") # Our print for instructing new users channel = GPIO.wait_for_edge(ButtonPin,GPIO.FALLING) # Waiting for button to be pressed if channel == ButtonPin: print(channel) # #------------------------------take picture---------------------------------------- camera.start_preview() time.sleep(1) camera.capture('/home/pi/image-recognition.jpg') camera.stop_preview() # #-----------------------check the prediction in azure------------------------------ best_pred_label = '' best_pred_prob = 0 with open("/home/pi/image-recognition.jpg", "rb") as image_contents: # Classify image using your lastest training iteration results = predictor.classify_image("***Your-Iteration-ID***", "***Your-'Published-As'-Iteration***", image_contents.read()) # Display the results. for prediction in results.predictions: if prediction.probability * 100 > best_pred_prob: best_pred_prob = prediction.probability * 100 best_pred_label = prediction.tag_name print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100)) print(best_pred_label) print(best_pred_prob) # OPTIONAL - defaultly accept predictions with probability over a specific thrashold (i.e. 70) # We chose NOT to use this. # Labels should be identical to those defined your project's Azure CV's Classifier. #-----------------------check if prediction more then 70%---------------------------
from azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient from azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateBatch, ImageFileCreateEntry, Region from msrest.authentication import ApiKeyCredentials prediction_credentials = ApiKeyCredentials( in_headers={"Prediction-key": "***keycode1***"}) predictor = CustomVisionPredictionClient( "https://xxxx.cognitiveservices.azure.com/", prediction_credentials) with open("./camera/" + "100-gobelets-transparent.jpg", "rb") as image_contents: results = predictor.classify_image("***keycode2***", "Iteration2", image_contents.read()) # Display the results. for prediction in results.predictions: print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100))
# 傳入prediction-key及endpoint credentials = ApiKeyCredentials( in_headers={"Prediction-key": '8d30ba3f687644c582153ad00394cd9c'}) predictor = CustomVisionPredictionClient( endpoint='https://treasuretrain.cognitiveservices.azure.com/', credentials=credentials) # 設定project.id, publish_iteration_name, 圖片位置及名稱 PROJECT_ID = 'b4ed92c4-f345-49bf-a5bf-a691bf9d18d2' publish_iteration_name = 'Iteration4' imgFile = 'C:/Users/USER/Desktop/treasure507/picture-testing/f7.jpg' # 預測 with open(imgFile, 'rb') as image_contents: results = predictor.classify_image(PROJECT_ID, publish_iteration_name, image_contents.read()) # 顯示結果 def result(): for prediction in results.predictions: if prediction.tag_name == "玻璃": return ("a01") elif prediction.tag_name == "塑膠": return ("b01") elif prediction.tag_name == "紙容器": return ("c01") elif prediction.tag_name == "鐵鋁": return ("d01") else: return ("e01")
def post(): file = request.files['file'] loc = request.form['jsn'] loc = json.loads(loc) json_data = {"data": "open", "loc": ""} # Get predictor and project objects predictor = CustomVisionPredictionClient(prediction_key, endpoint=ENDPOINT) project = find_project() results = predictor.classify_image(project.id, "Iteration24", file.stream.read()) for prediction in results.predictions: print(prediction.tag_name) print(prediction.probability) if prediction.tag_name == CLOSED_EYES: if ((prediction.probability * 100) > 70): print("closed eyes") global count count += 1 if count == 3: count = 0 ##**** uncomment these if you want to use smartcar API # with open(os.path.join(app.root_path, 'access_token.json')) as json_file: # js = json.load(json_file) # refresh = js['refresh_token'] # acc = js['access_token'] # try: # req = smartcar.get_vehicle_ids(acc) # except smartcar.AuthenticationException: # code = client.exchange_refresh_token(refresh) # with open(os.path.join(app.root_path, 'access_token.json'), 'w') as json_file: # data = {"refresh_token": code["refresh_token"], # "access_token": code["access_token"]} # json.dump(data, json_file) # req = smartcar.get_vehicle_ids(code["access_token"]) # vld = req['vehicles'][0] # v = smartcar.Vehicle(vld, acc) # print(v.location()) json_data = { "data": "closed", "loc": loc } #str(v.location()['data'])} ##*** use below code instead of the one below it to use smartcar #message(vld, v.location()['data']) message(loc) os.system('afplay ./alert.mp3') print("hazard!") url = 'https://www.jsonstore.io/962b54063ad9a4019de7f1629eea83173b549ae39f2d064e1f9f724b35851731' headers = {'Content-Type': 'application/json'} requests.post(url, json=json_data, headers=headers) else: #print("opeeenn") json_data = {"data": "open", "loc": ""} url = 'https://www.jsonstore.io/962b54063ad9a4019de7f1629eea83173b549ae39f2d064e1f9f724b35851731' headers = {'Content-Type': 'application/json'} requests.post(url, json=json_data, headers=headers) # global count count = 0 return Response(json_data)
import cv2 from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient from msrest.authentication import ApiKeyCredentials # camera = cv2.VideoCapture(0) # camera.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) credentials = ApiKeyCredentials(in_headers = {"Prediction-Key":"bf595a2cb1854d988a1f9d26834cd4e2"}) predictor = CustomVisionPredictionClient("https://pankaj.cognitiveservices.azure.com/", credentials) with open("capture.png", mode ='rb') as captured_image: print("load image... and predict ") results = predictor.classify_image("c22b7174-dd80-457b-829e-4d05496aee33", "Iteration3", captured_image) # print(results) for prediction in results.predictions: print("\t" + prediction.tag_name +": {0:.2f}%".format(prediction.probability * 100)) print("all done")
#Now we prepare the prediction based on training model above #get list of URLs scraped from twitter with images to predict prediction_images = tweet_df['images'] results_list = [] #authenticate with prediction engine prediction_credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key}) predictor = CustomVisionPredictionClient(ENDPOINT, prediction_credentials) #make predictions, save to list for tweet_df for image in prediction_images: try: resource = urllib.request.urlopen(image) results = predictor.classify_image(project.id, publish_iteration_name, resource.read()) # Display the results. for prediction in results.predictions: #x is for screen display x = "\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100) print(x) # y is to add score to tweet_df y = "{0:.2f}%".format(prediction.probability * 100) results_list.append(y) except: print("one of the file doesn't exists or is difficult to predict") results_list.append("image doesn't exist or couldn't predict") print("the algorithm is finished") #append score result to tweet_df