Spaces:
Runtime error
Runtime error
JWPencils commited on
Commit ·
bbf6bbd
1
Parent(s): 3c5f840
Add application file
Browse files- app.py +224 -0
- fast_ai_model_resnet18_new_labeling.pth +3 -0
- requirements.txt +11 -0
app.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastcore.all import *
|
| 2 |
+
from fastai.vision.all import *
|
| 3 |
+
|
| 4 |
+
learn = load_learner('./fast_ai_model_resnet18_new_labeling.pth')
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import torch
|
| 9 |
+
import torchvision.transforms as tt
|
| 10 |
+
import numpy as np
|
| 11 |
+
# from facenet_pytorch import MTCNN
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
from retinaface import RetinaFace
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
| 21 |
+
|
| 22 |
+
def load_checkpoint(filepath):
|
| 23 |
+
checkpoint = torch.load(filepath, device)
|
| 24 |
+
model = checkpoint['model']
|
| 25 |
+
model.load_state_dict(checkpoint['state_dict'], strict=False)
|
| 26 |
+
for parameter in model.parameters():
|
| 27 |
+
parameter.requires_grad = False
|
| 28 |
+
|
| 29 |
+
model.eval()
|
| 30 |
+
return model
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# filepath = './models/9.pth'
|
| 34 |
+
# loaded_model = load_checkpoint(filepath)
|
| 35 |
+
|
| 36 |
+
loaded_model = learn
|
| 37 |
+
|
| 38 |
+
class FaceDetector(object):
|
| 39 |
+
"""
|
| 40 |
+
Face detector class
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, detector,loaded_model,image=None):
|
| 44 |
+
self.detector = detector
|
| 45 |
+
self.loaded_model=loaded_model
|
| 46 |
+
self.image = image
|
| 47 |
+
|
| 48 |
+
def _draw(self, frame, boxes, probs, landmarks):
|
| 49 |
+
"""
|
| 50 |
+
Draw landmarks and boxes for each face detected
|
| 51 |
+
"""
|
| 52 |
+
try:
|
| 53 |
+
for box, prob, ld in zip(boxes, probs, landmarks):
|
| 54 |
+
# Draw rectangle on frame
|
| 55 |
+
box = box.astype('int')
|
| 56 |
+
ld = ld.astype('int')
|
| 57 |
+
cv2.rectangle(frame,
|
| 58 |
+
(box[0], box[1]),
|
| 59 |
+
(box[2], box[3]),
|
| 60 |
+
(0, 0, 255),
|
| 61 |
+
thickness=2)
|
| 62 |
+
|
| 63 |
+
# Show probability
|
| 64 |
+
cv2.putText(frame, str(
|
| 65 |
+
prob), (box[2], box[3]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
|
| 66 |
+
|
| 67 |
+
# Draw landmarks
|
| 68 |
+
cv2.circle(frame, tuple(ld[0]), 5, (0, 0, 255), -1)
|
| 69 |
+
cv2.circle(frame, tuple(ld[1]), 5, (0, 0, 255), -1)
|
| 70 |
+
cv2.circle(frame, tuple(ld[2]), 5, (0, 0, 255), -1)
|
| 71 |
+
cv2.circle(frame, tuple(ld[3]), 5, (0, 0, 255), -1)
|
| 72 |
+
cv2.circle(frame, tuple(ld[4]), 5, (0, 0, 255), -1)
|
| 73 |
+
except Exception as e:
|
| 74 |
+
# print(e)
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
return frame
|
| 78 |
+
|
| 79 |
+
# def _capture(self,frame,boxes,probs,landmarks):
|
| 80 |
+
# sampleNum = 0
|
| 81 |
+
# while True:
|
| 82 |
+
# try:
|
| 83 |
+
# sampleNum = sampleNum+1
|
| 84 |
+
# boxes = boxes.astype('int')
|
| 85 |
+
# face = frame[boxes[0,1]:boxes[0,3],boxes[0,0]:boxes[0,2]]
|
| 86 |
+
# cv2.imwrite(str(sampleNum) + ".jpg",face)
|
| 87 |
+
# except Exception as e:
|
| 88 |
+
# # print(e)
|
| 89 |
+
# pass
|
| 90 |
+
# if sampleNum >2:
|
| 91 |
+
# break
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _recognize(self,loaded_model,frame,boxes):
|
| 95 |
+
try:
|
| 96 |
+
|
| 97 |
+
for box in boxes:
|
| 98 |
+
# box = box.astype('int')
|
| 99 |
+
# face = frame[box[0][1]:box[0][3],box[0][0]:box[0][2]]
|
| 100 |
+
face = frame[box[1]:box[3],box[0]:box[2]]
|
| 101 |
+
# pil_image = Image.fromarray(face, mode="RGB")
|
| 102 |
+
|
| 103 |
+
labels,_,probs = loaded_model.predict(face)
|
| 104 |
+
# label= 1
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
label = labels if (probs[np.argmax(probs)] > 0.8) else "Unknown"
|
| 110 |
+
probs = probs[np.argmax(probs)] if (probs[np.argmax(probs)] > 0.8) else np.nan
|
| 111 |
+
|
| 112 |
+
# if prediction == 0:
|
| 113 |
+
# label = "Fadli"
|
| 114 |
+
# elif prediction == 1:
|
| 115 |
+
# label = "Aziz"
|
| 116 |
+
# elif prediction == 2:
|
| 117 |
+
# label = "Eka"
|
| 118 |
+
# else:
|
| 119 |
+
# label = "Unknown"
|
| 120 |
+
_ = "" if probs == np.nan else ": {:.2f}".format(float(probs))
|
| 121 |
+
|
| 122 |
+
cv2.putText(frame, label + _ , (box[2], box[3]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
|
| 123 |
+
|
| 124 |
+
# cv2.putText(frame,str(["{:.2f}".format(x)for x in probs]), (box[2]-100, box[3]+30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2, cv2.LINE_AA)
|
| 125 |
+
|
| 126 |
+
# cv2.putText(frame,"{:.2f}".format(float(probs[np.argmax(probs)])), (box[2]-100, box[3]+30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2, cv2.LINE_AA)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
cv2.rectangle(frame,
|
| 132 |
+
(box[0], box[1]),
|
| 133 |
+
(box[2], box[3]),
|
| 134 |
+
(0, 0, 255),
|
| 135 |
+
thickness=2)
|
| 136 |
+
# cv2.putText(frame, str(
|
| 137 |
+
# prediction), (box[0][2], box[0][3]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
|
| 138 |
+
return frame
|
| 139 |
+
except Exception as e:
|
| 140 |
+
print(e,'eaea')
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
def run_on_image(self,image):
|
| 144 |
+
frame = image
|
| 145 |
+
try:
|
| 146 |
+
# detect face box, probability and landmarks
|
| 147 |
+
json_face = self.detector.detect_faces(frame)
|
| 148 |
+
|
| 149 |
+
# boxes = [json_face['face_{}'.format(x)]['facial_area'] for x in range(1,len(json_face)+1)]
|
| 150 |
+
# probs = ["{:.2f}".format(json_face['face_{}'.format(x)]['score']) for x in range(1,len(json_face)+1)]
|
| 151 |
+
# landmarks = [json_face['face_{}'.format(x)]['landmarks'] for x in range(1,len(json_face)+1)]
|
| 152 |
+
|
| 153 |
+
boxes = []
|
| 154 |
+
probs = []
|
| 155 |
+
landmarks = []
|
| 156 |
+
for key, value in json_face.items():
|
| 157 |
+
boxes.append(value['facial_area'])
|
| 158 |
+
probs.append("{:.2f}".format(value['score']))
|
| 159 |
+
landmarks.append(value['landmarks'])
|
| 160 |
+
|
| 161 |
+
return Image.fromarray(self._recognize(loaded_model,frame,boxes))
|
| 162 |
+
# self._draw(frame, boxes, probs, landmarks)
|
| 163 |
+
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(e)
|
| 166 |
+
pass
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def run(self):
|
| 170 |
+
"""
|
| 171 |
+
Run the FaceDetector and draw landmarks and boxes around detected faces
|
| 172 |
+
"""
|
| 173 |
+
cap = cv2.VideoCapture(0)
|
| 174 |
+
|
| 175 |
+
while True:
|
| 176 |
+
ret, frame = cap.read()
|
| 177 |
+
try:
|
| 178 |
+
# detect face box, probability and landmarks
|
| 179 |
+
json_face = self.detector.detect_faces(frame)
|
| 180 |
+
|
| 181 |
+
# boxes = [json_face['face_{}'.format(x)]['facial_area'] for x in range(1,len(json_face)+1)]
|
| 182 |
+
# probs = ["{:.2f}".format(json_face['face_{}'.format(x)]['score']) for x in range(1,len(json_face)+1)]
|
| 183 |
+
# landmarks = [json_face['face_{}'.format(x)]['landmarks'] for x in range(1,len(json_face)+1)]
|
| 184 |
+
|
| 185 |
+
boxes = []
|
| 186 |
+
probs = []
|
| 187 |
+
landmarks = []
|
| 188 |
+
for key, value in json_face.items():
|
| 189 |
+
boxes.append(value['facial_area'])
|
| 190 |
+
probs.append("{:.2f}".format(value['score']))
|
| 191 |
+
landmarks.append(value['landmarks'])
|
| 192 |
+
|
| 193 |
+
self._recognize(loaded_model,frame,boxes)
|
| 194 |
+
# self._draw(frame, boxes, probs, landmarks)
|
| 195 |
+
|
| 196 |
+
except Exception as e:
|
| 197 |
+
print(e)
|
| 198 |
+
pass
|
| 199 |
+
|
| 200 |
+
# Show the frame
|
| 201 |
+
cv2.imshow('Face Detection', frame)
|
| 202 |
+
|
| 203 |
+
if cv2.waitKey(1) & 0xFF == ord('q'):
|
| 204 |
+
break
|
| 205 |
+
|
| 206 |
+
cap.release()
|
| 207 |
+
cv2.destroyAllWindows()
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# Run the app
|
| 211 |
+
|
| 212 |
+
# fcd = FaceDetector(RetinaFace,loaded_model)
|
| 213 |
+
detector = RetinaFace
|
| 214 |
+
# fcd = FaceDetector(detector,loaded_model)
|
| 215 |
+
# fcd.run()
|
| 216 |
+
|
| 217 |
+
fcd = FaceDetector(detector,loaded_model)
|
| 218 |
+
|
| 219 |
+
import gradio as gr
|
| 220 |
+
|
| 221 |
+
gr.Interface(fn=fcd.run_on_image,
|
| 222 |
+
inputs=gr.Image(),
|
| 223 |
+
outputs=gr.Image(),
|
| 224 |
+
).launch()
|
fast_ai_model_resnet18_new_labeling.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6799a295f99c4fe0a40e75ca174a7516ce6ea912228a9056ceee5a5683d5b818
|
| 3 |
+
size 46969633
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastai==2.7.8
|
| 2 |
+
fastapi==0.85.1
|
| 3 |
+
fastcore==1.5.27
|
| 4 |
+
fastdownload==0.0.7
|
| 5 |
+
fastprogress==1.0.3
|
| 6 |
+
retina-face==0.0.12
|
| 7 |
+
torch==1.12.1
|
| 8 |
+
torchaudio==0.12.1
|
| 9 |
+
torchvision==0.13.1
|
| 10 |
+
numpy==1.23.2
|
| 11 |
+
Pillow==9.2.0
|