Create helper.py
Browse files
helper.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
import matplotlib.pyplot as plt
|
3 |
+
import requests
|
4 |
+
import inflect
|
5 |
+
from PIL import Image
|
6 |
+
def render_results_in_image(in_pil_img, in_results):
|
7 |
+
plt.figure(figsize=(16, 10))
|
8 |
+
plt.imshow(in_pil_img)
|
9 |
+
|
10 |
+
ax = plt.gca()
|
11 |
+
|
12 |
+
for prediction in in_results:
|
13 |
+
|
14 |
+
x, y = prediction['box']['xmin'], prediction['box']['ymin']
|
15 |
+
w = prediction['box']['xmax'] - prediction['box']['xmin']
|
16 |
+
h = prediction['box']['ymax'] - prediction['box']['ymin']
|
17 |
+
|
18 |
+
ax.add_patch(plt.Rectangle((x, y),
|
19 |
+
w,
|
20 |
+
h,
|
21 |
+
fill=False,
|
22 |
+
color="green",
|
23 |
+
linewidth=2))
|
24 |
+
ax.text(
|
25 |
+
x,
|
26 |
+
y,
|
27 |
+
f"{prediction['label']}: {round(prediction['score']*100, 1)}%",
|
28 |
+
color='red'
|
29 |
+
)
|
30 |
+
|
31 |
+
plt.axis("off")
|
32 |
+
|
33 |
+
# Save the modified image to a BytesIO object
|
34 |
+
img_buf = io.BytesIO()
|
35 |
+
plt.savefig(img_buf, format='png',
|
36 |
+
bbox_inches='tight',
|
37 |
+
pad_inches=0)
|
38 |
+
img_buf.seek(0)
|
39 |
+
modified_image = Image.open(img_buf)
|
40 |
+
|
41 |
+
# Close the plot to prevent it from being displayed
|
42 |
+
plt.close()
|
43 |
+
|
44 |
+
return modified_image
|