ning8429 commited on
Commit
2d3c414
·
verified ·
1 Parent(s): d8ef608

Update api_server.py

Browse files
Files changed (1) hide show
  1. api_server.py +64 -33
api_server.py CHANGED
@@ -8,14 +8,14 @@ from ultralytics import YOLO
8
  import io
9
  import base64
10
  import uuid
11
-
12
- # Disable tensorflow warnings
13
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
14
-
15
  from tensorflow import keras
16
  from flask import Flask, jsonify, request, render_template, send_file
17
  import torch
18
 
 
 
 
19
  load_type = 'local'
20
 
21
  MODEL_NAME = "yolo11_detect_best_241018_1.pt"
@@ -50,12 +50,29 @@ else:
50
  raise AssertionError('No load type is specified!')
51
 
52
 
 
53
  def image_to_base64(image_path):
54
  with open(image_path, "rb") as image_file:
55
  encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
56
  return encoded_string
57
 
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  # Initialize the Flask application
60
  app = Flask(__name__)
61
 
@@ -65,18 +82,13 @@ app = Flask(__name__)
65
  def predict():
66
 
67
  user_id = request.args.get('user_id')
68
-
69
- # 生成一個唯一的 message_id
70
- message_id = str(uuid.uuid4())
71
 
72
  if 'image' not in request.files:
73
  # Handle if no file is selected
74
  return 'No file selected'
75
 
76
- start_time = time.time()
77
-
78
- file = request.files['image']
79
-
80
  # 讀取圖像
81
  try:
82
  image_data = Image.open(file)
@@ -90,20 +102,6 @@ def predict():
90
  if results is None or len(results) == 0:
91
  return jsonify({'error': 'No results from YOLO model'}), 400
92
 
93
- # # 渲染推理結果到圖像
94
- # img_with_boxes = results[0].plot() # 使用 results[0],假設只有一張圖像作推理
95
-
96
- # # 將 numpy array 轉換為 PIL Image
97
- # img = Image.fromarray(img_with_boxes)
98
-
99
- # # 儲存圖片到內存緩衝區
100
- # img_io = io.BytesIO()
101
- # img.save(img_io, 'PNG')
102
- # img_io.seek(0)
103
-
104
- # # 返回處理後的圖像
105
- # return send_file(img_io, mimetype='image/png')
106
-
107
  saved_images = []
108
 
109
  # 儲存辨識後的圖片到指定資料夾
@@ -115,22 +113,55 @@ def predict():
115
  labels = result.boxes.cls # Get predicted label IDs
116
  label_names = [model.names[int(label)] for label in labels] # Convert to names
117
 
118
- encoded_images=[]
119
 
120
- for label_name in label_names:
121
- output_file=f"{YOLO_DIR}/{message_id}/{label_name}/im.jpg.jpg"
122
- # 將圖片轉換為 base64 編碼
123
- encoded_images.append(image_to_base64(output_file))
124
-
 
 
 
 
 
 
 
 
 
 
 
 
125
  # 建立回應資料
126
  response_data = {
127
  'message_id': message_id,
128
  'images': encoded_images,
129
- 'description': label_names
130
  }
131
- return jsonify(response_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
 
 
133
 
 
134
  # # dictionary is not a JSON: https://www.quora.com/What-is-the-difference-between-JSON-and-a-dictionary
135
  # # flask.jsonify vs json.dumps https://sentry.io/answers/difference-between-json-dumps-and-flask-jsonify/
136
  # # The flask.jsonify() function returns a Response object with Serializable JSON and content_type=application/json.
 
8
  import io
9
  import base64
10
  import uuid
11
+ import glob
 
 
 
12
  from tensorflow import keras
13
  from flask import Flask, jsonify, request, render_template, send_file
14
  import torch
15
 
16
+ # Disable tensorflow warnings
17
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
18
+
19
  load_type = 'local'
20
 
21
  MODEL_NAME = "yolo11_detect_best_241018_1.pt"
 
50
  raise AssertionError('No load type is specified!')
51
 
52
 
53
+ # image to base64
54
  def image_to_base64(image_path):
55
  with open(image_path, "rb") as image_file:
56
  encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
57
  return encoded_string
58
 
59
 
60
+ # 抓取指定路徑下的所有 JPG 檔案
61
+ def get_jpg_files(path):
62
+ """
63
+ Args:
64
+ path: 要搜尋的目錄路徑。
65
+
66
+ Returns:
67
+ 一個包含所有 JPG 檔案路徑的列表。
68
+ """
69
+ return glob.glob(os.path.join(path, "*.jpg"))
70
+
71
+ # 使用範例
72
+ image_folder = '/content/drive/MyDrive/chiikawa' # 替換成你的目錄路徑
73
+ jpg_files = get_jpg_files(image_folder)
74
+
75
+
76
  # Initialize the Flask application
77
  app = Flask(__name__)
78
 
 
82
  def predict():
83
 
84
  user_id = request.args.get('user_id')
85
+ file = request.files['image']
86
+ message_id = str(uuid.uuid4()) # 生成一個唯一的 message_id
 
87
 
88
  if 'image' not in request.files:
89
  # Handle if no file is selected
90
  return 'No file selected'
91
 
 
 
 
 
92
  # 讀取圖像
93
  try:
94
  image_data = Image.open(file)
 
102
  if results is None or len(results) == 0:
103
  return jsonify({'error': 'No results from YOLO model'}), 400
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  saved_images = []
106
 
107
  # 儲存辨識後的圖片到指定資料夾
 
113
  labels = result.boxes.cls # Get predicted label IDs
114
  label_names = [model.names[int(label)] for label in labels] # Convert to names
115
 
116
+ element_counts = Counter(my_list)
117
 
118
+ encoded_images=[]
119
+ element_list =[]
120
+
121
+ for element, count in element_counts.items():
122
+ if element_counts[element] > 1: #某隻角色的數量>1
123
+ output_path = f"{YOLO_DIR}/{message_id}/{element}"
124
+ output_file = get_jpg_files(output_path)
125
+ element_list.append(element)
126
+
127
+ for output_img in output_file: # 取得每張圖的路徑
128
+ encoded_images.append(image_to_base64(output_img))
129
+
130
+ else : #某隻角色的數量=1
131
+ output_path = f"{YOLO_DIR}/{message_id}/{element}/im.jpg.jpg"
132
+ encoded_images.append(image_to_base64(output_path))
133
+ element_list.append(element)
134
+
135
  # 建立回應資料
136
  response_data = {
137
  'message_id': message_id,
138
  'images': encoded_images,
139
+ 'description': element_list
140
  }
141
+
142
+ return jsonify(response_data)
143
+
144
+ # for label_name in label_names:
145
+ # output_file=f"{YOLO_DIR}/{message_id}/{label_name}/im.jpg.jpg"
146
+ # # 將圖片轉換為 base64 編碼
147
+ # encoded_images.append(image_to_base64(output_file))
148
+
149
+
150
+ # # 渲染推理結果到圖像
151
+ # img_with_boxes = results[0].plot() # 使用 results[0],假設只有一張圖像作推理
152
+
153
+ # # 將 numpy array 轉換為 PIL Image
154
+ # img = Image.fromarray(img_with_boxes)
155
+
156
+ # # 儲存圖片到內存緩衝區
157
+ # img_io = io.BytesIO()
158
+ # img.save(img_io, 'PNG')
159
+ # img_io.seek(0)
160
 
161
+ # # 返回處理後的圖像
162
+ # return send_file(img_io, mimetype='image/png')
163
 
164
+
165
  # # dictionary is not a JSON: https://www.quora.com/What-is-the-difference-between-JSON-and-a-dictionary
166
  # # flask.jsonify vs json.dumps https://sentry.io/answers/difference-between-json-dumps-and-flask-jsonify/
167
  # # The flask.jsonify() function returns a Response object with Serializable JSON and content_type=application/json.