Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Deep-Learning-with-OpenCV-DNN-Module/python/detection/detect_img.py
3150 views
1
import cv2
2
import numpy as np
3
4
# load the COCO class names
5
with open('../../input/object_detection_classes_coco.txt', 'r') as f:
6
class_names = f.read().split('\n')
7
8
# get a different color array for each of the classes
9
COLORS = np.random.uniform(0, 255, size=(len(class_names), 3))
10
11
# load the DNN model
12
model = cv2.dnn.readNet(model='../../input/frozen_inference_graph.pb',
13
config='../../input/ssd_mobilenet_v2_coco_2018_03_29.pbtxt.txt',
14
framework='TensorFlow')
15
16
# read the image from disk
17
image = cv2.imread('../../input/image_2.jpg')
18
image_height, image_width, _ = image.shape
19
# create blob from image
20
blob = cv2.dnn.blobFromImage(image=image, size=(300, 300), mean=(104, 117, 123),
21
swapRB=True)
22
# create blob from image
23
model.setInput(blob)
24
# forward pass through the model to carry out the detection
25
output = model.forward()
26
27
# loop over each of the detection
28
for detection in output[0, 0, :, :]:
29
# extract the confidence of the detection
30
confidence = detection[2]
31
# draw bounding boxes only if the detection confidence is above...
32
# ... a certain threshold, else skip
33
if confidence > .4:
34
# get the class id
35
class_id = detection[1]
36
# map the class id to the class
37
class_name = class_names[int(class_id)-1]
38
color = COLORS[int(class_id)]
39
# get the bounding box coordinates
40
box_x = detection[3] * image_width
41
box_y = detection[4] * image_height
42
# get the bounding box width and height
43
box_width = detection[5] * image_width
44
box_height = detection[6] * image_height
45
# draw a rectangle around each detected object
46
cv2.rectangle(image, (int(box_x), int(box_y)), (int(box_width), int(box_height)), color, thickness=2)
47
# put the FPS text on top of the frame
48
cv2.putText(image, class_name, (int(box_x), int(box_y - 5)), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
49
50
cv2.imshow('image', image)
51
cv2.imwrite('../../outputs/image_result.jpg', image)
52
cv2.waitKey(0)
53
cv2.destroyAllWindows()
54
55