George commited on
Commit
e42312a
1 Parent(s): 4dbba62

add app.py

Browse files
Files changed (2) hide show
  1. app.py +89 -0
  2. requirements.txt +2 -1
app.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import khandy
3
+ import numpy as np
4
+ import gradio as gr
5
+ from PIL import Image
6
+ from insectid import InsectDetector
7
+ from insectid import InsectIdentifier
8
+
9
+
10
+ def inference(filename):
11
+ detector = InsectDetector()
12
+ identifier = InsectIdentifier()
13
+ image = khandy.imread(filename)
14
+
15
+ if image is None:
16
+ return None
17
+
18
+ if max(image.shape[:2]) > 1280:
19
+ image = khandy.resize_image_long(image, 1280)
20
+
21
+ image_for_draw = image.copy()
22
+ image_height, image_width = image.shape[:2]
23
+ boxes, confs, classes = detector.detect(image)
24
+
25
+ for box, conf, class_ind in zip(boxes, confs, classes):
26
+ box = box.astype(np.int32)
27
+ box_width = box[2] - box[0] + 1
28
+ box_height = box[3] - box[1] + 1
29
+
30
+ if box_width < 30 or box_height < 30:
31
+ continue
32
+
33
+ cropped = khandy.crop_or_pad(image, box[0], box[1], box[2], box[3])
34
+ results = identifier.identify(cropped)
35
+ print(results[0])
36
+ prob = results[0]['probability']
37
+
38
+ if prob < 0.10:
39
+ text = 'Unknown'
40
+ else:
41
+ text = '{}: {:.2f}%'.format(
42
+ results[0]['latin_name'],
43
+ 100.0 * results[0]['probability']
44
+ )
45
+
46
+ position = [box[0] + 2, box[1] - 20]
47
+ position[0] = min(max(position[0], 0), image_width)
48
+ position[1] = min(max(position[1], 0), image_height)
49
+ cv2.rectangle(
50
+ image_for_draw,
51
+ (box[0], box[1]),
52
+ (box[2], box[3]),
53
+ (0, 255, 0),
54
+ 2
55
+ )
56
+
57
+ image_for_draw = khandy.draw_text(
58
+ image_for_draw,
59
+ text,
60
+ position,
61
+ font='simsun.ttc',
62
+ font_size=15
63
+ )
64
+
65
+ return Image.fromarray(image_for_draw[:, :, ::-1], mode='RGB')
66
+
67
+
68
+ with gr.Blocks() as demo:
69
+ with gr.Tab("Image"):
70
+ gr.Markdown("## Insect Inference on Image")
71
+ with gr.Row():
72
+ image_input = gr.Image(
73
+ type='filepath',
74
+ label="Input Image",
75
+ source="upload"
76
+ )
77
+
78
+ image_output = gr.Image(
79
+ type='pil',
80
+ label="Output Image",
81
+ source="canvas"
82
+ )
83
+
84
+ text_button = gr.Button("Detect")
85
+
86
+ text_button.click(inference, inputs=image_input, outputs=image_output)
87
+
88
+
89
+ demo.launch()
requirements.txt CHANGED
@@ -3,4 +3,5 @@ numpy>=1.11.1
3
  lxml
4
  requests
5
  onnxruntime
6
- Pillow
 
 
3
  lxml
4
  requests
5
  onnxruntime
6
+ Pillow
7
+ gradio