Spaces:
Sleeping
Sleeping
File size: 5,726 Bytes
289811c c42ed8f 289811c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
import gradio as gr
import cv2
import numpy as np
from PIL import Image
# Load the face cascade classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
def detect_faces(image):
"""
Detect faces in the input image using Haar Cascade Classifier
Args:
image: Input image (numpy array or PIL Image)
Returns:
tuple: (processed_image, face_count, status_message)
"""
if image is None:
return None, "Please capture or upload an image first"
# Convert PIL Image to numpy array if needed
if isinstance(image, Image.Image):
image = np.array(image)
# Ensure image is in the correct format
if len(image.shape) == 2: # Grayscale
image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
elif image.shape[2] == 4: # RGBA
image = cv2.cvtColor(image, cv2.COLOR_RGBA2BGR)
elif image.shape[2] == 3: # RGB
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# Convert to grayscale for detection
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw rectangles around detected faces
result_image = image.copy()
for (x, y, w, h) in faces:
cv2.rectangle(result_image, (x, y), (x+w, y+h), (0, 255, 0), 3)
# Convert back to RGB for display
result_image = cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB)
# Create status message
if len(faces) == 0:
status = "β No faces detected"
elif len(faces) == 1:
status = "β
1 face detected"
else:
status = f"β
{len(faces)} faces detected"
return result_image, status
def process_image(image):
"""Process uploaded or captured image"""
return detect_faces(image)
# Custom CSS for better mobile experience
custom_css = """
.gradio-container {
max-width: 100% !important;
}
#camera-input {
max-width: 100%;
}
.output-image {
max-width: 100%;
height: auto;
}
"""
# Create Gradio interface
with gr.Blocks(title="Face Detection App") as demo:
gr.HTML(f"<style>{custom_css}</style>")
gr.Markdown(
"""
# πΈ Face Detection App
### Detect faces using your phone's camera or upload an image
This app uses OpenCV's Haar Cascade Classifier for real-time face detection.
"""
)
with gr.Tabs():
# Tab 1: Camera Input (Best for phones)
with gr.Tab("π± Phone Camera"):
gr.Markdown("### Capture a photo using your phone's camera")
gr.Markdown("*Tip: Grant camera permissions when prompted*")
with gr.Row():
with gr.Column():
camera_input = gr.Image(
sources=["webcam"],
type="numpy",
label="Camera Input"
)
camera_btn = gr.Button("π Detect Faces", variant="primary", size="lg")
with gr.Column():
camera_output = gr.Image(label="Detected Faces", elem_classes=["output-image"])
camera_status = gr.Textbox(label="Status", interactive=False)
camera_btn.click(
fn=process_image,
inputs=[camera_input],
outputs=[camera_output, camera_status]
)
# Tab 2: Upload Image
with gr.Tab("π€ Upload Image"):
gr.Markdown("### Upload an image from your device")
with gr.Row():
with gr.Column():
upload_input = gr.Image(
sources=["upload"],
type="numpy",
label="Upload Image"
)
upload_btn = gr.Button("π Detect Faces", variant="primary", size="lg")
with gr.Column():
upload_output = gr.Image(label="Detected Faces", elem_classes=["output-image"])
upload_status = gr.Textbox(label="Status", interactive=False)
upload_btn.click(
fn=process_image,
inputs=[upload_input],
outputs=[upload_output, upload_status]
)
# Information section
with gr.Accordion("βΉοΈ About & Parameters", open=False):
gr.Markdown(
"""
### How it works
This application uses **OpenCV's Haar Cascade Classifier** to detect faces in images.
The classifier is a machine learning-based approach that analyzes image patterns.
### Detection Parameters
```python
scaleFactor = 1.1 # Image pyramid scale
minNeighbors = 5 # Quality threshold
minSize = (30, 30) # Minimum face size in pixels
```
### Tips for best results
- Ensure good lighting
- Face the camera directly
- Keep a moderate distance from the camera
- Avoid extreme angles or occlusions
### Mobile Usage
- Use the "Phone Camera" tab for direct camera access
- Grant camera permissions when prompted
- The app works best in modern browsers (Chrome, Safari)
"""
)
# Launch the app
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0", # Allow access from other devices on the network
server_port=7860, # Default Gradio port
share=True, # Set to True to create a public link
inbrowser=True # Automatically open in browser
)
|