|
| 1 | +# Copyright 2020 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +def predict(project_id, model_id, file_path): |
| 17 | + """Predict.""" |
| 18 | + # [START automl_vision_object_detection_predict] |
| 19 | + from google.cloud import automl |
| 20 | + |
| 21 | + # TODO(developer): Uncomment and set the following variables |
| 22 | + # project_id = "YOUR_PROJECT_ID" |
| 23 | + # model_id = "YOUR_MODEL_ID" |
| 24 | + # file_path = "path_to_local_file.jpg" |
| 25 | + |
| 26 | + prediction_client = automl.PredictionServiceClient() |
| 27 | + |
| 28 | + # Get the full path of the model. |
| 29 | + model_full_id = prediction_client.model_path( |
| 30 | + project_id, "us-central1", model_id |
| 31 | + ) |
| 32 | + |
| 33 | + # Read the file. |
| 34 | + with open(file_path, "rb") as content_file: |
| 35 | + content = content_file.read() |
| 36 | + |
| 37 | + image = automl.types.Image(image_bytes=content) |
| 38 | + payload = automl.types.ExamplePayload(image=image) |
| 39 | + |
| 40 | + # params is additional domain-specific parameters. |
| 41 | + # score_threshold is used to filter the result |
| 42 | + # https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#predictrequest |
| 43 | + params = {"score_threshold": "0.8"} |
| 44 | + |
| 45 | + response = prediction_client.predict(model_full_id, payload, params) |
| 46 | + print("Prediction results:") |
| 47 | + for result in response.payload: |
| 48 | + print("Predicted class name: {}".format(result.display_name)) |
| 49 | + print( |
| 50 | + "Predicted class score: {}".format( |
| 51 | + result.image_object_detection.score |
| 52 | + ) |
| 53 | + ) |
| 54 | + bounding_box = result.image_object_detection.bounding_box |
| 55 | + print("Normalized Vertices:") |
| 56 | + for vertex in bounding_box.normalized_vertices: |
| 57 | + print("\tX: {}, Y: {}".format(vertex.x, vertex.y)) |
| 58 | + # [END automl_vision_object_detection_predict] |
0 commit comments