pythonintermediate
OpenCV Face Detection with DNN
Detect faces in images using OpenCV's deep neural network face detector for accurate results.
pythonPress ⌘/Ctrl + Shift + C to copy
import cv2
import numpy as np
def detect_faces(image_path: str, confidence_threshold: float = 0.5) -> list[dict]:
net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'res10_300x300_ssd_iter_140000.caffemodel')
img = cv2.imread(image_path)
h, w = img.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(img, (300,300)), 1.0, (300,300), (104,177,123))
net.setInput(blob)
detections = net.forward()
faces = []
for i in range(detections.shape[2]):
conf = float(detections[0,0,i,2])
if conf > confidence_threshold:
box = (detections[0,0,i,3:7] * np.array([w,h,w,h])).astype(int)
faces.append({'confidence': conf, 'bbox': box.tolist()})
return faces
for face in detect_faces('photo.jpg'):
print(f'Face: confidence={face["confidence"]:.2%}, bbox={face["bbox"]}')Use Cases
- face detection
- video surveillance
- photo tagging
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonadvanced
Image Segmentation with SAM in Python
Segment any object in an image using Meta's Segment Anything Model (SAM) with Python.
Best for: object segmentation
#sam#segmentation
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming
typescriptbeginner
Generate Text Embeddings with OpenAI
Create vector embeddings for semantic search and similarity matching using text-embedding-3-small.
Best for: semantic search
#openai#embeddings
typescriptadvanced
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
Best for: document Q&A
#rag#embeddings