Spaces:
Runtime error
Runtime error
wracell commited on
Commit ยท
caef22e
1
Parent(s): 804b0e5
modifications and added sam_vit_b.pth
Browse filesFiles changed (3)
- app.py+64-92
- requirements.txt+2-1
- sam_vit_b.pthAdded+3
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371 unmodified lineimport numpy as npimport cv2from PIL import Imageimport torchimport torchvision.transforms as transformsimport torchvision.models as modelsfrom io import BytesIOfrom google.generativeai import configure, GenerativeModelimport base64# Configure Gemini APIconfigure(api_key="AIzaSyBawh403z5cyyQzFhQo14y7oUQw6nr8mIg")model = GenerativeModel("gemini-2.0-flash")# Load DeepLabV3 model for garment segmentationdef load_segmentation_model():model = models.segmentation.deeplabv3_resnet101(pretrained=True)model.eval()return modeldef segment_garment(image, model):# Convert to model-compatible formattransform = transforms.Compose([transforms.Resize((520, 520)),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])image_tensor = transform(image).unsqueeze(0)with torch.no_grad():output = model(image_tensor)['out'][0]# Convert output to segmentation maskmask = output.argmax(0).byte().cpu().numpy()# Debugging: Check if any garment pixels are detectedprint("Unique values in mask:", np.unique(mask))if mask.max() == 0: # No garment detectedprint("Warning: No garment detected. Check input image.")return image # Return original image# Resize mask to match original image sizemask = Image.fromarray(mask.astype(np.uint8) * 255)mask = mask.resize(image.size, Image.NEAREST) # Match original sizemask = np.array(mask)# Convert grayscale mask to 3-channelmask = np.stack([mask] * 3, axis=-1)# Convert original image to numpy arrayimage_np = np.array(image)# Apply the mask (only keep garment pixels)segmented = np.where(mask > 0, image_np, 0)return Image.fromarray(segmented)# Preprocess image using OpenCV (Edge Detection & Background Removal)def preprocess_image(image):image = np.array(image.convert("RGB"))gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)edges = cv2.Canny(gray, 100, 200)return Image.fromarray(edges)# AI garment analysis & fashion recommendationsdef analyze_garment(image):# Convert PIL Image to bytesimage_bytes = BytesIO()image.save(image_bytes, format="PNG")image_bytes = image_bytes.getvalue()# Encode image in Base64encoded_image = base64.b64encode(image_bytes).decode("utf-8")# Prepare request payload in correct Gemini API formatprompt = {"parts": [{"text": "Analyze the garment in this image, describing its style, fabric, and design elements. ""Based on the garment's features, suggest the best occasions to wear it ""and recommend complementary fashion pieces (e.g., shoes, accessories, layering options). ""Also, provide a seasonal suitability rating."},{"inline_data": {"mime_type": "image/png", "data": encoded_image}}]}# Call Gemini APIresponse = model.generate_content(prompt)return response.text if response else "Analysis failed."# Load segmentation modelsegmentation_model = load_segmentation_model()# Streamlit UIst.title("๐ AI-Enhanced Fashion Design with Gemini 2.0 Flash")st.write("""### ๐จ **About This App**This AI-powered fashion tool helps you analyze and enhance garment designs using Google's **Gemini 2.0 Flash** and DeepLabV3 segmentation.It provides recommendations on **suitable fashion styles** for different occasions based on the uploaded garment.### ๐ **How to Use This App**1. **Upload an Image** โ Select a clothing item or a fashion sketch.2. **View Preprocessing & Segmentation** โ The app applies edge detection and garment segmentation.3. **Analyze Garment** โ Click "Analyze Garment" to get AI-powered fashion insights.4. **Get Recommendations** โ The AI suggests suitable **occasions and styling tips** based on the garment.### ๐ **How It Works**- **Edge Detection**: Uses OpenCV to highlight contours and details in the garment.- **Garment Segmentation**: DeepLabV3 identifies the clothing item and removes the background.- **AI Fashion Analysis**: Googleโs Gemini AI analyzes the **style, fabric, and design** of the garment and provides recommendations.โก๏ธ Try it now by uploading an image of your clothing!""")# File Uploaduploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])if uploaded_file is not None:# Display uploaded imageimage = Image.open(uploaded_file)st.image(image, caption="Uploaded Image", use_container_width=True)# Preprocess Image with OpenCVprocessed_image = preprocess_image(image)st.image(processed_image, caption="Processed Image (Edge Detection)", use_container_width=True)# Segment Garment using DeepLabV3segmented_image = segment_garment(image, segmentation_model)st.image(segmented_image.convert("RGB"), caption="Segmented Garment", use_container_width=True)if st.button("Analyze Garment"):result = analyze_garment(image)st.success(result)1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091 unmodified lineimport numpy as npimport cv2from PIL import Imageimport torchvision.transforms as transformsfrom segment_anything import sam_model_registry, SamPredictorfrom io import BytesIOimport base64from google.generativeai import configure, GenerativeModel# Configure Gemini APIconfigure(api_key="AIzaSyBawh403z5cyyQzFhQo14y7oUQw6nr8mIg")model = GenerativeModel("gemini-2.0-flash")# Load SAM model with ViT-Basedef load_sam_model():sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b.pth") # Use vit_b instead of vit_hpredictor = SamPredictor(sam)return predictor# Preprocess image using OpenCV (Edge Detection & Background Removal)def preprocess_image(image):image = np.array(image.convert("RGB")) # Convert to NumPy arraygray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # Convert to Grayscaleedges = cv2.Canny(gray, 100, 200) # Apply Canny Edge Detectionreturn Image.fromarray(edges) # Convert back to PIL Image# Segment garment using SAMdef segment_garment(image, predictor):image_np = np.array(image.convert("RGB"))predictor.set_image(image_np)# Use center point of image as promptheight, width, _ = image_np.shapeinput_point = np.array([[width // 2, height // 2]])input_label = np.array([1]) # 1 indicates object selectionmasks, _, _ = predictor.predict(point_coords=input_point, point_labels=input_label)mask = masks[0] # Get first mask# Resize mask to match imagemask_resized = cv2.resize(mask.astype(np.uint8) * 255, (width, height), interpolation=cv2.INTER_NEAREST)mask_resized = np.stack([mask_resized] * 3, axis=-1) # Convert to 3-channel# Apply segmentation masksegmented = np.where(mask_resized > 0, image_np, 0)return Image.fromarray(segmented)# AI garment analysisdef analyze_garment(image):image_bytes = BytesIO()image.save(image_bytes, format="PNG")encoded_image = base64.b64encode(image_bytes.getvalue()).decode("utf-8")prompt = {"parts": [{"text": "Analyze the garment in this image, describing its style, fabric, and design elements. ""Suggest the best occasions to wear it and recommend complementary fashion pieces."},{"inline_data": {"mime_type": "image/png", "data": encoded_image}}]}response = model.generate_content(prompt)return response.text if response else "Analysis failed."# Load SAM modelsam_predictor = load_sam_model()# Streamlit UIst.title("๐ AI Fashion Analysis with SAM & Gemini AI")# Description and Instructionsst.markdown("""### ๐ How to Use this App:1. *Upload an Image*: Click the upload button and select a fashion image.2. *Preprocess the Image*: Click 'Preprocess' to apply edge detection and garment segmentation.3. *View Results*: Processed and segmented images will be displayed.4. *Analyze the Garment*: Click 'Analyze Garment' to get AI-based fashion insights.""")# File Uploaduploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])if uploaded_file is not None:image = Image.open(uploaded_file)st.image(image, caption="Uploaded Image", use_container_width=True)# Initialize session state for persistenceif "processed_image" not in st.session_state:st.session_state.processed_image = Noneif "segmented_image" not in st.session_state:st.session_state.segmented_image = None# Preprocess Button (Runs Edge Detection & Segmentation)if st.button("Preprocess"):st.session_state.processed_image = preprocess_image(image)st.session_state.segmented_image = segment_garment(image, sam_predictor)# Display Preprocessed Images if Availableif st.session_state.processed_image:st.image(st.session_state.processed_image, caption="Edge Detection", use_container_width=True)if st.session_state.segmented_image:st.image(st.session_state.segmented_image, caption="Segmented Garment", use_container_width=True)# Analyze Garment Button (Gemini AI)if st.button("Analyze Garment"):result = analyze_garment(image)st.success(result)
3 unmodified lines45673 unmodified linespillowtorchtorchvisiongoogle-generativeai3 unmodified lines456783 unmodified linespillowtorchtorchvisiongoogle-generativeaitransformers
123version https://git-lfs.github.com/spec/v1oid sha256:ec2df62732614e57411cdcf32a23ffdf28910380d03139ee0f4fcbe91eb8c912size 375042383app.py+64-92
requirements.txt+2-1
sam_vit_b.pthAdded+3