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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
import sys
|
3 |
+
import openai
|
4 |
+
import toml
|
5 |
+
from openai import OpenAI
|
6 |
|
7 |
|
8 |
+
import pandas as pd
|
9 |
+
import os
|
10 |
+
import random
|
11 |
+
import glob
|
12 |
+
import re
|
13 |
+
from io import BytesIO
|
14 |
+
from six import BytesIO
|
15 |
+
import cv2
|
16 |
+
import warnings
|
17 |
+
warnings.filterwarnings('ignore')
|
18 |
+
|
19 |
+
from io import BytesIO
|
20 |
+
import tempfile
|
21 |
+
import time
|
22 |
+
import matplotlib.pyplot as plt
|
23 |
+
import matplotlib.colors as mcolors
|
24 |
+
import seaborn as sns
|
25 |
+
from PIL import Image
|
26 |
+
from PIL import ImageColor
|
27 |
+
from PIL import ImageDraw
|
28 |
+
from PIL import ImageFont
|
29 |
+
from PIL import ImageOps
|
30 |
+
import json
|
31 |
+
|
32 |
+
import numpy as np
|
33 |
+
np.random.seed(42)
|
34 |
+
import tensorflow as tf
|
35 |
+
tf.random.set_seed(42)
|
36 |
+
|
37 |
+
import tensorflow.keras as k
|
38 |
+
k.utils.set_random_seed(42) # idem keras
|
39 |
+
|
40 |
+
from keras.backend import manual_variable_initialization
|
41 |
+
manual_variable_initialization(True) # https://github.com/keras-team/keras/issues/4875#issuecomment-296696536
|
42 |
+
|
43 |
+
from tensorflow.keras.applications.xception import preprocess_input
|
44 |
+
from tensorflow.keras.applications.xception import Xception
|
45 |
+
from scipy.stats import mode
|
46 |
+
from tensorflow.keras.applications.mobilenet import MobileNet
|
47 |
+
from tensorflow.keras.applications.mobilenet import preprocess_input as mobilenet_preprocess
|
48 |
+
from tensorflow.keras.applications.xception import preprocess_input as xception_preprocess
|
49 |
+
|
50 |
+
import tensorflow_hub as hub
|
51 |
+
|
52 |
+
|
53 |
+
@st.cache_resource
|
54 |
+
def load_models_etc():
|
55 |
+
#OpenAI elements
|
56 |
+
#secrets = toml.load(".vscode/streamlit/secrets.toml")
|
57 |
+
#client_d = OpenAI(api_key = secrets["OPENAI_API_KEY"])
|
58 |
+
client_d = OpenAI(api_key = st.secrets["OPENAI_API_KEY"])
|
59 |
+
|
60 |
+
module_handle = "https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1"
|
61 |
+
detector_d = hub.load(module_handle).signatures['default'];
|
62 |
+
|
63 |
+
file_path = '.vscode/inputs/' # folder with files
|
64 |
+
Dis_percentage_d = pd.read_csv(os.path.join(file_path,'Spots_Percentage_results.csv'))
|
65 |
+
Details_d = pd.read_csv(os.path.join(file_path,'Plant_details.csv'))
|
66 |
+
|
67 |
+
# Load the TensorFlow Lite model
|
68 |
+
#model_path = '.vscode/model/model.tflite'
|
69 |
+
#interpreter = tf.lite.Interpreter(model_path=model_path)
|
70 |
+
#interpreter.allocate_tensors()
|
71 |
+
|
72 |
+
print("Loading CNN Model")
|
73 |
+
model3_path = '.vscode/model/CNN_0424.keras'
|
74 |
+
model3_weights_path = '.vscode/model/CNN_weights.hdf5'
|
75 |
+
cnn_model_d = k.models.load_model(model3_weights_path)
|
76 |
+
|
77 |
+
print("Loading Xception Model")
|
78 |
+
model1_path = '.vscode/model/XCeption_weights.hdf5'
|
79 |
+
xception_model_d = k.models.load_model(model1_path)
|
80 |
+
|
81 |
+
print("Loading Mobilenet Model")
|
82 |
+
model2_path = '.vscode/model/MobileNet_weights.hdf5'
|
83 |
+
mobilenet_model_d = k.models.load_model(model2_path)
|
84 |
+
print("finished loading models")
|
85 |
+
|
86 |
+
with open('.vscode/inputs/Xception_0422_labels.json', 'r') as file:
|
87 |
+
loaded_class_indices = {k: int(v) for k, v in json.load(file).items()}
|
88 |
+
class_labels_d = {value: key for key, value in loaded_class_indices.items()} # Convert keys to int
|
89 |
+
|
90 |
+
#xception_model.weights[-1]
|
91 |
+
#mobilenet_model.weights[-1]
|
92 |
+
#cnn_model.weights[-1]
|
93 |
+
|
94 |
+
return client_d,detector_d,Dis_percentage_d,Details_d,cnn_model_d,xception_model_d,mobilenet_model_d,class_labels_d
|
95 |
+
|
96 |
+
|
97 |
+
client,detector,Dis_percentage,Details,cnn_model,xception_model,mobilenet_model,class_labels = load_models_etc()
|
98 |
+
|
99 |
+
|
100 |
+
# Identify extent of spot or lesion coverage on leaf
|
101 |
+
def identify_spots_or_lesions(img):
|
102 |
+
|
103 |
+
cv_image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
104 |
+
lab_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2Lab)
|
105 |
+
l_channel, a_channel, b_channel = cv2.split(lab_image)
|
106 |
+
blur = cv2.GaussianBlur(a_channel,(3,3),0)
|
107 |
+
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
|
108 |
+
|
109 |
+
# Morphological clean-up
|
110 |
+
kernel = np.ones((3,3), np.uint8)
|
111 |
+
cleaned = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1) # Opening = erosion followed by dilation
|
112 |
+
edges = cv2.Canny(cleaned,100,300)
|
113 |
+
|
114 |
+
# Filter and contours
|
115 |
+
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
116 |
+
max_area = 18000
|
117 |
+
filtered_contours = [cnt for cnt in contours if cv2.contourArea(cnt) < max_area]
|
118 |
+
|
119 |
+
# Calculate the percentage of spots/lesions
|
120 |
+
spot_pixels = sum(cv2.contourArea(cnt) for cnt in filtered_contours)
|
121 |
+
total_pixels = edges.shape[0] * edges.shape[1]
|
122 |
+
percentage_spots = (spot_pixels / total_pixels)*100
|
123 |
+
print(f"Percentage of spots/lesions: {percentage_spots:.2f}%")
|
124 |
+
|
125 |
+
# Draw filtered contours
|
126 |
+
contoured_image = cv2.drawContours(cv_image.copy(), filtered_contours, -1, (0, 255, 0), 1)
|
127 |
+
|
128 |
+
# Visualization
|
129 |
+
plt.figure(figsize=(25, 8))
|
130 |
+
plt.subplot(1, 5, 1)
|
131 |
+
plt.imshow(cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB))
|
132 |
+
plt.title('Original Image')
|
133 |
+
|
134 |
+
plt.subplot(1, 5, 2)
|
135 |
+
plt.imshow(a_channel, cmap='gray')
|
136 |
+
plt.title('LAB - A channel')
|
137 |
+
|
138 |
+
plt.subplot(1, 5, 3)
|
139 |
+
plt.imshow(edges, cmap='gray')
|
140 |
+
plt.title('Edge Detection')
|
141 |
+
|
142 |
+
plt.subplot(1, 5, 4)
|
143 |
+
plt.imshow(cleaned, cmap='gray')
|
144 |
+
plt.title('Thresholded & Cleaned')
|
145 |
+
|
146 |
+
plt.subplot(1, 5, 5)
|
147 |
+
plt.imshow(cv2.cvtColor(contoured_image, cv2.COLOR_BGR2RGB))
|
148 |
+
plt.title('Spots or Lesions Identified')
|
149 |
+
plt.show()
|
150 |
+
return(percentage_spots)
|
151 |
+
|
152 |
+
|
153 |
+
# Plot disease percentage
|
154 |
+
def plot_dis_percentage(row, percentage):
|
155 |
+
# Determine the range category for the title
|
156 |
+
if percentage < row['Q1']:
|
157 |
+
category = 'Mild'
|
158 |
+
color = 'yellow'
|
159 |
+
elif row['Q1'] <= percentage <= row['Q3']:
|
160 |
+
category = 'Moderate'
|
161 |
+
color = 'orange'
|
162 |
+
else:
|
163 |
+
category = 'Severe'
|
164 |
+
color = 'darkred'
|
165 |
+
|
166 |
+
# Normalize the data to the range of [0, 1]
|
167 |
+
min_val = row['min']
|
168 |
+
max_val = row['max']
|
169 |
+
range_val = max_val - min_val
|
170 |
+
percentage_norm = (percentage - min_val) / range_val
|
171 |
+
|
172 |
+
# Create a figure and a set of subplots
|
173 |
+
fig, ax = plt.subplots(figsize=(6, 1))
|
174 |
+
|
175 |
+
# Create the ranges for Low, Medium, and High
|
176 |
+
ax.axhline(0, xmin=0, xmax=(row['Q1'] - min_val) / range_val, color='yellow', linewidth=4, label='Mild')
|
177 |
+
ax.axhline(0, xmin=(row['Q1'] - min_val) / range_val, xmax=(row['Q3'] - min_val) / range_val, color='orange', linewidth=4, label='Moderate')
|
178 |
+
ax.axhline(0, xmin=(row['Q3'] - min_val) / range_val, xmax=1, color='darkred', linewidth=4, label='Severe')
|
179 |
+
|
180 |
+
# Plot the actual percentage as an arrow
|
181 |
+
ax.annotate('', xy=(percentage_norm, 0.1), xytext=(percentage_norm, -0.1),
|
182 |
+
arrowprops=dict(facecolor=color, shrink=0.05, width=1, headwidth=10))
|
183 |
+
|
184 |
+
# Set display parameters
|
185 |
+
ax.set_yticks([]) # No y-ticks
|
186 |
+
ax.set_xticks([]) # Remove specific percentage figures from the x-axis
|
187 |
+
ax.set_xlim([0, 1]) # Set x-limits to normalized range
|
188 |
+
titlet = f'{category} - {row["Plant"]}'
|
189 |
+
ax.set_title(titlet)
|
190 |
+
ax.set_xlabel('Value (Normalized)')
|
191 |
+
|
192 |
+
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
|
193 |
+
plt.tight_layout()
|
194 |
+
st.pyplot(fig)
|
195 |
+
return titlet
|
196 |
+
|
197 |
+
|
198 |
+
|
199 |
+
def resize_image(image, target_size=(224, 224)):
|
200 |
+
return image.resize(target_size)
|
201 |
+
|
202 |
+
|
203 |
+
|
204 |
+
# Classify the image
|
205 |
+
def classify_image(image):
|
206 |
+
# Convert PIL Image to a NumPy array
|
207 |
+
image_np = np.array(image)
|
208 |
+
|
209 |
+
# Preprocess the image as needed
|
210 |
+
resized_image = cv2.resize(image_np, (224, 224), interpolation=cv2.INTER_LINEAR)
|
211 |
+
|
212 |
+
img_array = np.array(resized_image, dtype='float32')
|
213 |
+
img_array = np.expand_dims(img_array, axis=0)
|
214 |
+
img_batch = np.tile(img_array, (32, 1, 1, 1))
|
215 |
+
|
216 |
+
# preprocess_input from Xception to scale the image to -1 to +1
|
217 |
+
#img_array = preprocess_input(img_array)
|
218 |
+
|
219 |
+
# Perform inference using the TensorFlow Lite model
|
220 |
+
#interpreter.set_tensor(interpreter.get_input_details()[0]['index'], img_array)
|
221 |
+
#interpreter.invoke()
|
222 |
+
#prediction = interpreter.get_tensor(interpreter.get_output_details()[0]['index'])
|
223 |
+
|
224 |
+
|
225 |
+
mobilenet_input = mobilenet_preprocess(np.copy(img_batch))
|
226 |
+
xception_input = xception_preprocess(np.copy(img_batch))
|
227 |
+
cnn_input = img_batch / 255.0 # normalization for generic CNN model
|
228 |
+
|
229 |
+
# Predict using the models
|
230 |
+
mobilenet_preds = mobilenet_model(mobilenet_input, training = False)
|
231 |
+
xception_preds = xception_model(xception_input, training = False)
|
232 |
+
cnn_preds = cnn_model(cnn_input, training = False)
|
233 |
+
|
234 |
+
|
235 |
+
# Get the most likely class index from predictions
|
236 |
+
mobilenet_class = np.argmax(mobilenet_preds, axis=1)
|
237 |
+
xception_class = np.argmax(xception_preds, axis=1)
|
238 |
+
cnn_class = np.argmax(cnn_preds, axis=1)
|
239 |
+
|
240 |
+
# --------------------------------
|
241 |
+
# mean probabilities from each model
|
242 |
+
averaged_probs = (mobilenet_preds + xception_preds + cnn_preds) / 3
|
243 |
+
averaged_probs_np = averaged_probs.numpy()
|
244 |
+
|
245 |
+
# top two most likely class indices
|
246 |
+
top_two_probs_indices = np.argsort(-averaged_probs_np, axis=1)[:, :2]
|
247 |
+
top_class_index = top_two_probs_indices[:, 0]
|
248 |
+
second_class_index = top_two_probs_indices[:, 1]
|
249 |
+
top_class_prob = np.max(averaged_probs_np, axis=1)
|
250 |
+
second_class_prob = averaged_probs_np[np.arange(top_class_index.size), second_class_index]
|
251 |
+
predicted_class_name = class_labels[top_class_index[0]]
|
252 |
+
second_class_name = class_labels[second_class_index[0]]
|
253 |
+
|
254 |
+
# --------------------------------
|
255 |
+
|
256 |
+
if top_class_prob[0] < 0.999: # threshold close to 1 to handle floating-point precision issues
|
257 |
+
print("Second predicted class:", second_class_name)
|
258 |
+
print(f"Second class confidence: {second_class_prob[0]:.3%}")
|
259 |
+
else:
|
260 |
+
print("Second predicted class: None")
|
261 |
+
|
262 |
+
if "healthy" in predicted_class_name:
|
263 |
+
print(f"{predicted_class_name} is healthy, skipping further analysis.")
|
264 |
+
return
|
265 |
+
else:
|
266 |
+
if "Background_without_leaves" in predicted_class_name:
|
267 |
+
print(f"{predicted_class_name} is not recognized as a plant image, skipping further analysis.")
|
268 |
+
return
|
269 |
+
else:
|
270 |
+
spots_percentage = identify_spots_or_lesions(image)
|
271 |
+
|
272 |
+
|
273 |
+
if predicted_class_name in Dis_percentage['Plant'].values:
|
274 |
+
row = Dis_percentage.loc[Dis_percentage['Plant'] == predicted_class_name].iloc[0]
|
275 |
+
severity_disease = plot_dis_percentage(row, spots_percentage)
|
276 |
+
|
277 |
+
if predicted_class_name in Details['Plant'].values:
|
278 |
+
row = Details.loc[Details['Plant'] == predicted_class_name].iloc[0]
|
279 |
+
st.write("Disease Identification:", row[4])
|
280 |
+
st.write("----------------------------------")
|
281 |
+
#st.write("Management:", row[5])
|
282 |
+
#st.markdown(severity_disease)
|
283 |
+
return severity_disease, top_class_prob[0], second_class_name
|
284 |
+
else:
|
285 |
+
st.write("No data available for this plant disease in DataFrame.")
|
286 |
+
return
|
287 |
+
|
288 |
+
|
289 |
+
|
290 |
+
|
291 |
+
# Streamlit app
|
292 |
+
|
293 |
+
tab1, tab2, tab3 = st.tabs(["Home", "Solution", "Team"])
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
#First Tab: Title of Application and description
|
298 |
+
with tab1:
|
299 |
+
st.title("Plant Disease Identification")
|
300 |
+
# Display Plant Care Icon
|
301 |
+
st.image(".vscode/inputs/plantIcon.jpg", width=100)
|
302 |
+
st.markdown("Plant diseases are a significant threat to agricultural productivity worldwide, causing substantial crop losses and economic damage. These diseases can be caused by various factors, including fungi, bacteria, viruses, and environmental stressors. Recognizing the symptoms of plant diseases early is crucial for implementing effective management strategies and minimizing the impact on crop yield and quality.")
|
303 |
+
# Importance of Early Detection
|
304 |
+
st.write("""
|
305 |
+
### Importance of Early Detection
|
306 |
+
|
307 |
+
Early detection of plant diseases is paramount for farmers to protect their crops and livelihoods. By identifying diseases at their onset, farmers can implement timely interventions, such as targeted pesticide applications or cultural practices, to prevent the spread of diseases and reduce crop losses. Early detection also reduces the need for excessive chemical inputs, promoting sustainable agriculture practices and environmental stewardship.
|
308 |
+
""")
|
309 |
+
|
310 |
+
# Types of Plant Diseases Detected
|
311 |
+
st.image(".vscode/inputs/Plant-disease-classifier-with-ai-blog-banner.jpg", width=700)
|
312 |
+
|
313 |
+
st.write("With more than 50% of the population in India still relying on agriculture and with the average farm sizes and incomes being very small, we believe that cost effective solutions for early detection and treatment solutions for disease could significantly improve the quality of produce and lives of farmers. With smartphones being ubiquitous, we believe providing solutions to farmers over a smartphone is the most penetrative form.")
|
314 |
+
|
315 |
+
|
316 |
+
|
317 |
+
|
318 |
+
|
319 |
+
#Second Tab: Image upload and disease detection and remidy susgestions
|
320 |
+
with tab2:
|
321 |
+
st.title("Plant classification, Disease detection and management")
|
322 |
+
|
323 |
+
# Load and display the image
|
324 |
+
uploaded_file = st.file_uploader("Upload Leaf Image...", type=["jpg", "jpeg", "png"], key="uploader")
|
325 |
+
|
326 |
+
|
327 |
+
if uploaded_file is not None:
|
328 |
+
|
329 |
+
print("Image successfully uploaded!")
|
330 |
+
# Read the uploaded image file
|
331 |
+
st.image(uploaded_file, caption='Uploaded Image', use_column_width=True)
|
332 |
+
image = Image.open(uploaded_file)
|
333 |
+
|
334 |
+
image_for_drawing = image.copy()
|
335 |
+
|
336 |
+
# convert PIL format to TensorFlow format
|
337 |
+
img = tf.convert_to_tensor(image)
|
338 |
+
converted_img = tf.image.convert_image_dtype(img, tf.float32)[tf.newaxis, ...] #scales 0-1
|
339 |
+
|
340 |
+
start_time = time.time()
|
341 |
+
result = detector(converted_img)
|
342 |
+
end_time = time.time()
|
343 |
+
|
344 |
+
result = {key: value.numpy() for key, value in result.items()}
|
345 |
+
|
346 |
+
print("Found %d objects." % len(result["detection_scores"]))
|
347 |
+
print("Inference time: ", end_time - start_time)
|
348 |
+
|
349 |
+
detection_scores = result["detection_scores"]
|
350 |
+
detection_class_entities = result["detection_class_entities"]
|
351 |
+
|
352 |
+
#image_with_boxes = draw_boxes(image_for_drawing, result["detection_boxes"],detection_class_entities, detection_scores)
|
353 |
+
|
354 |
+
#display_image(image_with_boxes)
|
355 |
+
|
356 |
+
top_3_idx = np.argsort(-detection_scores)[:3]
|
357 |
+
|
358 |
+
for idx in top_3_idx:
|
359 |
+
entity = detection_class_entities[idx].decode('utf-8')
|
360 |
+
if "Plant" == entity:
|
361 |
+
plant_score = detection_scores[idx]
|
362 |
+
print(f"Plant probability score: {plant_score:.2%}")
|
363 |
+
result1 = classify_image(image)
|
364 |
+
|
365 |
+
if result1 is not None:
|
366 |
+
#st.markdown("Result " + result)
|
367 |
+
new1 = result1[0] + ""
|
368 |
+
newresult = new1.replace("_"," ")
|
369 |
+
newresult2 = newresult.replace("-"," ")
|
370 |
+
st.markdown("Searching disease management steps for " + ":red[" + newresult2 + "]... :eyes:")
|
371 |
+
completion = client.chat.completions.create(
|
372 |
+
model="gpt-4-turbo",
|
373 |
+
messages=[
|
374 |
+
{"role": "user", "content": "List out the most relevant remediation steps for " + newresult2 + " in 7 bullet points"}
|
375 |
+
],
|
376 |
+
temperature=0.1,
|
377 |
+
max_tokens=2000,
|
378 |
+
top_p=0.1
|
379 |
+
)
|
380 |
+
st.markdown(completion.choices[0].message.content)
|
381 |
+
#st.markdown(completion.choices[0].delta.content)
|
382 |
+
else:
|
383 |
+
print("No file uploaded.")
|
384 |
+
|
385 |
+
|
386 |
+
# Disclaimer
|
387 |
+
st.write("""
|
388 |
+
### Disclaimer
|
389 |
+
|
390 |
+
While our disease identification system strives for accuracy and reliability, it is essential to note its limitations. False positives or false negatives may occur, and users are encouraged to consult with agricultural experts for professional advice and decision-making.
|
391 |
+
""")
|
392 |
+
|
393 |
+
|
394 |
+
|
395 |
+
|
396 |
+
|
397 |
+
|
398 |
+
|
399 |
+
|
400 |
+
# Third Tab
|
401 |
+
with tab3:
|
402 |
+
st.title("CDS Batch 6 - Group 2:")
|
403 |
+
st.divider()
|
404 |
+
|
405 |
+
st.write("Abhinav Singh")
|
406 |
+
st.divider()
|
407 |
+
|
408 |
+
st.write("Ankit Kourav")
|
409 |
+
st.divider()
|
410 |
+
|
411 |
+
st.write("Challoju Anurag.")
|
412 |
+
st.divider()
|
413 |
+
|
414 |
+
st.write("Madhucchand Darbha")
|
415 |
+
st.divider()
|
416 |
+
|
417 |
+
st.write("Neha Gupta")
|
418 |
+
st.divider()
|
419 |
+
|
420 |
+
st.write("Pradeep Rajagopal")
|
421 |
+
st.divider()
|
422 |
+
|
423 |
+
st.write("Rakesh Vegesana")
|
424 |
+
st.divider()
|
425 |
+
|
426 |
+
st.write("Sachin Sharma")
|
427 |
+
st.divider()
|
428 |
+
|
429 |
+
st.write("Shashank Srivastava")
|
430 |
+
st.divider()
|
431 |
+
|
432 |
+
|
433 |
+
|
434 |
+
|
435 |
+
|
436 |
+
def display_image(image):
|
437 |
+
fig = plt.figure(figsize=(12, 6))
|
438 |
+
plt.grid(False)
|
439 |
+
plt.imshow(image)
|
440 |
+
plt.show()
|
441 |
+
|
442 |
+
|
443 |
+
def draw_bounding_box_on_image(image,
|
444 |
+
ymin,
|
445 |
+
xmin,
|
446 |
+
ymax,
|
447 |
+
xmax,
|
448 |
+
color,
|
449 |
+
font,
|
450 |
+
thickness=4,
|
451 |
+
display_str_list=()):
|
452 |
+
"""Adds a bounding box to an image."""
|
453 |
+
draw = ImageDraw.Draw(image)
|
454 |
+
im_width, im_height = image.size
|
455 |
+
(left, right, top, bottom) = (xmin * im_width, xmax * im_width,
|
456 |
+
ymin * im_height, ymax * im_height)
|
457 |
+
draw.line([(left, top), (left, bottom), (right, bottom), (right, top),
|
458 |
+
(left, top)],
|
459 |
+
width=thickness,
|
460 |
+
fill=color)
|
461 |
+
|
462 |
+
# height of the display strings added to the top of the bounding
|
463 |
+
# box exceeds the top of the image - stack below:
|
464 |
+
display_str_heights = [font.getbbox(ds)[3] for ds in display_str_list]
|
465 |
+
total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)
|
466 |
+
|
467 |
+
if top > total_display_str_height:
|
468 |
+
text_bottom = top
|
469 |
+
else:
|
470 |
+
text_bottom = top + total_display_str_height
|
471 |
+
# Reverse list and print from bottom to top.
|
472 |
+
for display_str in display_str_list[::-1]:
|
473 |
+
bbox = font.getbbox(display_str)
|
474 |
+
text_width, text_height = bbox[2], bbox[3]
|
475 |
+
margin = np.ceil(0.05 * text_height)
|
476 |
+
draw.rectangle([(left, text_bottom - text_height - 2 * margin),
|
477 |
+
(left + text_width, text_bottom)],
|
478 |
+
fill=color)
|
479 |
+
draw.text((left + margin, text_bottom - text_height - margin),
|
480 |
+
display_str,
|
481 |
+
fill="black",
|
482 |
+
font=font)
|
483 |
+
text_bottom -= text_height - 2 * margin
|
484 |
+
|
485 |
+
|
486 |
+
|
487 |
+
def draw_boxes(image, boxes, class_names, scores, max_boxes=3, min_score=0.1):
|
488 |
+
"""Overlay labeled boxes on an image with formatted scores and label names."""
|
489 |
+
colors = list(ImageColor.colormap.values())
|
490 |
+
|
491 |
+
try:
|
492 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Regular.ttf", 15)
|
493 |
+
except IOError:
|
494 |
+
print("Font not found, using default font.")
|
495 |
+
font = ImageFont.load_default()
|
496 |
+
|
497 |
+
# Prepare a list of all detections that meet the score threshold
|
498 |
+
filtered_boxes = [(boxes[i], scores[i], class_names[i]) for i in range(len(scores)) if scores[i] >= min_score]
|
499 |
+
|
500 |
+
# Sort detections based on scores in descending order
|
501 |
+
filtered_boxes.sort(key=lambda x: x[1], reverse=False)
|
502 |
+
|
503 |
+
# Process each box to draw (limited by max_boxes)
|
504 |
+
for i, (box, score, class_name) in enumerate(filtered_boxes[:max_boxes]):
|
505 |
+
ymin, xmin, ymax, xmax = tuple(box)
|
506 |
+
display_str = "{}: {:.2f}%".format(class_name.decode("ascii"), score * 100)
|
507 |
+
color = colors[hash(class_name) % len(colors)]
|
508 |
+
draw_bounding_box_on_image(
|
509 |
+
image,
|
510 |
+
ymin,
|
511 |
+
xmin,
|
512 |
+
ymax,
|
513 |
+
xmax,
|
514 |
+
color,
|
515 |
+
font,
|
516 |
+
display_str_list=[display_str])
|
517 |
+
|
518 |
+
# Convert PIL Image back to numpy array for display (if necessary)
|
519 |
+
return np.array(image) if isinstance(image, Image.Image) else image
|