brxerq commited on
Commit
a8a4269
1 Parent(s): 7048e8e

Create common_detection.py

Browse files
Files changed (1) hide show
  1. common_detection.py +41 -0
common_detection.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # common_detection.py
2
+ import cv2
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+ def perform_detection(image, interpreter, labels, input_details, output_details, height, width, floating_model):
7
+ imH, imW, _ = image.shape
8
+ image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
9
+ image_resized = cv2.resize(image_rgb, (width, height))
10
+ input_data = np.expand_dims(image_resized, axis=0)
11
+
12
+ input_mean = 127.5
13
+ input_std = 127.5
14
+ if floating_model:
15
+ input_data = (np.float32(input_data) - input_mean) / input_std
16
+
17
+ interpreter.set_tensor(input_details[0]['index'], input_data)
18
+ interpreter.invoke()
19
+
20
+ boxes = interpreter.get_tensor(output_details[0]['index'])[0]
21
+ classes = interpreter.get_tensor(output_details[1]['index'])[0]
22
+ scores = interpreter.get_tensor(output_details[2]['index'])[0]
23
+
24
+ detections = []
25
+ for i in range(len(scores)):
26
+ if (scores[i] > 0.5):
27
+ ymin = int(max(1, (boxes[i][0] * imH)))
28
+ xmin = int(max(1, (boxes[i][1] * imW)))
29
+ ymax = int(min(imH, (boxes[i][2] * imH)))
30
+ xmax = int(min(imW, (boxes[i][3] * imW)))
31
+
32
+ cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (10, 255, 0), 2)
33
+ object_name = labels[int(classes[i])]
34
+ label = f'{object_name}: {int(scores[i] * 100)}%'
35
+ labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2)
36
+ label_ymin = max(ymin, labelSize[1] + 10)
37
+ cv2.rectangle(image, (xmin, label_ymin - labelSize[1] - 10), (xmin + labelSize[0], label_ymin + baseLine - 10), (255, 255, 255), cv2.FILLED)
38
+ cv2.putText(image, label, (xmin, label_ymin - 7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)
39
+
40
+ detections.append([object_name, scores[i], xmin, ymin, xmax, ymax])
41
+ return image