Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

Detect_Video.py 3.7 KB

You have to be logged in to leave a comment. Sign In
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
  1. from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
  2. from tensorflow.keras.preprocessing.image import img_to_array
  3. from tensorflow.keras.models import load_model
  4. from imutils.video import VideoStream
  5. import numpy as np
  6. import argparse
  7. import imutils
  8. import time
  9. import cv2
  10. import os
  11. import time
  12. from pygame import mixer
  13. mixer.init()
  14. sound = mixer.Sound('voice/alarm_1.wav')
  15. IMAGE = "images"
  16. FACE = "face_detector"
  17. MODEL = "mask_detector.model"
  18. CONFIDENCE = 0.5
  19. def detect_and_predict_mask(frame, faceNet, maskNet):
  20. (h, w) = frame.shape[:2]
  21. blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300),(104.0, 177.0, 123.0))
  22. faceNet.setInput(blob)
  23. # 透過模型向前傳遞
  24. detections = faceNet.forward()
  25. faces = []
  26. locs = []
  27. preds = []
  28. for i in range(0, detections.shape[2]):
  29. confidence = detections[0, 0, i, 2]
  30. # 取信賴程度>50%
  31. if confidence > CONFIDENCE:
  32. # 取得人臉座標框
  33. box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
  34. (startX, startY, endX, endY) = box.astype("int")
  35. (startX, startY) = (max(0, startX), max(0, startY))
  36. (endX, endY) = (min(w - 1, endX), min(h - 1, endY))
  37. # 影像resize 224*224 符合 MobileNetV2
  38. face = frame[startY:endY, startX:endX]
  39. face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
  40. face = cv2.resize(face, (224, 224))
  41. face = img_to_array(face)
  42. face = preprocess_input(face)
  43. # 複數個臉,把座標全部存在locs中
  44. faces.append(face)
  45. locs.append((startX, startY, endX, endY))
  46. # 人臉的數量>0,才進行預測
  47. if len(faces) > 0:
  48. faces = np.array(faces, dtype="float32")
  49. preds = maskNet.predict(faces, batch_size=32)
  50. # 回傳框框的(座標,是否戴口罩)
  51. return (locs, preds)
  52. prototxtPath = os.path.sep.join([FACE, "deploy.prototxt"])
  53. weightsPath = os.path.sep.join([FACE, "res10_300x300_ssd_iter_140000.caffemodel"])
  54. faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)
  55. maskNet = load_model(MODEL)
  56. print("[INFO] Starting stream ......")
  57. vs = VideoStream(src=0).start()
  58. time.sleep(2.0)
  59. # 迴圈視訊串流,反覆執行
  60. while True:
  61. # 指定畫面 400 pixels
  62. frame = vs.read()
  63. frame = imutils.resize(frame, width=400)
  64. # 取得座標&是否戴口罩的預測結果
  65. try:
  66. (locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet)
  67. for (box, pred) in zip(locs, preds):
  68. # Bounding box 座標
  69. (startX, startY, endX, endY) = box
  70. # mask & withoutMaks機率
  71. (mask, withoutMask) = pred
  72. # 口罩大於沒口罩顯示藍色框
  73. # 沒口罩大於口罩顯示紅色框
  74. label = "Mask" if mask > withoutMask else "No Mask"
  75. color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
  76. label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)
  77. if mask < withoutMask:
  78. sound.play()
  79. # 將預測用文字顯示在畫面上
  80. cv2.putText(frame, label, (startX, startY - 10),
  81. cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
  82. cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)
  83. except Exception as ex:
  84. print('Running ......')
  85. # show the output frame
  86. cv2.imshow("Frame", frame)
  87. key = cv2.waitKey(1) & 0xFF
  88. # if the `q` key was pressed, break from the loop
  89. if key == ord("q"):
  90. break
  91. # do a bit of cleanup
  92. cv2.destroyAllWindows()
  93. vs.stop()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...