sagar007 commited on
Commit
dc23d39
·
verified ·
1 Parent(s): 54db35c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -10
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
  import numpy as np
3
- from PIL import Image, ImageDraw
4
  import torch
5
  from transformers import AutoProcessor, CLIPSegForImageSegmentation
6
 
@@ -19,16 +19,16 @@ def segment_everything(image):
19
  def segment_box(image, box):
20
  if box is None:
21
  return image
22
- x1, y1, x2, y2 = map(int, box)
23
- mask = Image.new('L', (image.shape[1], image.shape[0]), 0)
24
- draw = ImageDraw.Draw(mask)
25
- draw.rectangle([x1, y1, x2, y2], fill=255)
26
 
27
- inputs = processor(text=["object in box"], images=[image], mask_pixels=np.array(mask), padding="max_length", return_tensors="pt")
28
  with torch.no_grad():
29
  outputs = model(**inputs)
30
  preds = outputs.logits.squeeze().sigmoid()
31
- segmentation = (preds.numpy() * 255).astype(np.uint8)
 
 
32
  return Image.fromarray(segmentation)
33
 
34
  def update_image(image, segmentation):
@@ -43,8 +43,7 @@ with gr.Blocks() as demo:
43
  gr.Markdown("# Segment Anything-like Demo")
44
  with gr.Row():
45
  with gr.Column(scale=1):
46
- input_image = gr.Image(label="Input Image")
47
- box_input = gr.Box(label="Select Box")
48
  with gr.Row():
49
  everything_btn = gr.Button("Everything")
50
  box_btn = gr.Button("Box")
@@ -59,7 +58,7 @@ with gr.Blocks() as demo:
59
 
60
  box_btn.click(
61
  fn=segment_box,
62
- inputs=[input_image, box_input],
63
  outputs=[output_image]
64
  )
65
 
 
1
  import gradio as gr
2
  import numpy as np
3
+ from PIL import Image
4
  import torch
5
  from transformers import AutoProcessor, CLIPSegForImageSegmentation
6
 
 
19
  def segment_box(image, box):
20
  if box is None:
21
  return image
22
+ x1, y1, x2, y2 = box
23
+ cropped_image = image[y1:y2, x1:x2]
 
 
24
 
25
+ inputs = processor(text=["object"], images=[cropped_image], padding="max_length", return_tensors="pt")
26
  with torch.no_grad():
27
  outputs = model(**inputs)
28
  preds = outputs.logits.squeeze().sigmoid()
29
+
30
+ segmentation = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
31
+ segmentation[y1:y2, x1:x2] = (preds.numpy() * 255).astype(np.uint8)
32
  return Image.fromarray(segmentation)
33
 
34
  def update_image(image, segmentation):
 
43
  gr.Markdown("# Segment Anything-like Demo")
44
  with gr.Row():
45
  with gr.Column(scale=1):
46
+ input_image = gr.Image(label="Input Image", tool="select")
 
47
  with gr.Row():
48
  everything_btn = gr.Button("Everything")
49
  box_btn = gr.Button("Box")
 
58
 
59
  box_btn.click(
60
  fn=segment_box,
61
+ inputs=[input_image, input_image],
62
  outputs=[output_image]
63
  )
64