Spaces:
Build error
Build error
Update app.py
Browse files123452 unmodified lines89101112131415166 unmodified lines232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import gradio as grfrom PIL import Image, ImageEnhanceimport numpy as npimport cv2from lang_sam import LangSAM2 unmodified linesimport torch# Load the LangSAM modelmodel = LangSAM() # Use the default model or specify custom checkpoint: LangSAM("<model_type>", "<path/to/checkpoint>")# Function to apply color matching based on reference imagedef apply_color_matching(source_img_np, ref_img_np):# Initialize ColorMatchercm = ColorMatcher()6 unmodified linesreturn img_res# Function to extract sky and apply color matching using a reference imagedef extract_and_color_match_sky(image_pil, reference_image_pil, text_prompt="sky"):# Use LangSAM to predict the mask for the skymasks, boxes, phrases, logits = model.predict(image_pil, text_prompt)# Ensure masks is converted from tensor to NumPymasks_np = masks[0].cpu().numpy() # Convert the tensor to NumPy array# Convert the mask to a binary format and create a mask imagesky_mask = (masks_np > 0).astype(np.uint8) * 255 # Ensure it's a binary mask# Convert PIL image to numpy array for processingimg_np = np.array(image_pil)# Convert sky mask to 3-channel format to blend with the original imagesky_mask_3ch = cv2.merge([sky_mask, sky_mask, sky_mask])# Extract the sky regionsky_region = cv2.bitwise_and(img_np, sky_mask_3ch)# Convert the reference image to a numpy arrayref_img_np = np.array(reference_image_pil)# Apply color matching using the reference image to the extracted sky regionsky_region_color_matched = apply_color_matching(sky_region, ref_img_np)# Combine the color-matched sky region back into the original imageresult_img_np = np.where(sky_mask_3ch > 0, sky_region_color_matched, img_np)# Convert the result back to PIL Image for final outputresult_img_pil = Image.fromarray(result_img_np)return result_img_pil# Gradio Interfacedef gradio_interface():# Gradio function to be called on inputdef process_image(source_img, ref_img):# Extract sky and apply color matching using reference imageresult_img_pil = extract_and_color_match_sky(source_img, ref_img)return result_img_pil# Define Gradio input componentsinputs = [gr.Image(type="pil", label="Source Image"),gr.Image(type="pil", label="Reference Image") # Second input for reference image]# Define Gradio output componentoutputs = gr.Image(type="pil", label="Resulting Image")# Launch Gradio appgr.Interface(fn=process_image, inputs=inputs, outputs=outputs, title="Sky Extraction and Color Matching").launch(share=True)# Run the Gradio Interfaceif __name__ == "__main__":gradio_interface()123452 unmodified lines891011121314151617181920216 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156import gradio as grfrom PIL import Imageimport numpy as npimport cv2from lang_sam import LangSAM2 unmodified linesimport torch# Load the LangSAM modelmodel = LangSAM() # Use the default model or specify custom checkpoint if necessarydef extract_mask(image_pil, text_prompt):masks, boxes, phrases, logits = model.predict(image_pil, text_prompt)masks_np = masks[0].cpu().numpy()mask = (masks_np > 0).astype(np.uint8) * 255 # Binary maskreturn maskdef apply_color_matching(source_img_np, ref_img_np):# Initialize ColorMatchercm = ColorMatcher()6 unmodified linesreturn img_resdef process_image(current_image_pil, prompt, replacement_image_pil, color_ref_image_pil, image_history):# Check if current_image_pil is Noneif current_image_pil is None:return None, "No current image to edit.", image_history, None# Save current image to history for undoif image_history is None:image_history = []image_history.append(current_image_pil.copy())# Extract maskmask = extract_mask(current_image_pil, prompt)# Check if mask is validif mask.sum() == 0:return current_image_pil, f"No mask detected for prompt: {prompt}", image_history, current_image_pil# Proceed with replacement or color matchingcurrent_image_np = np.array(current_image_pil)mask_3ch = cv2.merge([mask, mask, mask])result_image_np = current_image_np.copy()# If replacement image is providedif replacement_image_pil is not None:# Resize replacement image to fit the mask area# Get bounding box of the masky_indices, x_indices = np.where(mask > 0)if y_indices.size == 0 or x_indices.size == 0:# No mask detectedreturn current_image_pil, f"No mask detected for prompt: {prompt}", image_history, current_image_pily_min, y_max = y_indices.min(), y_indices.max()x_min, x_max = x_indices.min(), x_indices.max()# Extract the region of interestmask_height = y_max - y_min + 1mask_width = x_max - x_min + 1# Resize replacement image to fit mask areareplacement_image_resized = replacement_image_pil.resize((mask_width, mask_height))replacement_image_np = np.array(replacement_image_resized)# Create a mask for the ROImask_roi = mask[y_min:y_max+1, x_min:x_max+1]mask_roi_3ch = cv2.merge([mask_roi, mask_roi, mask_roi])# Replace the masked area with the replacement imageresult_image_np[y_min:y_max+1, x_min:x_max+1] = np.where(mask_roi_3ch > 0, replacement_image_np, result_image_np[y_min:y_max+1, x_min:x_max+1])# If color reference image is providedif color_ref_image_pil is not None:# Extract the masked areamasked_region = cv2.bitwise_and(result_image_np, mask_3ch)# Convert color reference image to numpycolor_ref_image_np = np.array(color_ref_image_pil)# Apply color matchingcolor_matched_region = apply_color_matching(masked_region, color_ref_image_np)# Combine the color matched region back into the result imageresult_image_np = np.where(mask_3ch > 0, color_matched_region, result_image_np)# Convert result back to PIL Imageresult_image_pil = Image.fromarray(result_image_np)# Update current_image_pilcurrent_image_pil = result_image_pilreturn current_image_pil, f"Applied changes for prompt: {prompt}", image_history, current_image_pildef undo(image_history):if image_history and len(image_history) > 1:# Pop the last imageimage_history.pop()# Return the previous imagecurrent_image_pil = image_history[-1]return current_image_pil, image_history, current_image_pilelif image_history and len(image_history) == 1:current_image_pil = image_history[0]return current_image_pil, image_history, current_image_pilelse:# Cannot undoreturn None, [], Nonedef gradio_interface():with gr.Blocks() as demo:# Define the state variablesimage_history = gr.State([])current_image_pil = gr.State(None)gr.Markdown("## Continuous Image Editing with LangSAM")with gr.Row():with gr.Column():initial_image = gr.Image(type="pil", label="Upload Image")prompt = gr.Textbox(lines=1, placeholder="Enter prompt for object detection", label="Prompt")replacement_image = gr.Image(type="pil", label="Replacement Image (optional)", optional=True)color_ref_image = gr.Image(type="pil", label="Color Reference Image (optional)", optional=True)apply_button = gr.Button("Apply Changes")undo_button = gr.Button("Undo")with gr.Column():current_image_display = gr.Image(type="pil", label="Edited Image", interactive=False)status = gr.Textbox(lines=2, interactive=False, label="Status")def initialize_image(initial_image_pil):# Initialize image history with the initial imageif initial_image_pil is not None:image_history = [initial_image_pil]current_image_pil = initial_image_pilreturn current_image_pil, image_history, initial_image_pilelse:return None, [], None# When the initial image is uploaded, initialize the image historyinitial_image.upload(fn=initialize_image, inputs=initial_image, outputs=[current_image_pil, image_history, current_image_display])# Apply button clickapply_button.click(fn=process_image,inputs=[current_image_pil, prompt, replacement_image, color_ref_image, image_history],outputs=[current_image_pil, status, image_history, current_image_display])# Undo button clickundo_button.click(fn=undo, inputs=image_history, outputs=[current_image_pil, image_history, current_image_display])demo.launch(share=True)# Run the Gradio Interfaceif __name__ == "__main__":gradio_interface()
app.py+121-47