File size: 1,428 Bytes
f41e267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import gradio as gr
from PIL import Image, ImageDraw
from transparent_background import Remover
import numpy as np


def infer(img: Image):
    remover = Remover(mode="fast")
    masked_image = remover.process(img, type="map")

    gray_image = masked_image.convert("L")
    binary_image = gray_image.point(lambda x: 0 if x < 128 else 255, "1")

    image_array = np.array(binary_image)
    white_pixels = np.where(image_array == True)

    x_coords = white_pixels[1]
    y_coords = white_pixels[0]

    min_x = np.min(x_coords)
    max_x = np.max(x_coords)
    min_y = np.min(y_coords)
    max_y = np.max(y_coords)

    draw = ImageDraw.Draw(img)
    draw.rectangle([(min_x, min_y), (max_x, max_y)], outline="red", width=2)

    return img, masked_image


gr.Interface(
    fn=infer,
    description="""
    This space performs salient object detection on an image uploaded by the user. I.e. it will detect the object(s) in the image foreground and draw a red rectangle around it.
    
    It uses the [transparente-background](https://github.com/plemeri/transparent-background) library, which is build on [InSPyReNet](https://github.com/plemeri/inspyrenet).
    """,
    inputs=gr.components.Image(type="pil", label="Input Image"),
    outputs=[
        gr.components.Image(type="pil", label="Output Image"),
        gr.components.Image(type="pil", label="Image Mask"),
    ],
    title="Salient Object Detection",
).launch()