Spaces:
Sleeping
Sleeping
Update api_server.py
Browse files- api_server.py +34 -34
api_server.py
CHANGED
@@ -75,45 +75,45 @@ def predict():
|
|
75 |
if results is None or len(results) == 0:
|
76 |
return jsonify({'error': 'No results from YOLO model'}), 400
|
77 |
|
78 |
-
# 渲染推理結果到圖像
|
79 |
-
img_with_boxes = results[0].plot() # 使用 results[0],假設只有一張圖像作推理
|
80 |
|
81 |
-
# 將 numpy array 轉換為 PIL Image
|
82 |
-
img = Image.fromarray(img_with_boxes)
|
83 |
|
84 |
-
# 儲存圖片到內存緩衝區
|
85 |
-
img_io = io.BytesIO()
|
86 |
-
img.save(img_io, 'PNG')
|
87 |
-
img_io.seek(0)
|
88 |
|
89 |
-
# 返回處理後的圖像
|
90 |
-
return send_file(img_io, mimetype='image/png')
|
91 |
|
92 |
-
|
93 |
|
94 |
-
#
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
#
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
|
118 |
|
119 |
|
|
|
75 |
if results is None or len(results) == 0:
|
76 |
return jsonify({'error': 'No results from YOLO model'}), 400
|
77 |
|
78 |
+
# # 渲染推理結果到圖像
|
79 |
+
# img_with_boxes = results[0].plot() # 使用 results[0],假設只有一張圖像作推理
|
80 |
|
81 |
+
# # 將 numpy array 轉換為 PIL Image
|
82 |
+
# img = Image.fromarray(img_with_boxes)
|
83 |
|
84 |
+
# # 儲存圖片到內存緩衝區
|
85 |
+
# img_io = io.BytesIO()
|
86 |
+
# img.save(img_io, 'PNG')
|
87 |
+
# img_io.seek(0)
|
88 |
|
89 |
+
# # 返回處理後的圖像
|
90 |
+
# return send_file(img_io, mimetype='image/png')
|
91 |
|
92 |
+
saved_images = []
|
93 |
|
94 |
+
# 儲存辨識後的圖片到指定資料夾
|
95 |
+
for result in results:
|
96 |
+
# 保存完整圖片
|
97 |
+
yolo_path = f'{YOLO_DIR}/results_{Path(result.path).name}'
|
98 |
+
result.save(yolo_path)
|
99 |
+
saved_images.append(yolo_path)
|
100 |
+
|
101 |
+
# 保存裁剪後的圖片(僅當 save_crop 返回有效的路徑時才加入)
|
102 |
+
cropped_images = result.save_crop(YOLO_DIR) # 有些 YOLO 版本 save_crop 不返回值
|
103 |
+
if cropped_images: # 確保不會對 None 進行迭代
|
104 |
+
if isinstance(cropped_images, list): # 如果它返回一個列表
|
105 |
+
saved_images.extend(cropped_images)
|
106 |
+
else:
|
107 |
+
saved_images.append(cropped_images)
|
108 |
+
|
109 |
+
end_time = time.time()
|
110 |
+
inference_time = end_time - start_time
|
111 |
+
|
112 |
+
# 返回辨識結果的文件路徑以及推理時間
|
113 |
+
return jsonify({
|
114 |
+
'saved_images': saved_images,
|
115 |
+
'inference_time': inference_time
|
116 |
+
}), 200
|
117 |
|
118 |
|
119 |
|