A component for measuring the distance in pixels between two points in an image.
Project description
gradio_imagemeasurement
A component for measuring the distance in pixels between two points in an image.
Installation
pip install gradio_imagemeasurement
Usage
import gradio as gr
from gradio_imagemeasurement import ImageMeasurement
def show_measurement(image_input, data: gr.EventData):
if data._data and 'distance_px' in data._data:
return f"{data._data}"
return "Click two dots on the image"
with gr.Blocks() as demo:
gr.Markdown("# ImageMeasurement")
gr.Markdown("Click two points on the image to measure the distance.")
with gr.Row():
image_input = ImageMeasurement(label="Image", sources="upload")
result = gr.Textbox(label="Result")
gr.Examples(
examples=[
"https://raw.githubusercontent.com/rybakov-ks/ParticleAnalyzer/refs/heads/main/example/Cathode_LiCoVO4.jpg",
"https://raw.githubusercontent.com/rybakov-ks/ParticleAnalyzer/refs/heads/main/example/Chitosan.webp",
"https://raw.githubusercontent.com/rybakov-ks/ParticleAnalyzer/refs/heads/main/example/Silicon_oxide.webp",
"https://raw.githubusercontent.com/rybakov-ks/ParticleAnalyzer/refs/heads/main/example/Gold_on_carbon.jpg",
"https://raw.githubusercontent.com/rybakov-ks/ParticleAnalyzer/refs/heads/main/example/Colloidal_silver.webp",
],
example_labels=[
"Cathode material LiCoVO₄",
"Chitosan nanoparticles",
"Silicon oxide",
"Gold on carbon",
"Colloidal silver",
],
inputs=[image_input],
label="Examples",
elem_id="examples_images",
)
image_input.measurement(fn=show_measurement, inputs=image_input, outputs=result)
if __name__ == "__main__":
demo.launch()
ImageMeasurement
Initialization
| name | type | default | description |
|---|---|---|---|
value |
str | PIL.Image.Image | np.ndarray | Callable | None
|
None |
A `PIL.Image`, `numpy.array`, `pathlib.Path`, or `str` filepath or URL for the default value that ImageMeasurement component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component. |
format |
str
|
"webp" |
File format (e.g. "png" or "gif"). Used 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 ImageMeasurement). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files. |
height |
int | str | None
|
None |
The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image. |
width |
int | str | None
|
None |
The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image. |
image_mode |
Literal[
"1",
"L",
"P",
"RGB",
"RGBA",
"CMYK",
"YCbCr",
"LAB",
"HSV",
"I",
"F",
]
| None
|
"RGB" |
The pixel format and color depth that the image should be loaded and preprocessed as. "RGB" will load the image as a color image, or "L" as black-and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other cases). |
sources |
list[Literal["upload", "webcam", "clipboard"]]
| Literal["upload", "webcam", "clipboard"]
| None
|
None |
List of sources for the 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. If None, defaults to ["upload", "webcam", "clipboard"] if streaming is False, otherwise defaults to ["webcam"]. |
type |
Literal["numpy", "pil", "filepath"]
|
"numpy" |
The format the image is converted before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. To support animated GIFs in input, the `type` should be set to "filepath" or "pil". To support SVGs, the `type` should be set to "filepath". |
label |
str | I18nData | 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 |
Timer | float | None
|
None |
Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer. |
inputs |
Component | Sequence[Component] | set[Component] | None
|
None |
Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. |
show_label |
bool | None
|
None |
if True, will display label. |
show_download_button |
bool
|
True |
If True, will display button to download image. Only applies if interactive is False (e.g. if the component is used as an output). |
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 | Literal["hidden"]
|
True |
If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM |
streaming |
bool
|
False |
If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'. If the component is an output component, will automatically convert images to base64. |
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 | tuple[int | str, ...] | None
|
None |
in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render. |
preserved_by_key |
list[str] | str | None
|
"value" |
A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor. |
mirror_webcam |
bool | None
|
None |
If True webcam will be mirrored. Default is True. |
webcam_options |
WebcamOptions | None
|
None |
None |
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. |
placeholder |
str | None
|
None |
Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading. |
show_fullscreen_button |
bool
|
True |
If True, will show a fullscreen icon in the corner of the component that allows user to view the image in fullscreen mode. If False, icon does not appear. |
webcam_constraints |
dict[str, Any] | None
|
None |
A dictionary that allows developers to specify custom media constraints for the webcam stream. This parameter provides flexibility to control the video stream's properties, such as resolution and front or rear camera on mobile devices. See $demo/webcam_constraints |
watermark |
WatermarkOptions | None
|
None |
If provided and this component is used to display a `value` image, the `watermark` image will be displayed on the bottom right of the `value` image, 10 pixels from the bottom and 10 pixels from the right. The watermark image will not be resized. Supports `PIL.Image`, `numpy.array`, `pathlib.Path`, and `str` filepaths. SVGs and GIFs are not supported as `watermark` images nor can they be watermarked. |
Events
| name | description |
|---|---|
clear |
This listener is triggered when the user clears the ImageMeasurement using the clear button for the component. |
change |
Triggered when the value of the ImageMeasurement 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. |
stream |
This listener is triggered when the user streams the ImageMeasurement. |
select |
Event listener for when the user selects or deselects the ImageMeasurement. Uses event data gradio.SelectData to carry value referring to the label of the ImageMeasurement, and selected to refer to state of the ImageMeasurement. See EventData documentation on how to use this event data |
upload |
This listener is triggered when the user uploads a file into the ImageMeasurement. |
input |
This listener is triggered when the user changes the value of the ImageMeasurement. |
measurement |
This listener is triggered when the user completes a measurement by clicking two points on the image. |
The event data contains the coordinates of both points and the calculated distance in pixels.
Returns:
dict: Measurement data with the following structure:
{
'point_a': {'x': int, 'y': int}, # Coordinates of first point
'point_b': {'x': int, 'y': int}, # Coordinates of second point
'distance_px': int # Distance between points in pixels
}
|
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 image as a
numpy.array,PIL.Imageorstrfilepath depending ontype. - As input: Should return, expects a
numpy.array,PIL.Image, orstrorpathlib.Pathfilepath to an image which is displayed.
def predict(
value: numpy.ndarray | PIL.Image.Image | str | None
) -> numpy.ndarray | PIL.Image.Image | str | pathlib.Path | None:
return value
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gradio_imagemeasurement-0.0.3-py3-none-any.whl.
File metadata
- Download URL: gradio_imagemeasurement-0.0.3-py3-none-any.whl
- Upload date:
- Size: 151.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
14b31cf272366782412dfe00b4872028eabf8584eebbfefae2dd30b79b78913c
|
|
| MD5 |
57534cc076ce4452a18bf8a1a2ac096f
|
|
| BLAKE2b-256 |
f50ff2dd93645c5ea393310f072499ee8adc20f4dc81b491f38e9f04e3b546e0
|