### Install gradio-imageslider Source: https://github.com/pngwn/gradio-imageslider/blob/main/README.md Install the gradio-imageslider Python package using pip. This command fetches and installs the latest stable version from the Python Package Index (PyPI). ```bash pip install gradio_imageslider ``` -------------------------------- ### ImageSlider Type Hinting and Optional Parameters Source: https://github.com/pngwn/gradio-imageslider/blob/main/README.md Demonstrates type hinting for optional parameters of the ImageSlider component. This includes 'label', 'every', 'show_label', 'id', 'elem_classes', 'show_share_button', and 'slider_color', specifying their possible types and default values. ```python str | None list[str] | str | None bool | None str | None ``` -------------------------------- ### Initialize ImageSlider Component Source: https://context7.com/pngwn/gradio-imageslider/llms.txt Demonstrates the initialization of the ImageSlider component with various customizable parameters. This includes setting default values, slider position, upload count, dimensions, return type (PIL Image, numpy array, filepath), labels, download buttons, and styling like slider color. ```python import gradio as gr from gradio_imageslider import ImageSlider from PIL import Image import numpy as np # Basic initialization with default settings slider1 = ImageSlider() # Advanced initialization with custom parameters slider2 = ImageSlider( value=None, # Default value as tuple of images position=0.5, # Slider starts at center (0-1 range) upload_count=1, # Allow single image upload height=400, # Component height in pixels width=600, # Component width in pixels type="pil", # Return PIL Image objects label="Image Comparison", show_download_button=True, show_label=True, container=True, interactive=True, visible=True, slider_color="#FF69B4" # Pink slider separator ) # Component with numpy array output slider3 = ImageSlider( type="numpy", # Returns numpy arrays (height, width, 3) position=0.3, # Slider starts at 30% upload_count=2 # Allow two separate image uploads ) # Component with filepath output slider4 = ImageSlider( type="filepath", # Returns temporary file paths show_download_button=False, min_width=200, scale=2 # Takes 2x width compared to adjacent components ) ``` -------------------------------- ### Image Slider Initialization Source: https://github.com/pngwn/gradio-imageslider/blob/main/README.md This section details the parameters available when initializing the Gradio Image Slider component. These parameters control the default value, slider position, upload capabilities, image display, and interactive features. ```APIDOC ## Image Slider Initialization Parameters This document outlines the parameters for initializing the Gradio Image Slider component. ### Parameters #### Initialization Parameters - **value** (tuple[str, str] | tuple[PIL.Image.Image, PIL.Image.Image] | tuple[numpy.ndarray, numpy.ndarray] | None) - Optional - A PIL Image, numpy array, path or URL for the default value. If callable, the function will be called whenever the app loads to set the initial value. - **position** (int) - Optional (default: 0.5) - The position of the slider, between 0 and 1. - **upload_count** (int) - Optional (default: 1) - The number of images that can be uploaded (1 or 2). - **height** (int | None) - Optional - Height of the displayed image in pixels. - **width** (int | None) - Optional - Width of the displayed image in pixels. - **type** ("numpy" | "pil" | "filepath") - Optional (default: "numpy") - The format the image is converted to before being passed into the prediction function. - **label** (str | None) - Optional - Component name in the interface. - **every** (float | None) - Optional - If `value` is a callable, run the function 'every' number of seconds. Requires 'queue' to be enabled. - **show_label** (bool | None) - Optional - If True, will display the label. - **show_download_button** (bool) - Optional (default: True) - If True, will display a button to download the image. - **container** (bool) - Optional (default: True) - If True, will place the component in a container with extra padding. - **scale** (int | None) - Optional - Relative width compared to adjacent Components in a Row. - **min_width** (int) - Optional (default: 160) - Minimum pixel width for the component. - **interactive** (bool | None) - Optional - If True, allows users to upload and edit an image; if False, can only display images. Inferred if not provided. - **visible** (bool) - Optional (default: True) - If False, the component will be hidden. - **elem_id** (str | None) - Optional - CSS ID for the component. ``` -------------------------------- ### Image Slider Component Source: https://github.com/pngwn/gradio-imageslider/blob/main/README.md Configuration and usage of the Image Slider component in Gradio. ```APIDOC ## Image Slider Component ### Description The Image Slider component allows users to select between two images. It can be used as an input or output for Gradio applications. ### Method N/A (Component definition) ### Endpoint N/A (Component definition) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## Parameters ### `id` - **id** (str | None) - Required/Optional - An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. ### `elem_classes` - **elem_classes** (list[str] | str | None) - Required/Optional - An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. ### `show_share_button` - **show_share_button** (bool | None) - Required/Optional - If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise. ### `slider_color` - **slider_color** (str | None) - Required/Optional - The color of the slider separator. ## Events ### `change` - **description**: Triggered when the value of the ImageSlider changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. ### `upload` - **description**: This listener is triggered when the user uploads a file into the ImageSlider. ## User function Integration ### As output: - **description**: Is passed, tuple of images in the requested format. ### As input: - **description**: Should return, image as a numpy array, PIL Image, string/Path filepath, or string URL. ### Code Snippet Example: ```python def predict( value: tuple[str, str] | tuple[PIL.Image.Image, PIL.Image.Image] | tuple[numpy.ndarray, numpy.ndarray] | None ) -> tuple[str, str] | tuple[PIL.Image.Image, PIL.Image.Image] | tuple[numpy.ndarray, numpy.ndarray] | None: return value ``` ``` -------------------------------- ### Basic ImageSlider Usage in Gradio Source: https://github.com/pngwn/gradio-imageslider/blob/main/README.md Demonstrates how to use the ImageSlider component within a Gradio Blocks interface. It includes a function to apply a Gaussian blur to an input image and displays the original and blurred images side-by-side for comparison. ```python import gradio as gr from gradio_imageslider import ImageSlider from PIL import ImageFilter def fn(im): if not im or not im[0]: return im return (im[0], im[0].filter(filter=ImageFilter.GaussianBlur(radius=10))) with gr.Blocks() as demo: with gr.Group(): img1 = ImageSlider(label="Blur image", type="pil", slider_color="pink") img1.upload(fn, inputs=img1, outputs=img1) if __name__ == "__main__": demo.launch() ``` -------------------------------- ### Static Output Display for Model Inference with Gradio ImageSlider Source: https://context7.com/pngwn/gradio-imageslider/llms.txt Utilizes ImageSlider as a non-interactive output component to display the comparison between a noisy image and a denoised version, simulating model inference. Users can upload an image, adjust a noise level slider, and process it to see the denoising effect. Dependencies include gradio, Pillow, and numpy. ```python import gradio as gr from gradio_imageslider import ImageSlider from PIL import ImageFilter, Image import numpy as np def generate_comparison(input_image, noise_level): """Simulate model inference generating a processed image""" if input_image is None: return None # Convert to PIL if numpy array if isinstance(input_image, np.ndarray): input_image = Image.fromarray(input_image) # Simulate processing: add noise and blur img_array = np.array(input_image) noise = np.random.normal(0, noise_level, img_array.shape) noisy = np.clip(img_array + noise, 0, 255).astype(np.uint8) noisy_img = Image.fromarray(noisy) denoised = noisy_img.filter(ImageFilter.MedianFilter(size=3)) # Return tuple: (noisy image, denoised image) return (noisy_img, denoised) with gr.Blocks() as demo: gr.Markdown("## Image Denoising Model Demo") gr.Markdown("Simulate a denoising model: add noise then remove it") with gr.Row(): with gr.Column(): input_img = gr.Image( label="Input Image", type="pil", sources=["upload", "webcam"] ) noise_slider = gr.Slider( minimum=5, maximum=50, value=20, step=5, label="Noise Level" ) process_btn = gr.Button("Process Image", variant="primary") with gr.Column(): output_slider = ImageSlider( label="Noisy vs Denoised", type="pil", position=0.5, slider_color="purple", interactive=False, # Output only, no upload height=500 ) process_btn.click( fn=generate_comparison, inputs=[input_img, noise_slider], outputs=output_slider ) demo.launch() # Expected output: Users upload image, adjust noise level, click process. # Output slider shows noisy image vs denoised result with purple separator. ``` -------------------------------- ### Manual Two-Image Comparison Source: https://context7.com/pngwn/gradio-imageslider/llms.txt Configures a Gradio interface allowing users to manually upload two distinct images for side-by-side comparison using the `ImageSlider` component. The component is set to accept two uploads (`upload_count=2`) and configured for filepath output. ```python import gradio as gr from gradio_imageslider import ImageSlider def compare_images(im): """Pass through uploaded images for comparison""" if not im: return None return im with gr.Blocks() as demo: gr.Markdown("## Compare Two Images") gr.Markdown("Upload two images to compare them side-by-side") comparison_slider = ImageSlider( label="Image Comparison Tool", type="filepath", upload_count=2, # Enable uploading two separate images position=0.5, slider_color="red", height=500, show_download_button=True ) # Optional: Add change event to track slider position changes comparison_slider.change( compare_images, inputs=comparison_slider, outputs=comparison_slider ) demo.launch() # Expected output: Interface allowing upload of two images with a draggable # red slider to compare them. Images can be downloaded via the download button. ``` -------------------------------- ### ImageSlider User Function Signature Source: https://github.com/pngwn/gradio-imageslider/blob/main/README.md Shows the 'predict' function signature when ImageSlider is used as both an input and output. It specifies the expected input types (tuple of strings, PIL Images, numpy arrays, or None) and the return types, which mirror the input types. ```python def predict( value: tuple[str, str] | tuple[PIL.Image.Image, PIL.Image.Image] | tuple[numpy.ndarray, numpy.ndarray] | None ) -> tuple[str, str] | tuple[PIL.Image.Image, PIL.Image.Image] | tuple[numpy.ndarray, numpy.ndarray] | None: return value ``` -------------------------------- ### Interactive Image Processing Pipeline with Gradio ImageSlider Source: https://context7.com/pngwn/gradio-imageslider/llms.txt Applies various image filters (Blur, Sharpen, Edge Detection, Grayscale, Sepia, Brightness) to an uploaded image and displays a comparison using ImageSlider. It handles image uploads and filter selections, updating the comparison in real-time. Dependencies include gradio, Pillow, and numpy. ```python import gradio as gr from gradio_imageslider import ImageSlider from PIL import ImageFilter, ImageOps, ImageEnhance, Image import numpy as np def apply_filter(im, filter_type): """Apply selected filter to the uploaded image""" if not im or not im[0]: return im original = im[0] if filter_type == "Blur": processed = original.filter(ImageFilter.GaussianBlur(radius=15)) elif filter_type == "Sharpen": processed = original.filter(ImageFilter.SHARPEN) elif filter_type == "Edge Detection": processed = original.filter(ImageFilter.FIND_EDGES) elif filter_type == "Grayscale": processed = ImageOps.grayscale(original) processed = processed.convert("RGB") elif filter_type == "Sepia": processed = np.array(original) sepia_filter = np.array([[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]) processed = processed.dot(sepia_filter.T) processed = np.clip(processed, 0, 255).astype(np.uint8) processed = Image.fromarray(processed) elif filter_type == "Brightness +50%": enhancer = ImageEnhance.Brightness(original) processed = enhancer.enhance(1.5) else: processed = original return (original, processed) with gr.Blocks(title="Image Filter Comparison") as demo: gr.Markdown("# Image Filter Comparison Tool") gr.Markdown("Upload an image and select a filter to see the comparison") with gr.Row(): with gr.Column(): filter_dropdown = gr.Dropdown( choices=["Blur", "Sharpen", "Edge Detection", "Grayscale", "Sepia", "Brightness +50%"], value="Blur", label="Select Filter" ) with gr.Column(): slider = ImageSlider( label="Original vs Filtered", type="pil", position=0.5, slider_color="orange", height=600, show_download_button=True ) # Update on image upload slider.upload( fn=lambda im: apply_filter(im, "Blur"), inputs=slider, outputs=slider ) # Update when filter changes filter_dropdown.change( fn=apply_filter, inputs=[slider, filter_dropdown], outputs=slider ) demo.launch() # Expected output: Interactive tool where users upload an image and select # filters from dropdown. The slider shows original vs filtered version with # an orange draggable separator. Users can download both images. ``` -------------------------------- ### Single Image Upload with Processing Function Source: https://context7.com/pngwn/gradio-imageslider/llms.txt Sets up a Gradio interface where users upload a single image, and the `ImageSlider` component automatically applies image processing functions (like blur or contrast enhancement) to generate a comparison. The `upload` event is used to trigger these processing functions. ```python import gradio as gr from gradio_imageslider import ImageSlider from PIL import ImageFilter, ImageEnhance, Image def apply_blur(im): """Apply Gaussian blur to the uploaded image""" if not im or not im[0]: return im original = im[0] blurred = original.filter(filter=ImageFilter.GaussianBlur(radius=10)) return (original, blurred) def enhance_contrast(im): """Increase image contrast for comparison""" if not im or not im[0]: return im original = im[0] enhancer = ImageEnhance.Contrast(original) enhanced = enhancer.enhance(2.0) return (original, enhanced) with gr.Blocks() as demo: with gr.Row(): blur_slider = ImageSlider( label="Blur Comparison", type="pil", slider_color="blue" ) blur_slider.upload(apply_blur, inputs=blur_slider, outputs=blur_slider) contrast_slider = ImageSlider( label="Contrast Enhancement", type="pil", slider_color="green" ) contrast_slider.upload( enhance_contrast, inputs=contrast_slider, outputs=contrast_slider ) demo.launch() # Expected output: Interactive interface where uploading an image to blur_slider # shows original vs blurred version, and contrast_slider shows original vs # enhanced contrast version with draggable sliders ``` -------------------------------- ### Gradio ImageSlider with Event Tracking and Effects Source: https://context7.com/pngwn/gradio-imageslider/llms.txt This Python code integrates the ImageSlider with Gradio's event system. It tracks image uploads using state, applies blur and brightness effects via sliders, and updates an upload history. The 'upload' event logs timestamps, 'change' updates the history display, and 'click' applies custom image processing. ```python import gradio as gr from gradio_imageslider import ImageSlider from PIL import ImageFilter, ImageEnhance import time def track_changes(im, history): """Track image changes in state""" if not im or not im[0]: return im, history, "No image uploaded" timestamp = time.strftime("%H:%M:%S") history.append(f"Image uploaded at {timestamp}") status = f"Total uploads: {len(history)}" return im, history, status def apply_multiple_effects(im, blur_amount, brightness): """Apply multiple effects with custom parameters""" if not im or not im[0]: return None original = im[0] # Apply blur processed = original.filter(ImageFilter.GaussianBlur(radius=blur_amount)) # Apply brightness adjustment enhancer = ImageEnhance.Brightness(processed) processed = enhancer.enhance(brightness) return (original, processed) with gr.Blocks() as demo: gr.Markdown("## Advanced ImageSlider Integration") # State to track history state_history = gr.State([]) with gr.Row(): with gr.Column(): slider = ImageSlider( label="Multi-Effect Comparison", type="pil", position=0.5, slider_color="gold", height=400 ) status_text = gr.Textbox(label="Status", interactive=False) blur_control = gr.Slider( minimum=0, maximum=20, value=5, step=1, label="Blur Radius" ) brightness_control = gr.Slider( minimum=0.5, maximum=2.0, value=1.0, step=0.1, label="Brightness" ) apply_btn = gr.Button("Apply Effects", variant="primary") with gr.Column(): history_box = gr.JSON(label="Upload History") # Upload event: track in state slider.upload( fn=track_changes, inputs=[slider, state_history], outputs=[slider, state_history, status_text] ) # Change event: update when slider moves slider.change( fn=lambda im, h: (im, h), inputs=[slider, state_history], outputs=[slider, history_box] ) # Button click: apply custom effects apply_btn.click( fn=apply_multiple_effects, inputs=[slider, blur_control, brightness_control], outputs=slider ) demo.launch() ``` -------------------------------- ### Python: Process Images with NumPy Arrays and File Paths using ImageSlider Source: https://context7.com/pngwn/gradio-imageslider/llms.txt This Python code demonstrates how to use Gradio's ImageSlider component to process images represented as NumPy arrays and file paths. The `numpy_processing` function manipulates color channels of a NumPy array, while `filepath_processing` adds a watermark to an image opened from a file path. Both functions return processed image data, which is then displayed by the ImageSlider. ```python import gradio as gr from gradio_imageslider import ImageSlider import numpy as np from PIL import Image, ImageDraw, ImageFont def numpy_processing(im): """Process images using numpy arrays""" if not im or not im[0]: return im # Input is numpy array due to type="numpy" original_array = im[0] # Apply color channel manipulation processed_array = original_array.copy() processed_array[:, :, 0] = np.clip(processed_array[:, :, 0] * 1.3, 0, 255) # Boost red processed_array[:, :, 2] = np.clip(processed_array[:, :, 2] * 0.7, 0, 255) # Reduce blue return (original_array, processed_array.astype(np.uint8)) def filepath_processing(im): """Process images from file paths""" if not im or not im[0]: return im # Input is filepath string due to type="filepath" original_path = im[0] original = Image.open(original_path) # Add watermark watermarked = original.copy() draw = ImageDraw.Draw(watermarked) text = "PROCESSED" # Use default font draw.text((10, 10), text, fill=(255, 255, 255, 128)) # ImageSlider will save to temp file automatically return (original, watermarked) with gr.Blocks() as demo: gr.Markdown("## Image Format Types Demo") with gr.Row(): with gr.Column(): gr.Markdown("### NumPy Array Processing") numpy_slider = ImageSlider( label="Color Channel Adjustment", type="numpy", # Returns numpy.ndarray slider_color="cyan" ) numpy_slider.upload(numpy_processing, numpy_slider, numpy_slider) with gr.Column(): gr.Markdown("### File Path Processing") filepath_slider = ImageSlider( label="Watermark Addition", type="filepath", # Returns file paths slider_color="magenta" ) filepath_slider.upload(filepath_processing, filepath_slider, filepath_slider) demo.launch() # Expected output: Two sliders demonstrating different format types. # Left slider (numpy) shows color-adjusted image with cyan separator. # Right slider (filepath) shows watermarked image with magenta separator. # Processing functions receive data in specified formats. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.