前提・実現したいこと
OpenCVを利用してPythonでマスクの有無の検知を行いました。
ここからマスクの有無の検知数をカウントし、カウントした数値を表示したいです。
githubよりダウンロードしました
リンク内容
Python
1# USAGE 2# python detect_mask_video.py 3 4# import the necessary packages 5from tensorflow.keras.applications.mobilenet_v2 import preprocess_input 6from tensorflow.keras.preprocessing.image import img_to_array 7from tensorflow.keras.models import load_model 8from imutils.video import VideoStream 9import numpy as np 10import argparse 11import imutils 12import time 13import cv2 14import os 15 16def detect_and_predict_mask(frame, faceNet, maskNet): 17 # grab the dimensions of the frame and then construct a blob 18 # from it 19 (h, w) = frame.shape[:2] 20 blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), 21 (104.0, 177.0, 123.0)) 22 23 # pass the blob through the network and obtain the face detections 24 faceNet.setInput(blob) 25 detections = faceNet.forward() 26 27 # initialize our list of faces, their corresponding locations, 28 # and the list of predictions from our face mask network 29 faces = [] 30 locs = [] 31 preds = [] 32 33 # loop over the detections 34 for i in range(0, detections.shape[2]): 35 # extract the confidence (i.e., probability) associated with 36 # the detection 37 confidence = detections[0, 0, i, 2] 38 39 # filter out weak detections by ensuring the confidence is 40 # greater than the minimum confidence 41 if confidence > args["confidence"]: 42 # compute the (x, y)-coordinates of the bounding box for 43 # the object 44 box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) 45 (startX, startY, endX, endY) = box.astype("int") 46 47 # ensure the bounding boxes fall within the dimensions of 48 # the frame 49 (startX, startY) = (max(0, startX), max(0, startY)) 50 (endX, endY) = (min(w - 1, endX), min(h - 1, endY)) 51 52 # extract the face ROI, convert it from BGR to RGB channel 53 # ordering, resize it to 224x224, and preprocess it 54 face = frame[startY:endY, startX:endX] 55 if face.any(): 56 face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB) 57 face = cv2.resize(face, (224, 224)) 58 face = img_to_array(face) 59 face = preprocess_input(face) 60 61 # only make a predictions if at least one face was detected 62 if len(faces) > 0: 63 # for faster inference we'll make batch predictions on *all* 64 # faces at the same time rather than one-by-one predictions 65 # in the above `for` loop 66 faces = np.array(faces, dtype="float32") 67 preds = maskNet.predict(faces, batch_size=32) 68 69 # return a 2-tuple of the face locations and their corresponding 70 # locations 71 return (locs, preds) 72 73# construct the argument parser and parse the arguments 74ap = argparse.ArgumentParser() 75ap.add_argument("-f", "--face", type=str, 76 default="face_detector", 77 help="path to face detector model directory") 78ap.add_argument("-m", "--model", type=str, 79 default="mask_detector.model", 80 help="path to trained face mask detector model") 81ap.add_argument("-c", "--confidence", type=float, default=0.5, 82 help="minimum probability to filter weak detections") 83args = vars(ap.parse_args()) 84 85# load our serialized face detector model from disk 86print("[INFO] loading face detector model...") 87prototxtPath = os.path.sep.join([args["face"], "deploy.prototxt"]) 88weightsPath = os.path.sep.join([args["face"], 89 "res10_300x300_ssd_iter_140000.caffemodel"]) 90faceNet = cv2.dnn.readNet(prototxtPath, weightsPath) 91 92# load the face mask detector model from disk 93print("[INFO] loading face mask detector model...") 94maskNet = load_model(args["model"]) 95 96# initialize the video stream and allow the camera sensor to warm up 97print("[INFO] starting video stream...") 98vs = VideoStream(src=0).start() 99time.sleep(2.0) 100 101# loop over the frames from the video stream 102while True: 103 # grab the frame from the threaded video stream and resize it 104 # to have a maximum width of 400 pixels 105 frame = vs.read() 106 frame = imutils.resize(frame, width=400) 107 108 # detect faces in the frame and determine if they are wearing a 109 # face mask or not 110 (locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet) 111 112 # loop over the detected face locations and their corresponding 113 # locations 114 for (box, pred) in zip(locs, preds): 115 # unpack the bounding box and predictions 116 (startX, startY, endX, endY) = box 117 (mask, withoutMask) = pred 118 119 # determine the class label and color we'll use to draw 120 # the bounding box and text 121 label = "Mask" if mask > withoutMask else "No Mask" 122 color = (0, 255, 0) if label == "Mask" else (0, 0, 255) 123 124 # include the probability in the label 125 label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100) 126 127 # display the label and bounding box rectangle on the output 128 # frame 129 cv2.putText(frame, label, (startX, startY - 10), 130 cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2) 131 cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2) 132 133 # show the output frame 134 cv2.imshow("Frame", frame) 135 key = cv2.waitKey(1) & 0xFF 136 137 # if the `q` key was pressed, break from the loop 138 if key == ord("q"): 139 break 140 141# do a bit of cleanup 142cv2.destroyAllWindows() 143vs.stop() 144
pythonのコードの一番最初の行のすぐ上に
```python
だけの行を追加してください
また、pythonのコードの一番最後の行のすぐ下に
```
だけの行を追加してください
または、
https://teratail.storage.googleapis.com/uploads/contributed_images/56957fe805d9d7befa7dba6a98676d2b.gif
を見て、そのようにしてみてください
現状、コードがとても読み辛いです
質問にコードを載せる際に上記をやってくれたら、他人がコードを読みやすくなり、コードの実行による現象確認もやりやすくなるので、回答されやすくなります
何もわからないのだったらpythonにこだわらずご自分の得意な言語で
やった方がいいかと思います。
あなたの回答
tips
プレビュー