Advertisement
kopyl

Untitled

Jun 10th, 2023
1,139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. import json
  2. import numpy as np
  3. import cv2
  4. import onnxruntime
  5. import urllib.request
  6.  
  7.  
  8. model = "/child-adult-nonhuman.onnx"
  9. class_names = ["adults", "children", "nonhuman"]
  10.  
  11.  
  12. def predict_single_image(image_url):
  13.     req = urllib.request.Request(image_url, headers={"User-Agent": "Mozilla/5.0"})
  14.     with urllib.request.urlopen(req) as url:
  15.         image_contents = url.read()
  16.  
  17.     arr = np.asarray(bytearray(image_contents), dtype=np.uint8)
  18.     img = cv2.imdecode(arr, -1)
  19.  
  20.     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  21.  
  22.     resized_image = cv2.resize(img, (300, 300))
  23.     image_for_prediction = resized_image.transpose(2, 0, 1)
  24.     image_for_prediction = image_for_prediction.astype("float32") / 255.0
  25.     image_for_prediction = image_for_prediction[np.newaxis, :]
  26.  
  27.     data = json.dumps({"data": image_for_prediction.tolist()})
  28.     data = np.array(json.loads(data)["data"]).astype("float32")
  29.     session = onnxruntime.InferenceSession(model, None)
  30.     input_name = session.get_inputs()[0].name
  31.     output_name = session.get_outputs()[0].name
  32.  
  33.     result = session.run([output_name], {input_name: data})
  34.     prediction = int(np.argmax(np.array(result).squeeze(), axis=0))
  35.  
  36.     probabilities = np.exp(result) / np.sum(np.exp(result))
  37.     score = np.max(probabilities)
  38.     score = float(score)
  39.  
  40.     return {"predicted_class": class_names[prediction], "score": score}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement