Spaces:
Sleeping
Sleeping
Update services/detection.py
Browse files- services/detection.py +47 -0
services/detection.py
CHANGED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
|
| 5 |
+
class FaceDetector:
|
| 6 |
+
def __init__(self, model_path="models/face_detection.tflite"):
|
| 7 |
+
self.interpreter = tf.lite.Interpreter(model_path=model_path)
|
| 8 |
+
self.interpreter.allocate_tensors()
|
| 9 |
+
|
| 10 |
+
self.input_details = self.interpreter.get_input_details()
|
| 11 |
+
self.output_details = self.interpreter.get_output_details()
|
| 12 |
+
|
| 13 |
+
def detect_faces(self, image):
|
| 14 |
+
"""كشف الوجوه في الصورة"""
|
| 15 |
+
# تحضير الصورة
|
| 16 |
+
input_shape = self.input_details[0]['shape'][1:3]
|
| 17 |
+
img_resized = cv2.resize(image, (input_shape[1], input_shape[0]))
|
| 18 |
+
img_normalized = img_resized.astype(np.float32) / 255.0
|
| 19 |
+
img_input = np.expand_dims(img_normalized, axis=0)
|
| 20 |
+
|
| 21 |
+
# تنفيذ النموذج
|
| 22 |
+
self.interpreter.set_tensor(self.input_details[0]['index'], img_input)
|
| 23 |
+
self.interpreter.invoke()
|
| 24 |
+
|
| 25 |
+
# استخراج النتائج
|
| 26 |
+
boxes = self.interpreter.get_tensor(self.output_details[0]['index'])
|
| 27 |
+
scores = self.interpreter.get_tensor(self.output_details[1]['index'])
|
| 28 |
+
|
| 29 |
+
return self._process_detections(boxes[0], scores[0], image.shape)
|
| 30 |
+
|
| 31 |
+
def _process_detections(self, boxes, scores, image_shape):
|
| 32 |
+
"""معالجة صناديق الكشف"""
|
| 33 |
+
h, w = image_shape[:2]
|
| 34 |
+
faces = []
|
| 35 |
+
|
| 36 |
+
for i, score in enumerate(scores):
|
| 37 |
+
if score > 0.5: # عتبة الثقة
|
| 38 |
+
y1, x1, y2, x2 = boxes[i]
|
| 39 |
+
x1, y1 = int(x1 * w), int(y1 * h)
|
| 40 |
+
x2, y2 = int(x2 * w), int(y2 * h)
|
| 41 |
+
|
| 42 |
+
faces.append({
|
| 43 |
+
'bbox': [x1, y1, x2, y2],
|
| 44 |
+
'confidence': float(score)
|
| 45 |
+
})
|
| 46 |
+
|
| 47 |
+
return faces
|