dyguay commited on
Commit
f52975b
·
1 Parent(s): f817066

Upload ObjectDetector.py

Browse files
Files changed (1) hide show
  1. ObjectDetector.py +51 -0
ObjectDetector.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2 as cv
2
+ import numpy as np
3
+
4
+
5
+ classNames = ["background", "person", "bicycle", "car", "motorcycle",
6
+ "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant",
7
+ "unknown", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse",
8
+ "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "unknown", "backpack",
9
+ "umbrella", "unknown", "unknown", "handbag", "tie", "suitcase", "frisbee", "skis",
10
+ "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard",
11
+ "surfboard", "tennis racket", "bottle", "unknown", "wine glass", "cup", "fork", "knife",
12
+ "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog",
13
+ "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "unknown", "dining table",
14
+ "unknown", "unknown", "toilet", "unknown", "tv", "laptop", "mouse", "remote", "keyboard",
15
+ "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "unknown",
16
+ "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush" ]
17
+
18
+
19
+ class Detector:
20
+ def __init__(self):
21
+ global cvNet, colors
22
+ cvNet = cv.dnn.readNetFromTensorflow('frozen_inference_graph.pb',
23
+ 'ssd_mobilenet_v1_coco_2017_11_17.pbtxt')
24
+ np.random.seed(543210)
25
+ colors = np.random.uniform(0,255,size=(len(classNames),3))
26
+
27
+ def detectObject(self, img):
28
+ cvNet.setInput(cv.dnn.blobFromImage(cv.resize(img, (300, 300)), 0.007843, (300, 300), 130))
29
+ detections = cvNet.forward()
30
+ cols = img.shape[1]
31
+ rows = img.shape[0]
32
+
33
+ for i in range(detections.shape[2]):
34
+ confidence = detections[0, 0, i, 2]
35
+ if confidence > 0.3:
36
+ class_id = int(detections[0, 0, i, 1])
37
+
38
+ xLeftBottom = int(detections[0, 0, i, 3] * cols)
39
+ yLeftBottom = int(detections[0, 0, i, 4] * rows)
40
+ xRightTop = int(detections[0, 0, i, 5] * cols)
41
+ yRightTop = int(detections[0, 0, i, 6] * rows)
42
+
43
+ cv.rectangle(img, (xLeftBottom, yLeftBottom), (xRightTop, yRightTop),colors[class_id], 7)
44
+ if class_id in range(len(classNames)):
45
+ label = classNames[class_id] + ": " + str(confidence)
46
+ labelSize, _ = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX,1.5, 4)
47
+ yLeftBottom = max(yLeftBottom, labelSize[1])
48
+ cv.putText(img, label, (xLeftBottom, yLeftBottom-30 if yLeftBottom > 60 else yLeftBottom+30),\
49
+ cv.FONT_HERSHEY_SIMPLEX, 1.5, colors[class_id], 5)
50
+
51
+ return img