File size: 1,815 Bytes
f41e267
 
 
 
90d0892
f41e267
 
41cb532
 
 
 
 
 
 
 
 
 
16fdd22
41cb532
 
 
 
f41e267
41cb532
 
 
f41e267
41cb532
f41e267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41cb532
f41e267
 
41cb532
f41e267
 
 
 
 
 
 
475f71c
f41e267
 
90d0892
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import gradio as gr
from PIL import Image, ImageDraw
from transparent_background import Remover
import numpy as np
from gradio_imageslider import ImageSlider


def resize(img: Image, target_size_px: int):
    aspect_ratio = img.width / img.height

    if img.width > img.height:
        new_width = target_size_px
        new_height = int(target_size_px / aspect_ratio)
    else:
        new_height = target_size_px
        new_width = int(target_size_px * aspect_ratio)

    img = img.resize((new_width, new_height))

    return img


def infer(img: Image):

    img_resized = resize(img, 512)

    remover = Remover(mode="fast")
    masked_image = remover.process(img_resized, 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_resized)
    draw.rectangle([(min_x, min_y), (max_x, max_y)], outline="red", width=2)

    return img_resized, 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 [transparent-background](https://github.com/plemeri/transparent-background) library, which is built on [InSPyReNet](https://github.com/plemeri/inspyrenet).
    """,
    inputs=gr.components.Image(type="pil", label="Input Image"),
    outputs=ImageSlider(label="Output", type="pil"),
    title="Salient Object Detection",
).launch()