RysonFeng commited on
Commit
6f49966
1 Parent(s): 9a7372a

Add app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+
4
+ with gr.Blocks() as demo:
5
+ tolerance = gr.Slider(label="Tolerance",
6
+ info="How different colors can be in a segment.",
7
+ minimum=0, maximum=256 * 3, value=50)
8
+ with gr.Row():
9
+ input_img = gr.Image(label="Input")
10
+ output_img = gr.Image(label="Selected Segment")
11
+
12
+
13
+ def get_select_coords(img, tolerance, evt: gr.SelectData):
14
+ visited_pixels = set()
15
+ pixels_in_queue = set()
16
+ pixels_in_segment = set()
17
+ start_pixel = img[evt.index[1], evt.index[0]]
18
+ pixels_in_queue.add((evt.index[1], evt.index[0]))
19
+ while len(pixels_in_queue) > 0:
20
+ pixel = pixels_in_queue.pop()
21
+ visited_pixels.add(pixel)
22
+ neighbors = []
23
+ if pixel[0] > 0:
24
+ neighbors.append((pixel[0] - 1, pixel[1]))
25
+ if pixel[0] < img.shape[0] - 1:
26
+ neighbors.append((pixel[0] + 1, pixel[1]))
27
+ if pixel[1] > 0:
28
+ neighbors.append((pixel[0], pixel[1] - 1))
29
+ if pixel[1] < img.shape[1] - 1:
30
+ neighbors.append((pixel[0], pixel[1] + 1))
31
+ for neighbor in neighbors:
32
+ if neighbor in visited_pixels:
33
+ continue
34
+ neighbor_pixel = img[neighbor[0], neighbor[1]]
35
+ if np.abs(neighbor_pixel - start_pixel).sum() < tolerance:
36
+ pixels_in_queue.add(neighbor)
37
+ pixels_in_segment.add(neighbor)
38
+
39
+ out = img.copy() * 0.2
40
+ out = out.astype(np.uint8)
41
+ for pixel in pixels_in_segment:
42
+ out[pixel[0], pixel[1]] = img[pixel[0], pixel[1]]
43
+ return out
44
+
45
+
46
+ input_img.select(get_select_coords, [input_img, tolerance], output_img)
47
+
48
+ if __name__ == "__main__":
49
+ demo.launch()