18
18
19
19
Examples:
20
20
python automl_vision_edge_container_predict.py \
21
- --image_file_path=./test.jpg --image_key=1 --port_number=8051
21
+ --image_file_path=./test.jpg --image_key=1 --port_number=8501
22
22
23
23
"""
24
24
25
25
import argparse
26
26
# [START automl_vision_edge_container_predict]
27
27
import base64
28
+ import cv2
28
29
import io
29
30
import json
30
31
31
32
import requests
32
33
34
+ def preprocess_image (image_file_path , max_width , max_height ):
35
+ """Preprocesses input images for AutoML Vision Edge models.
36
+
37
+ Args:
38
+ image_file_path: Path to a local image for the prediction request.
39
+ max_width: The max width for preprocessed images. The max width is 640
40
+ (1024) for AutoML Vision Image Classfication (Object Detection)
41
+ models.
42
+ max_height: The max width for preprocessed images. The max height is
43
+ 480 (1024) for AutoML Vision Image Classfication (Object
44
+ Detetion) models.
45
+ Returns:
46
+ The preprocessed encoded image bytes.
47
+ """
48
+ # cv2 is used to read, resize and encode images.
49
+ encode_param = [int (cv2 .IMWRITE_JPEG_QUALITY ), 85 ]
50
+ im = cv2 .imread (image_file_path )
51
+ [height , width , _ ] = im .shape
52
+ if height > max_height or width > max_width :
53
+ ratio = max (height / float (max_width ), width / float (max_height ))
54
+ new_height = int (height / ratio + 0.5 )
55
+ new_width = int (width / ratio + 0.5 )
56
+ resized_im = cv2 .resize (
57
+ im , (new_width , new_height ), interpolation = cv2 .INTER_AREA )
58
+ _ , processed_image = cv2 .imencode ('.jpg' , resized_im , encode_param )
59
+ else :
60
+ _ , processed_image = cv2 .imencode ('.jpg' , im , encode_param )
61
+ return base64 .b64encode (processed_image ).decode ('utf-8' )
62
+
33
63
34
64
def container_predict (image_file_path , image_key , port_number = 8501 ):
35
65
"""Sends a prediction request to TFServing docker container REST API.
@@ -41,9 +71,12 @@ def container_predict(image_file_path, image_key, port_number=8501):
41
71
Returns:
42
72
The response of the prediction request.
43
73
"""
44
-
45
- with io .open (image_file_path , 'rb' ) as image_file :
46
- encoded_image = base64 .b64encode (image_file .read ()).decode ('utf-8' )
74
+ # AutoML Vision Edge models will preprocess the input images.
75
+ # The max width and height for AutoML Vision Image Classification and
76
+ # Object Detection models are 640*480 and 1024*1024 separately. The
77
+ # example here is for Image Classification models.
78
+ encoded_image = preprocess_image (
79
+ image_file_path = image_file_path , max_width = 640 , max_height = 480 )
47
80
48
81
# The example here only shows prediction with one image. You can extend it
49
82
# to predict with a batch of images indicated by different keys, which can
0 commit comments