SAMI156 commited on
Commit
94ea426
·
1 Parent(s): 9afc72b

Updated the code

Browse files
Files changed (4) hide show
  1. .gitignore +8 -0
  2. README.md +50 -0
  3. main.py +66 -0
  4. requirements.txt +15 -0
.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ ./env
3
+ ./venv
4
+ .venv
5
+ .venv
6
+ ./venv
7
+ ./__pycache__
8
+ .__pycache__
README.md CHANGED
@@ -1,3 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
  ---
 
1
+ # 🖼️ Image Sticker Generator API
2
+ Welcome to the Image Sticker Generator API! This service is designed to transform images into "stickers" by isolating the main object with advanced semantic segmentation. The stickers are crafted with smooth, feathered edges to ensure a clean and professional appearance.
3
+
4
+
5
+ ## Examples
6
+
7
+ ![Example1](output/sticker_check3.png)
8
+ ![Example2](output/sticker_check.png)
9
+ ![Example3](output/sticker_check5.png)
10
+
11
+
12
+ ## 📋 Features
13
+ ### 🔍 Semantic Segmentation: Automatically detects and highlights the main object in an image, ensuring accurate cutouts and clear subject isolation.
14
+ ### 🌟 Feathered Edges: Applies a soft Gaussian blur to mask edges, creating a natural transition to transparency.
15
+ ### ⚡ Built with FastAPI: Ensures high performance, scalability, and rapid response times for production use.
16
+ ### 📂 Versatile Image Support: Accepts both PNG and JPEG image formats.
17
+
18
+ ### 🚀 Quick Start Guide
19
+ Clone the repository and navigate to the project directory.
20
+ Install Dependencies with Python 3.8+.
21
+ Start the API Server using the provided configuration.
22
+ Once running, the API will be accessible locally, ready for image uploads and sticker creation.
23
+
24
+ ## 🛠️ API Endpoints
25
+ POST /create_sticker/
26
+ Description: Upload an image to generate a sticker with a transparent background.
27
+ Supported File Types: Accepts PNG and JPEG formats.
28
+ Response: Returns a PNG image of the sticker with a transparent background. In case of an unsupported file format, an error message will be returned.
29
+ ## 🧩 How It Works
30
+ Model & Preprocessing: Uploaded images are preprocessed and passed through a pre-trained model for semantic segmentation.
31
+ Mask Generation: A binary mask isolates the main object in the image.
32
+ Edge Feathering: A Gaussian blur is applied to the mask edges to create a soft transition.
33
+ Sticker Creation: The mask is used to add transparency, producing an image that can be directly used as a sticker.
34
+ ## 📂 Directory Structure
35
+ The main application file manages the API and endpoints, while generated stickers are saved in a designated output directory. This ensures easy access and organization for generated images.
36
+
37
+ ## ⚙️ Configuration
38
+ Before running the application, confirm that the output directory exists. This is essential for storing all generated stickers for easy retrieval and management.
39
+
40
+ ## 📜 License
41
+ Licensed under the MIT License, making it easy for anyone to adapt and build upon the work.
42
+
43
+ ## 🙋‍♂️ Contributing
44
+ Contributions are welcome! To contribute, create a new issue or pull request for bug fixes, enhancements, or new features. All contributions should adhere to the project's coding standards and guidelines.
45
+
46
+ ## Built with ❤️ by [SAMIULLAH]
47
+
48
+ ## 📞 Support
49
+ For support or inquiries, please contact nicesami156@gmail.com.
50
+
51
  ---
52
  license: mit
53
  ---
main.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi.responses import FileResponse
2
+ from transformers import AutoImageProcessor, AutoModelForSemanticSegmentation
3
+ from PIL import Image, ImageFilter
4
+ from fastapi import FastAPI, File, UploadFile, HTTPException
5
+ import numpy as np
6
+ import uvicorn
7
+ import torch
8
+ import os
9
+
10
+ app = FastAPI()
11
+
12
+ # Load the model and processor once to avoid reloading on every request
13
+ preprocessor = AutoImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")
14
+ model = AutoModelForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")
15
+
16
+ # Create the directory for saving output if it doesn’t exist
17
+ os.makedirs("output", exist_ok=True)
18
+
19
+ def get_segmentation_mask(image: Image.Image) -> Image.Image:
20
+ """Generate a binary segmentation mask with feathered edges from an input image."""
21
+ # Step 1: Preprocess and run model inference
22
+ inputs = preprocessor(images=image, return_tensors="pt")
23
+ with torch.no_grad():
24
+ outputs = model(**inputs)
25
+
26
+ # Step 2: Post-process the segmentation output to get a clean binary mask
27
+ predicted_mask = preprocessor.post_process_semantic_segmentation(outputs)[0]
28
+ mask_np = predicted_mask.cpu().numpy().astype("uint8") * 255 # Convert to binary values (0 or 255)
29
+ binary_mask = Image.fromarray(mask_np)
30
+
31
+ # Step 3: Apply a slight Gaussian blur to soften the edges
32
+ feathered_mask = binary_mask.filter(ImageFilter.GaussianBlur(1)) # Adjust blur radius as needed
33
+ feathered_mask = feathered_mask.resize(image.size, Image.BICUBIC)
34
+
35
+ return feathered_mask
36
+
37
+ def apply_mask_to_image(image: Image.Image, mask: Image.Image) -> Image.Image:
38
+ """Apply the segmentation mask to the input image to create a transparent sticker."""
39
+ image = image.convert("RGBA") # Ensure image is in RGBA mode
40
+ sticker = Image.new("RGBA", image.size)
41
+ sticker.paste(image, (0, 0), mask) # Use mask as the alpha channel
42
+ return sticker
43
+
44
+ @app.post("/create_sticker/")
45
+ async def create_sticker(file: UploadFile = File(...)):
46
+ """Endpoint to convert an uploaded image to a sticker."""
47
+ if file.content_type not in ["image/png", "image/jpeg"]:
48
+ raise HTTPException(status_code=400, detail="Invalid image format. Only PNG and JPEG are supported.")
49
+
50
+ # Load the image
51
+ input_image = Image.open(file.file).convert("RGB")
52
+
53
+ # Generate segmentation mask and apply it to create a sticker
54
+ mask = get_segmentation_mask(input_image)
55
+ sticker = apply_mask_to_image(input_image, mask)
56
+
57
+ # Save the output sticker
58
+ output_path = f"output/sticker_{file.filename}"
59
+ sticker.save(output_path, "PNG")
60
+
61
+ return FileResponse(output_path, media_type="image/png")
62
+
63
+
64
+ # Run the app
65
+ if __name__ == "__main__":
66
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diffusers
2
+ transformers
3
+ accelerate
4
+ huggingface_hub
5
+ pillow
6
+ fastapi
7
+ pydantic
8
+ ngrok
9
+ uvicorn
10
+ celery
11
+ redis
12
+ sentencepiece
13
+ tokenizers
14
+ opencv-python
15
+ python-multipart