-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_dnn.py
More file actions
48 lines (36 loc) · 1.64 KB
/
app_dnn.py
File metadata and controls
48 lines (36 loc) · 1.64 KB
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
import numpy as np
import cv2
# Load the pre-trained model
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe('deploy.prototxt.txt', 'res10_300x300_ssd_iter_140000.caffemodel')
# Open a connection to the webcam (use 0 for the default camera)
cap = cv2.VideoCapture(0)
count = 0
while True:
# Read a frame from the webcam
ret, frame = cap.read()
# Resize the frame to a fixed 300x300 pixels and normalize it
(h, w) = frame.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
# Pass the blob through the network and obtain the detections
net.setInput(blob)
detections = net.forward()
# Loop over the detections
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
# Filter out weak detections
if confidence > 0.5: # Adjust the confidence threshold as needed
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
text = "{:.2f}%".format(confidence * 100) + ' Count ' + str(count)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2)
cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
# Display the output frame
cv2.imshow("Webcam", frame)
# Break the loop if 'q' key is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the webcam and close all OpenCV windows
cap.release()
cv2.destroyAllWindows()