Fu-Chuen commited on
Commit
b085184
·
1 Parent(s): 111bf33

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -67
app.py CHANGED
@@ -139,89 +139,105 @@ def delete_files_in_folder(path):
139
  import subprocess
140
 
141
  def Aspergillus_Detect():
142
- delete_files_in_folder(image_path)
143
- # !python detect.py --source Fu-Chuen/Fungus_Classification_Genus_Species/tree/main/Test/ --weights $WEIGHTS --conf 0.25 --save-txt --exist-ok
144
- # Construct the command to run the detect.py script
145
- command = [
146
- "python",
147
- "yolov7_environment_data/yolov7/detect.py",
148
- "--source",
149
- test_path,
150
- "--weights",
151
- "$WEIGHTS"
152
- "--conf",
153
- "0.25",
154
- "--save-txt",
155
- "--exist-ok"
156
- ]
157
-
158
- # Run the command as a subprocess
159
- process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
160
- stdout, stderr = process.communicate()
161
-
162
- # Print the output and errors if any
163
- print("Output:", stdout)
164
- print("Errors:", stderr)
165
-
166
- file_paths = []
167
- for root, dirs, files in os.walk(label_path):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  for file in files:
169
  if file.lower().endswith('.jpg'):
170
  file_path = os.path.join(root, file)
171
  file_paths.append(file_path)
172
-
173
- df_test = pd.DataFrame({'filepath': file_paths})
174
-
175
- files = os.listdir(label_path)
176
-
177
- # initialize an empty list to store data
178
- data = []
179
-
180
- # loop through each file and extract the data
181
- for file in files:
182
  if file.endswith('.txt'):
183
  with open(os.path.join(label_path, file), 'r') as f:
184
  lines = f.readlines()
185
  for line in lines:
186
  line = line.strip().split(' ')
187
  data.append([file[:-4], line[0], float(line[1]), float(line[2]), float(line[3]), float(line[4])])
188
-
189
- # convert list of data to data frame
190
- df = pd.DataFrame(data, columns=['image', 'class', 'xmin', 'ymin', 'xmax', 'ymax'])
191
- # group by labels, count the number of detections for each label
192
- counts = df.groupby(['image', 'class']).size().reset_index(name='count')
193
- # add the file name to the data frame
194
- counts['file'] = counts['image'].apply(lambda x: x + '.jpg')
195
-
196
- counts['filepath'] = counts['file'].apply(lambda x: Path(label_path,x))
197
-
198
- replace_dict = {'0': 'flavus-oryzae', '1': 'fumigatus', '2': 'niger', '3': 'terreus', '4': 'versicolor'}
199
- counts['label'] = counts['class'].replace(replace_dict)
200
-
201
- # Select only the relevant columns
202
- counts = counts[['filepath', 'label', 'count']]
203
- df_pivot = pd.pivot_table(counts, values='count', index=['filepath'], columns='label', aggfunc='sum')
204
- df_pivot['detect'] = df_pivot.sum(axis=1)
205
- pd.options.display.float_format = '{:,.0f}'.format
206
- df_pivot = pd.DataFrame(df_pivot)
207
-
208
- total_col = df_pivot.pop('detect')
209
- df_pivot.insert(0, 'detect', total_col)
210
- detect_number = round(df_pivot['detect'].sum())
211
- a = []
212
- for i in df_pivot.columns[1:]:
213
  a.append([i,round(df_pivot[i].sum()/detect_number,3)])
214
- a = sorted(a,key=lambda x: x[1],reverse=True)
215
-
216
- result = [f'Prediction of species of Aspergillus: {a[0][0] if a[0][1] >= threshold else "Unclassified"}',
217
  f'There are {df_pivot.shape[0]} mold images.',
218
  f'Yolov7 detects {detect_number} instances.',
219
  f'The top {len(a)} percentage of specifies:']
220
- for i in a:
221
  # print(f'i: {i}')
222
  result.append(f'{i[0]} {i[1]}')
223
-
224
- return '\n'.join(result)
225
 
226
  """# classify images: genus and Aspergillus"""
227
 
 
139
  import subprocess
140
 
141
  def Aspergillus_Detect():
142
+ delete_files_in_folder(image_path)
143
+ # # !python detect.py --source Fu-Chuen/Fungus_Classification_Genus_Species/tree/main/Test/ --weights $WEIGHTS --conf 0.25 --save-txt --exist-ok
144
+ # # Construct the command to run the detect.py script
145
+ # command = [
146
+ # "python",
147
+ # "yolov7_environment_data/yolov7/detect.py",
148
+ # "--source",
149
+ # test_path,
150
+ # "--weights",
151
+ # "$WEIGHTS"
152
+ # "--conf",
153
+ # "0.25",
154
+ # "--save-txt",
155
+ # "--exist-ok"
156
+ # ]
157
+
158
+ # # Run the command as a subprocess
159
+ # process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
160
+ # stdout, stderr = process.communicate()
161
+
162
+ # # Print the output and errors if any
163
+ # print("Output:", stdout)
164
+ # print("Errors:", stderr)
165
+
166
+
167
+ !pip install transformers
168
+
169
+ from transformers import AutoModelForYOLO
170
+
171
+ # 在Hugging Face Hub上选择并加载已经训练好的YOLO v7模型
172
+ model_name = r'Model/best_Yolo_v7.pt' # 请将"your_yolo_v7_model_name"替换为实际的模型名称
173
+ model = AutoModelForYOLO.from_pretrained(model_name)
174
+
175
+ # 在此处添加推理代码,根据模型的要求对输入数据进行推理
176
+ inference_results = model.inference(input_data)
177
+ print(inference_results)
178
+
179
+
180
+
181
+
182
+ file_paths = []
183
+ for root, dirs, files in os.walk(label_path):
184
  for file in files:
185
  if file.lower().endswith('.jpg'):
186
  file_path = os.path.join(root, file)
187
  file_paths.append(file_path)
188
+
189
+ df_test = pd.DataFrame({'filepath': file_paths})
190
+
191
+ files = os.listdir(label_path)
192
+
193
+ # initialize an empty list to store data
194
+ data = []
195
+
196
+ # loop through each file and extract the data
197
+ for file in files:
198
  if file.endswith('.txt'):
199
  with open(os.path.join(label_path, file), 'r') as f:
200
  lines = f.readlines()
201
  for line in lines:
202
  line = line.strip().split(' ')
203
  data.append([file[:-4], line[0], float(line[1]), float(line[2]), float(line[3]), float(line[4])])
204
+
205
+ # convert list of data to data frame
206
+ df = pd.DataFrame(data, columns=['image', 'class', 'xmin', 'ymin', 'xmax', 'ymax'])
207
+ # group by labels, count the number of detections for each label
208
+ counts = df.groupby(['image', 'class']).size().reset_index(name='count')
209
+ # add the file name to the data frame
210
+ counts['file'] = counts['image'].apply(lambda x: x + '.jpg')
211
+
212
+ counts['filepath'] = counts['file'].apply(lambda x: Path(label_path,x))
213
+
214
+ replace_dict = {'0': 'flavus-oryzae', '1': 'fumigatus', '2': 'niger', '3': 'terreus', '4': 'versicolor'}
215
+ counts['label'] = counts['class'].replace(replace_dict)
216
+
217
+ # Select only the relevant columns
218
+ counts = counts[['filepath', 'label', 'count']]
219
+ df_pivot = pd.pivot_table(counts, values='count', index=['filepath'], columns='label', aggfunc='sum')
220
+ df_pivot['detect'] = df_pivot.sum(axis=1)
221
+ pd.options.display.float_format = '{:,.0f}'.format
222
+ df_pivot = pd.DataFrame(df_pivot)
223
+
224
+ total_col = df_pivot.pop('detect')
225
+ df_pivot.insert(0, 'detect', total_col)
226
+ detect_number = round(df_pivot['detect'].sum())
227
+ a = []
228
+ for i in df_pivot.columns[1:]:
229
  a.append([i,round(df_pivot[i].sum()/detect_number,3)])
230
+ a = sorted(a,key=lambda x: x[1],reverse=True)
231
+
232
+ result = [f'Prediction of species of Aspergillus: {a[0][0] if a[0][1] >= threshold else "Unclassified"}',
233
  f'There are {df_pivot.shape[0]} mold images.',
234
  f'Yolov7 detects {detect_number} instances.',
235
  f'The top {len(a)} percentage of specifies:']
236
+ for i in a:
237
  # print(f'i: {i}')
238
  result.append(f'{i[0]} {i[1]}')
239
+
240
+ return '\n'.join(result)
241
 
242
  """# classify images: genus and Aspergillus"""
243