|
| 1 | +# Copyright 2020-2022 OpenDR European Project |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +import cv2 |
| 17 | + |
| 18 | +from opendr.perception.object_detection_2d import RetinaFaceLearner |
| 19 | +from opendr.perception.object_detection_2d.datasets.transforms import\ |
| 20 | + BoundingBoxListToNumpyArray |
| 21 | +from opendr.perception.face_recognition import FaceRecognitionLearner |
| 22 | + |
| 23 | +facedetector = RetinaFaceLearner(backbone='mnet', device='cuda') |
| 24 | +facedetector.download(".", mode="pretrained") |
| 25 | +facedetector.load("./retinaface_mnet") |
| 26 | + |
| 27 | +recognizer = FaceRecognitionLearner(device='cuda', backbone='mobilefacenet', mode='backbone_only') |
| 28 | +recognizer.download(path=".") |
| 29 | +recognizer.load(".") |
| 30 | +recognizer.fit_reference('./cropped_images_path', save_path="./save_path", create_new=True) |
| 31 | + |
| 32 | +cam = cv2.VideoCapture(0) |
| 33 | +cv2.namedWindow("face recognition") |
| 34 | +font = cv2.FONT_HERSHEY_SIMPLEX |
| 35 | +fontScale = 1 |
| 36 | +color = (255, 0, 0) |
| 37 | +thickness = 2 |
| 38 | +while True: |
| 39 | + ret, frame = cam.read() |
| 40 | + if not ret: |
| 41 | + print("Failed to grab frame") |
| 42 | + break |
| 43 | + bounding_boxes = facedetector.infer(frame) |
| 44 | + if bounding_boxes: |
| 45 | + bounding_boxes_ = BoundingBoxListToNumpyArray()(bounding_boxes) |
| 46 | + boxes = bounding_boxes_[:, :4] |
| 47 | + for idx, box in enumerate(boxes): |
| 48 | + (startX, startY, endX, endY) = int(box[0]), int(box[1]), int(box[2]), int(box[3]) |
| 49 | + img = frame[startY:endY, startX:endX] |
| 50 | + result = recognizer.infer(img) |
| 51 | + if result.description != 'Not found': |
| 52 | + color = (0, 255, 0) |
| 53 | + else: |
| 54 | + color = (0, 0, 255) |
| 55 | + img = cv2.rectangle(frame, (startX, startY), (endX, endY), color, thickness) |
| 56 | + img = cv2.putText(img, result.description, (startX, endY - 10), font, |
| 57 | + fontScale, color, thickness, cv2.LINE_AA) |
| 58 | + else: |
| 59 | + img = frame |
| 60 | + cv2.imshow("face recognition", img) |
| 61 | + cv2.waitKey(1) |
| 62 | + |
| 63 | +cam.release() |
0 commit comments