-
Notifications
You must be signed in to change notification settings - Fork 0
/
object_detection_using_opencv.py
88 lines (73 loc) · 2.41 KB
/
object_detection_using_opencv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# -*- coding: utf-8 -*-
"""Object Detection using opencv.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Lx7qWd6nJpW8G64o_VZyHWmypwBpaQOT
"""
import cv2
import matplotlib.pyplot as plt
cnfig_file='ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
frozen_model='frozen_inefrencee_graph.pb'
model= cv2.dnn_DetectionModel(frozen_model,cnfig_file)
classLabels=[]
file_name='labels.txt'
with open(file_name,'rt') as fpt:
classLabels=fpt.read().rstrip('\n').split('\n')
print(classLabels)
print(len(classLabels))
model.setInputSize(320,320)
model.setInputScale(1.0/127.5)
model.setInputMean((127.5,127,5,127.5))
model.setInputSwapRB(True)
image = cv2.imread('image.jpg')
plt.imshow(image)
plt.axis('off') # This line is to turn off axis labels if not needed
plt.show()
image = cv2.imread('image.jpg')
# Assuming 'model' is your cv2.dnn.DetectionModel
Classindex, confidence, bbox = model.detect(image, confThreshold=0.5)
print(Classindex)
font_scale = 3
font = cv2.FONT_HERSHEY_PLAIN
for Classind, conf, boxes in zip(Classindex.flatten(), confidence.flatten(), bbox):
cv2.rectangle(image, boxes, (255, 0, 0), 2)
cv2.putText(
image,
classLabels[Classind - 1],
(boxes[0] + 40, boxes[1] + 40),
font,
fontScale=font_scale,
color=(0, 255, 0),
thickness=3
)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
cap=cv2.VideoCapture('output.mp4')
if not cap.isOpened():
cap=cv2.VideoCapture(0)
if not cap.isOpened():
raise IOError('Cant open the video')
font_scale=3
font=cv2.FONT_HERSHEY_PLAIN
while True:
ret, frame = cap.read()
classIndex, confidence, bbox = model.detect(frame, confThreshold=0.55)
print(classIndex)
if len(classIndex) != 0:
for ClassInd, conf, boxes in zip(classIndex.flatten(), confidence.flatten(), bbox):
if ClassInd <= 80:
cv2.rectangle(frame, boxes, (255, 0, 0), 2)
cv2.putText(
frame,
classLabels[ClassInd - 1],
(boxes[0] + 10, boxes[1] + 40),
font,
fontScale=font_scale,
color=(0, 255, 0),
thickness=3
)
from google.colab.patches import cv2_imshow
cv2_imshow(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()