vlaadkshl commited on
Commit
1ba3fc8
·
verified ·
1 Parent(s): bc5a680

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -0
app.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import numpy as np
4
+ from PIL import Image
5
+ from ultralytics import SAM
6
+
7
+ model = SAM('sam_b.pt')
8
+
9
+
10
+ def process_image(input_image):
11
+ if input_image is None:
12
+ return None, "Can't find photo", 0
13
+
14
+ input_image = np.array(input_image)
15
+ bgr_image = cv2.cvtColor(input_image, cv2.COLOR_RGB2BGR)
16
+
17
+ r = model(bgr_image)[0]
18
+ masks = r.masks.xy
19
+
20
+ # point = (x, y)
21
+ # segment_index = point_in_mask(masks, point)
22
+
23
+ im_array = r.plot().astype(np.uint8)
24
+ im_array = cv2.cvtColor(im_array, cv2.COLOR_BGR2RGB)
25
+ im_pil = Image.fromarray(im_array)
26
+
27
+ # cv2.circle(im_array, point, radius=5, color=(255, 255, 0), thickness=2)
28
+
29
+ return im_pil
30
+
31
+
32
+ def point_in_mask(masks, point):
33
+ x, y = point
34
+ for i in range(len(masks) - 1, -1, -1):
35
+ mask = np.array(masks[i])
36
+ min_x = min(mask[:, 0])
37
+ max_x = max(mask[:, 0])
38
+ min_y = min(mask[:, 1])
39
+ max_y = max(mask[:, 1])
40
+ if min_x <= x <= max_x and min_y <= y <= max_y:
41
+ return i
42
+ return None
43
+
44
+
45
+ iface = gr.Interface(
46
+ fn=process_image,
47
+ inputs=[gr.Image()],
48
+ outputs=[gr.Image(type="numpy")],
49
+ title="Image Segmenter",
50
+ description="Upload an image to segment."
51
+ )
52
+
53
+ iface.launch()