Skip to main content

Simplified ImageEditor with disabled overlay of brush-options.

Project description


tags: [gradio-custom-component, ImageEditor, image, mask, imagemask, editor, imageeditor, sketch, sketchpad, brush, simple] title: gradio_imagemask short_description: Simplified ImageEditor with disabled overlay of brush-options. colorFrom: blue colorTo: yellow sdk: gradio pinned: false app_file: space.py

gradio_imagemask

Static Badge

Simplified ImageEditor with disabled overlay of brush-options.

Installation

pip install gradio_imagemask

Usage

import gradio as gr
from gradio_imagemask import ImageMask


example = ImageMask().example_value()

demo = gr.Interface(
    lambda x:x,
    ImageMask(),  # interactive version of your component
    ImageMask(),  # static version of your component
    # examples=[[example]],  # uncomment this line to view the "example version" of your component
)


if __name__ == "__main__":
    demo.launch()

ImageMask

Initialization

name type default description
value
EditorValue | numpy.ndarray | PIL.Image.Image | str | None
None Optional initial image(s) to populate the image editor. Should be a dictionary with keys: `background`, `layers`, and `composite`. The values corresponding to `background` and `composite` should be images or None, while `layers` should be a list of images. Images can be of type PIL.Image, np.array, or str filepath/URL. Or, the value can be a callable, in which case the function will be called whenever the app loads to set the initial value of the component.
height
int | str | None
None The height of the component container, specified in pixels if a number is passed, or in CSS units if a string is passed.
width
int | str | None
None The width of the component container, specified in pixels if a number is passed, or in CSS units if a string is passed.
image_mode
"1"
    | "L"
    | "P"
    | "RGB"
    | "RGBA"
    | "CMYK"
    | "YCbCr"
    | "LAB"
    | "HSV"
    | "I"
    | "F"
"RGBA" "RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning.
sources
Iterable["upload" | "webcam" | "clipboard"] | None
"upload" List of sources that can be used to set the background image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard.
type
"numpy" | "pil" | "filepath"
"numpy" The format the images are converted to before being passed into the prediction function. "numpy" converts the images to numpy arrays with shape (height, width, 3) and values from 0 to 255, "pil" converts the images to PIL image objects, "filepath" passes images as str filepaths to temporary copies of the images.
label
str | None
None The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
every
float | None
None If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
show_label
bool | None
None if True, will display label.
show_download_button
bool
True If True, will display button to download image.
container
bool
True If True, will place the component in a container - providing some extra padding around the border.
scale
int | None
None relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
min_width
int
160 minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
interactive
bool | None
None if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.
visible
bool
True If False, component will be hidden.
elem_id
str | None
None 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
list[str] | str | None
None 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.
render
bool
True If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
key
int | str | None
None if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
mirror_webcam
bool
True If True webcam will be mirrored. Default is True.
show_share_button
bool | None
None 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.
_selectable
bool
False None
crop_size
tuple[int | float, int | float] | str | None
None The size of the crop box in pixels. If a tuple, the first value is the width and the second value is the height. If a string, the value must be a ratio in the form `width:height` (e.g. "16:9").
transforms
Iterable["crop"]
The transforms tools to make available to users. "crop" allows the user to crop the image.
eraser
Eraser | None | False
None The options for the eraser tool in the image editor. Should be an instance of the `gr.Eraser` class, or None to use the default settings. Can also be False to hide the eraser tool.
brush
Brush | None | False
Brush( default_size="auto", colors=["#000000"], default_color="auto", color_mode="fixed", ) The options for the brush tool in the image editor. Should be an instance of the `gr.Brush` class, or None to use the default settings. Can also be False to hide the brush tool, which will also hide the eraser tool.
format
str
"webp" Format to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. This parameter has no effect on SVG files.
layers
bool
False If True, will allow users to add layers to the image. If False, the layers option will be hidden.
canvas_size
tuple[int, int] | None
None The size of the default canvas in pixels. If a tuple, the first value is the width and the second value is the height. If None, the canvas size will be the same as the background image or 800 x 600 if no background image is provided.

Events

name description
clear This listener is triggered when the user clears the ImageMask using the X button for the component.
change Triggered when the value of the ImageMask 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.
input This listener is triggered when the user changes the value of the ImageMask.
select Event listener for when the user selects or deselects the ImageMask. Uses event data gradio.SelectData to carry value referring to the label of the ImageMask, and selected to refer to state of the ImageMask. See EventData documentation on how to use this event data
upload This listener is triggered when the user uploads a file into the ImageMask.
apply This listener is triggered when the user applies changes to the ImageMask through an integrated UI action.

User function

The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).

  • When used as an Input, the component only impacts the input signature of the user function.
  • When used as an output, the component only impacts the return signature of the user function.

The code snippet below is accurate in cases where the component is used as both an input and an output.

  • As output: Is passed, passes the uploaded images as an instance of EditorValue, which is just a dict with keys: 'background', 'layers', and 'composite'. The values corresponding to 'background' and 'composite' are images, while 'layers' is a list of images. The images are of type PIL.Image, np.array, or str filepath, depending on the type parameter.
  • As input: Should return, expects a EditorValue, which is just a dictionary with keys: 'background', 'layers', and 'composite'. The values corresponding to 'background' and 'composite' should be images or None, while layers should be a list of images. Images can be of type PIL.Image, np.array, or str filepath/URL. Or, the value can be simply a single image (ImageType), in which case it will be used as the background.
def predict(
    value: EditorValue | None
) -> EditorValue | numpy.ndarray | PIL.Image.Image | str | None:
    return value

EditorValue

class EditorValue(TypedDict):
    background: Optional[ImageType]
    layers: list[ImageType]
    composite: Optional[ImageType]

Eraser

@dataclasses.dataclass
class Eraser:
    default_size: int | Literal["auto"] = "auto"

Brush

@dataclasses.dataclass
class Brush(Eraser):
    colors: Union[
        list[str],
        str,
        None,
    ] = None
    default_color: Union[str, Literal["auto"]] = "auto"
    color_mode: Literal["fixed", "defaults"] = "defaults"

    def __post_init__(self):
        if self.colors is None:
            self.colors = [
                "rgb(204, 50, 50)",
                "rgb(173, 204, 50)",
                "rgb(50, 204, 112)",
                "rgb(50, 112, 204)",
                "rgb(173, 50, 204)",
            ]
        if self.default_color is None:
            self.default_color = (
                self.colors[0]
                if isinstance(self.colors, list)
                else self.colors
            )

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gradio_imagemask-0.0.1.tar.gz (408.3 kB view hashes)

Uploaded Source

Built Distribution

gradio_imagemask-0.0.1-py3-none-any.whl (335.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page