| from PIL import Image | |
| import cv2 | |
| import numpy as np | |
| import io | |
| import torchvision.transforms as T | |
| def detect_face(image_bytes): | |
| nparr = np.frombuffer(image_bytes, np.uint8) | |
| img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR) | |
| gray = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY) | |
| face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") | |
| faces = face_cascade.detectMultiScale(gray, 1.3, 5) | |
| return len(faces) > 0 | |
| def preprocess_image(image_bytes): | |
| image = Image.open(io.BytesIO(image_bytes)).convert('RGB') | |
| transform = T.Compose([ | |
| T.Resize((224, 224)), | |
| T.ToTensor(), | |
| ]) | |
| return transform(image).unsqueeze(0) | |