To create a web application that allows users to upload a photo and automatically paints the lips red, we'll utilize HTML, Tailwind CSS v3, and JavaScript. We'll also leverage the face-api.js library to detect facial landmarks, which will help us identify the lips' location on the uploaded image. Here's a step-by-step guide to building this application.
Prerequisites
- Tailwind CSS v3: Make sure you have access to Tailwind CSS v3 via CDN or installed in your project.
- face-api.js: We'll use this JavaScript library for face detection and landmark recognition.
Step 1: Set Up the Basic HTML Structure
We'll start by creating an HTML file with the necessary structure and include Tailwind CSS and face-api.js via CDNs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Red Lips Photo Editor</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- face-api.js CDN -->
<script defer src="https://unpkg.com/face-api.js"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
<!-- Content will go here -->
</body>
</html>
Step 2: Create the Image Upload Interface
We'll create a simple interface where users can upload their photos.
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
<div class="bg-white p-8 rounded shadow-md w-full max-w-md">
<h1 class="text-2xl font-bold mb-4 text-center">Red Lips Photo Editor</h1>
<input id="imageUpload" type="file" accept=".jpg, .jpeg, .png, .webp" class="block w-full text-sm text-gray-500
file:mr-4 file:py-2 file:px-4
file:rounded file:border-0
file:text-sm file:font-semibold
file:bg-blue-50 file:text-blue-700
hover:file:bg-blue-100
"/>
<div id="imageContainer" class="mt-6 relative">
<!-- Canvas will be inserted here -->
</div>
</div>
<!-- Place scripts at the end of body -->
</body>
Step 3: Load face-api.js Models
Before we can use face-api.js to detect facial landmarks, we need to load the necessary models. We'll do this when the window loads.
<script>
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
faceapi.nets.faceLandmark68TinyNet.loadFromUri('/models'),
]).then(() => {
console.log('Models loaded');
});
</script>
Note: You'll need to host the models locally or use an online source. For simplicity, you can download the models from the face-api.js repository and place them in a /models directory on your server.
Step 4: Handle Image Upload and Processing
We'll add JavaScript to handle the image upload, detect the lips, and paint them red.
<script>
const imageUpload = document.getElementById('imageUpload');
const imageContainer = document.getElementById('imageContainer');
imageUpload.addEventListener('change', async () => {
const file = imageUpload.files[0];
if (!file) return;
// Clear previous images
imageContainer.innerHTML = '';
// Create an image element
const img = document.createElement('img');
img.src = URL.createObjectURL(file);
img.alt = 'Uploaded Image';
img.className = 'max-w-full rounded shadow';
// Append image to container
imageContainer.appendChild(img);
// Wait for the image to load
img.onload = async () => {
// Create a canvas element
const canvas = faceapi.createCanvasFromMedia(img);
imageContainer.appendChild(canvas);
const displaySize = { width: img.width, height: img.height };
faceapi.matchDimensions(canvas, displaySize);
// Detect face landmarks
const detections = await faceapi.detectAllFaces(img, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks(true);
const resizedDetections = faceapi.resizeResults(detections, displaySize);
// Draw the detections onto the canvas
resizedDetections.forEach(detection => {
const landmarks = detection.landmarks;
const ctx = canvas.getContext('2d');
// Get lip landmarks (mouth)
const mouth = landmarks.getMouth();
// Create a path for the lips
ctx.beginPath();
mouth.forEach((point, index) => {
if (index === 0) {
ctx.moveTo(point.x, point.y);
} else {
ctx.lineTo(point.x, point.y);
}
});
ctx.closePath();
// Fill the lips with red color
ctx.fillStyle = 'red';
ctx.fill();
});
};
});
</script>
Step 5: Style the Application with Tailwind CSS
We've already applied some Tailwind classes to style the elements, but you can customize it further as needed.
Folder Structure for Models
Make sure your project directory contains a folder named models with the necessary model files from face-api.js. Your folder structure should look like this:
- index.html
- models/
- face_landmark_68_tiny_model-weights_manifest.json
- face_landmark_68_tiny_model-shard1
- tiny_face_detector_model-weights_manifest.json
- tiny_face_detector_model-shard1
Full Code Example
Here's the complete HTML code with all the above steps combined.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Red Lips Photo Editor</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- face-api.js CDN -->
<script defer src="https://unpkg.com/face-api.js"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
<div class="bg-white p-8 rounded shadow-md w-full max-w-md">
<h1 class="text-2xl font-bold mb-4 text-center">Red Lips Photo Editor</h1>
<input id="imageUpload" type="file" accept=".jpg, .jpeg, .png, .webp" class="block w-full text-sm text-gray-500
file:mr-4 file:py-2 file:px-4
file:rounded file:border-0
file:text-sm file:font-semibold
file:bg-blue-50 file:text-blue-700
hover:file:bg-blue-100
"/>
<div id="imageContainer" class="mt-6 relative">
<!-- Canvas will be inserted here -->
</div>
</div>
<script>
// Load face-api.js models
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
faceapi.nets.faceLandmark68TinyNet.loadFromUri('/models'),
]).then(() => {
console.log('Models loaded');
});
const imageUpload = document.getElementById('imageUpload');
const imageContainer = document.getElementById('imageContainer');
imageUpload.addEventListener('change', async () => {
const file = imageUpload.files[0];
if (!file) return;
// Clear previous images
imageContainer.innerHTML = '';
// Create an image element
const img = document.createElement('img');
img.src = URL.createObjectURL(file);
img.alt = 'Uploaded Image';
img.className = 'max-w-full rounded shadow';
// Append image to container
imageContainer.appendChild(img);
// Wait for the image to load
img.onload = async () => {
// Create a canvas element
const canvas = faceapi.createCanvasFromMedia(img);
imageContainer.appendChild(canvas);
const displaySize = { width: img.width, height: img.height };
faceapi.matchDimensions(canvas, displaySize);
// Detect face landmarks
const detections = await faceapi.detectAllFaces(img, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks(true);
const resizedDetections = faceapi.resizeResults(detections, displaySize);
// Draw the detections onto the canvas
resizedDetections.forEach(detection => {
const landmarks = detection.landmarks;
const ctx = canvas.getContext('2d');
// Get lip landmarks (mouth)
const mouth = landmarks.getMouth();
// Create a path for the lips
ctx.beginPath();
mouth.forEach((point, index) => {
if (index === 0) {
ctx.moveTo(point.x, point.y);
} else {
ctx.lineTo(point.x, point.y);
}
});
ctx.closePath();
// Fill the lips with red color
ctx.fillStyle = 'red';
ctx.fill();
});
};
});
</script>
</body>
</html>
How It Works
-
Image Upload: The user selects an image file using the file input field.
-
Display Image: The selected image is displayed on the page.
-
Load Models: The face-api.js models for face detection and landmark recognition are loaded.
-
Face and Landmark Detection: Once the image is loaded, the application detects faces and facial landmarks in the image.
-
Identify Lips: Using the landmarks, the application identifies the coordinates of the lips.
-
Paint Lips Red: A canvas is overlaid on the image, and the lips area is filled with a red color.
Additional Notes
-
Browser Support: Ensure that you're running this application in a modern browser that supports ES6 and async/await syntax.
-
Security: For local files to be accessible via URLs (using URL.createObjectURL), you need to run this on a local server rather than opening the HTML file directly in the browser.
-
Running a Local Server: You can use a simple HTTP server. For example, using Python:
Then, navigate to http://localhost:8000 in your browser.
-
Model Hosting: If you prefer not to host the models locally, you can reference them from a CDN or an online repository, but ensure you have proper access permissions.
Conclusion
You've now created a simple web application that allows users to upload a photo and automatically paints the lips red. This application combines the power of HTML, Tailwind CSS for styling, and JavaScript with face-api.js for facial landmark detection.
Feel free to enhance the application by adding features such as:
- Color Picker: Allow users to choose different lip colors.
- Download Option: Enable users to download the edited image.
- Multiple Face Support: Handle images with multiple faces.
If you have any questions or need further assistance, feel free to ask!