ning8429 commited on
Commit
52063f0
·
verified ·
1 Parent(s): 7114c54

Update api_server.py

Browse files
Files changed (1) hide show
  1. api_server.py +71 -60
api_server.py CHANGED
@@ -76,71 +76,82 @@ def predict():
76
 
77
  file = request.files['image']
78
 
79
- # Get pixels out of file
80
- image_data = Image.open(file)
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  # # Check image shape
83
  # if image_data.size != (28, 28):
84
  # return "Invalid image shape. Expected (28, 28), take from 'demo images' folder."
85
 
86
- # Preprocess the image
87
- processed_image = preprocess_image(image_data)
88
-
89
- # Make a prediction using YOLO
90
- results = model(processed_image)
91
-
92
- # Process the YOLO output
93
- detections = []
94
- for det in results.xyxy[0]: # Assuming results are in xyxy format (xmin, ymin, xmax, ymax, confidence, class)
95
- x_min, y_min, x_max, y_max, confidence, class_idx = det
96
- width = x_max - x_min
97
- height = y_max - y_min
98
- detection = {
99
- "label": int(class_idx),
100
- "confidence": float(confidence),
101
- "bbox": [float(x_min), float(y_min), float(width), float(height)]
102
- }
103
- detections.append(detection)
104
-
105
- # Calculate latency in milliseconds
106
- latency_ms = (time.time() - start_time) * 1000
107
-
108
- # Return the detection results and latency as JSON response
109
- response = {
110
- 'detections': detections,
111
- 'ml-latency-ms': round(latency_ms, 4)
112
- }
113
-
114
- # dictionary is not a JSON: https://www.quora.com/What-is-the-difference-between-JSON-and-a-dictionary
115
- # flask.jsonify vs json.dumps https://sentry.io/answers/difference-between-json-dumps-and-flask-jsonify/
116
- # The flask.jsonify() function returns a Response object with Serializable JSON and content_type=application/json.
117
- return jsonify(response)
118
-
119
-
120
- # Helper function to preprocess the image
121
- def preprocess_image(image_data):
122
- """Preprocess image for YOLO Model Inference
123
-
124
- :param image_data: Raw image (PIL.Image)
125
- :return: image: Preprocessed Image (Tensor)
126
- """
127
- # Define the YOLO input size (example 640x640, you can modify this based on your model)
128
- input_size = (640, 640)
129
-
130
- # Define transformation: Resize the image, convert to Tensor, and normalize pixel values
131
- transform = transforms.Compose([
132
- transforms.Resize(input_size), # Resize to YOLO input size
133
- transforms.ToTensor(), # Convert image to PyTorch Tensor (通道數、影像高度和寬度)
134
- transforms.Normalize([0.0, 0.0, 0.0], [1.0, 1.0, 1.0]) # Normalization (if needed)
135
- ])
136
-
137
- # Apply transformations to the image
138
- image = transform(image_data)
139
-
140
- # Add batch dimension (1, C, H, W) since YOLO expects a batch
141
- image = image.unsqueeze(0)
142
-
143
- return image
144
 
145
 
146
  # API route for health check
 
76
 
77
  file = request.files['image']
78
 
79
+ # 讀取圖像
80
+ try:
81
+ image_data = Image.open(file)
82
+ except Exception as e:
83
+ return jsonify({'error': str(e)}), 400
84
+
85
+ # 將圖像儲存到一個緩衝區
86
+ img_io = io.BytesIO()
87
+ image.save(img_io, 'PNG')
88
+ img_io.seek(0)
89
+
90
+ # 返回圖像
91
+ return send_file(img_io, mimetype='image/png')
92
 
93
  # # Check image shape
94
  # if image_data.size != (28, 28):
95
  # return "Invalid image shape. Expected (28, 28), take from 'demo images' folder."
96
 
97
+ # # Preprocess the image
98
+ # processed_image = preprocess_image(image_data)
99
+
100
+ # # Make a prediction using YOLO
101
+ # results = model(image_data)
102
+
103
+ # # Process the YOLO output
104
+ # detections = []
105
+ # for det in results.xyxy[0]: # Assuming results are in xyxy format (xmin, ymin, xmax, ymax, confidence, class)
106
+ # x_min, y_min, x_max, y_max, confidence, class_idx = det
107
+ # width = x_max - x_min
108
+ # height = y_max - y_min
109
+ # detection = {
110
+ # "label": int(class_idx),
111
+ # "confidence": float(confidence),
112
+ # "bbox": [float(x_min), float(y_min), float(width), float(height)]
113
+ # }
114
+ # detections.append(detection)
115
+
116
+ # # Calculate latency in milliseconds
117
+ # latency_ms = (time.time() - start_time) * 1000
118
+
119
+ # # Return the detection results and latency as JSON response
120
+ # response = {
121
+ # 'detections': detections,
122
+ # 'ml-latency-ms': round(latency_ms, 4)
123
+ # }
124
+
125
+ # # dictionary is not a JSON: https://www.quora.com/What-is-the-difference-between-JSON-and-a-dictionary
126
+ # # flask.jsonify vs json.dumps https://sentry.io/answers/difference-between-json-dumps-and-flask-jsonify/
127
+ # # The flask.jsonify() function returns a Response object with Serializable JSON and content_type=application/json.
128
+ # return jsonify(response)
129
+
130
+
131
+ # # Helper function to preprocess the image
132
+ # def preprocess_image(image_data):
133
+ # """Preprocess image for YOLO Model Inference
134
+
135
+ # :param image_data: Raw image (PIL.Image)
136
+ # :return: image: Preprocessed Image (Tensor)
137
+ # """
138
+ # # Define the YOLO input size (example 640x640, you can modify this based on your model)
139
+ # input_size = (640, 640)
140
+
141
+ # # Define transformation: Resize the image, convert to Tensor, and normalize pixel values
142
+ # transform = transforms.Compose([
143
+ # transforms.Resize(input_size), # Resize to YOLO input size
144
+ # transforms.ToTensor(), # Convert image to PyTorch Tensor (通道數、影像高度和寬度)
145
+ # transforms.Normalize([0.0, 0.0, 0.0], [1.0, 1.0, 1.0]) # Normalization (if needed)
146
+ # ])
147
+
148
+ # # Apply transformations to the image
149
+ # image = transform(image_data)
150
+
151
+ # # Add batch dimension (1, C, H, W) since YOLO expects a batch
152
+ # image = image.unsqueeze(0)
153
+
154
+ # return image
155
 
156
 
157
  # API route for health check