LiveDemo/ColorSwitcher
0
1import streamlit as st2import cv23import numpy as np4from PIL import Image5import webcolors6from streamlit_drawable_canvas import st_canvas7 8# Load the image9image_path = "ImageTest.jpeg"10image = cv2.imread(image_path)11image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert to RGB12image_pil = Image.fromarray(image)13 14# Streamlit App15st.title("Best-in-Class Pants Color Changer")16st.write("Draw over the pants to create an accurate mask before applying color changes.")17 18# Show original image separately19st.image(image_pil, caption="Original Image", use_container_width=True)20 21# Create a drawing canvas (without background image)22canvas_result = st_canvas(23 fill_color="rgba(255, 0, 0, 0.3)", # Default color for mask overlay24 stroke_width=5,25 stroke_color="#FF0000",26 background_color="#FFFFFF", # White background to avoid error27 update_streamlit=True,28 height=image.shape[0],29 width=image.shape[1],30 drawing_mode="freedraw",31 key="canvas"32)33 34# Convert drawn mask to binary mask35if canvas_result.image_data is not None:36 mask = cv2.cvtColor(canvas_result.image_data.astype(np.uint8), cv2.COLOR_RGBA2GRAY)37 mask = (mask > 50).astype(np.uint8) * 255 # Threshold to create binary mask38else:39 mask = np.zeros(image.shape[:2], dtype=np.uint8)40 41# Function to convert HEX to RGB42def hex_to_rgb(hex_color):43 return webcolors.hex_to_rgb(hex_color)44 45# Function to change pants color while preserving texture46def change_pants_color(hex_color):47 rgb_color = hex_to_rgb(hex_color)48 overlay = np.full_like(image, rgb_color, dtype=np.uint8)49 50 # Blend new color with texture using color dodge blend51 pants_colored = cv2.addWeighted(image, 0.6, overlay, 0.4, 0)52 new_image = np.where(mask[:, :, None] > 0, pants_colored, image)53 return Image.fromarray(new_image)54 55selected_color = st.color_picker("Pick a color for the pants", "#ff0000")56 57if np.any(mask > 0):58 modified_image = change_pants_color(selected_color)59 st.image(modified_image, caption="Modified Image", use_container_width=True)60else:61 st.write("Draw over the pants first to apply the color change!")62 