svjack commited on
Commit
d64bbca
·
verified ·
1 Parent(s): 7e5d0d8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -0
app.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import imageio
4
+ from PIL import Image
5
+ import os
6
+
7
+ # 定义颜色列表,每个颜色对应一个 mask
8
+ colors = [
9
+ '#000000', # 背景色
10
+ '#2692F3', # 蓝色
11
+ '#F89E12', # 橙色
12
+ '#16C232', # 绿色
13
+ '#F92F6C', # 粉色
14
+ '#AC6AEB', # 紫色
15
+ ]
16
+
17
+ # 将颜色转换为 RGB 值
18
+ palette = np.array([
19
+ tuple(int(s[i + 1:i + 3], 16) for i in (0, 2, 4))
20
+ for s in colors[1:] # 跳过背景色
21
+ ]) # (N, 3)
22
+
23
+ # 计算颜色距离
24
+ def color_distance(c1, c2):
25
+ return np.sqrt(np.sum((c1 - c2) ** 2, axis=-1))
26
+
27
+ # 处理用户绘制的图像,生成 mask
28
+ def process_image(img):
29
+ # 保存用户上传的图像(包含绘制的掩码)
30
+ imageio.imwrite("output_image.png", img["composite"])
31
+
32
+ # 提取用户绘制的图层
33
+ user_input = np.asarray(img["layers"][0]) # (H, W, 4)
34
+ height, width, _ = user_input.shape
35
+
36
+ # 提取 alpha 通道作为前景 mask
37
+ alpha_channel = user_input[..., 3] # (H, W)
38
+ foreground_mask = alpha_channel > 0 # 用户绘制的区域
39
+
40
+ # 提取 RGB 通道
41
+ user_input_rgb = user_input[..., :3] # (H, W, 3)
42
+
43
+ # 使用颜色距离生成 mask
44
+ masks = []
45
+ for i, color in enumerate(palette):
46
+ distance = color_distance(user_input_rgb, color)
47
+ mask = (distance < 100) # 调整颜色偏差阈值
48
+ mask = mask * foreground_mask # 只保留用户绘制的区域
49
+ masks.append(mask)
50
+
51
+ # 生成合并后的 mask(使用对应颜色的 RGB 值)
52
+ merged_mask = np.zeros((height, width, 3), dtype=np.uint8) # RGB 图像
53
+ for i, mask in enumerate(masks):
54
+ merged_mask[mask] = palette[i] # 使用对应颜色填充
55
+
56
+ # 将 mask 转换为 PIL 图像(使用对应颜色的 RGB 值)
57
+ mask_images = []
58
+ for i, mask in enumerate(masks):
59
+ mask_array = np.zeros((height, width, 3), dtype=np.uint8) # RGB 图像
60
+ mask_array[mask] = palette[i] # 使用对应颜色填充
61
+ mask_image = Image.fromarray(mask_array, mode='RGB')
62
+ mask_images.append(mask_image)
63
+
64
+ merged_mask_image = Image.fromarray(merged_mask, mode='RGB')
65
+
66
+ # 保存 mask 到本地
67
+ output_dir = "output_masks"
68
+ os.makedirs(output_dir, exist_ok=True)
69
+ for i, mask_image in enumerate(mask_images):
70
+ mask_image.save(f"{output_dir}/mask_{i + 1}.png")
71
+ merged_mask_image.save(f"{output_dir}/merged_mask.png")
72
+
73
+ print(f"Masks saved to {output_dir}")
74
+ return img["background"], *mask_images, merged_mask_image
75
+
76
+ # Gradio 界面
77
+ with gr.Blocks() as demo:
78
+ # 添加 HTML 标题和介绍
79
+ gr.Markdown("""
80
+ # 🎨 **Multi-Color Mask Generator**
81
+ Welcome to the **Multi-Color Mask Generator**! This tool allows you to upload an image, draw masks using different colors, and generate corresponding mask images. Each mask is saved as an RGB image, and a merged mask is also created for your convenience.
82
+ """)
83
+
84
+ with gr.Row():
85
+ # 左侧:用户上传图像并绘制掩码
86
+ with gr.Column():
87
+ gr.Markdown("### 🖌️ **Draw Your Mask**")
88
+ img = gr.ImageEditor(
89
+ image_mode='RGBA',
90
+ sources=['upload'], # 允许用户上传图像
91
+ transforms=[], # 禁用变换功能
92
+ brush=gr.Brush(
93
+ colors=colors[1:], # 设置画笔颜色
94
+ color_mode="fixed",
95
+ ),
96
+ type='pil',
97
+ label="Draw Mask",
98
+ height=800, # 设置较高的纵向高度
99
+ width=600, # 设置宽度
100
+ )
101
+ # 右侧:显示处理后的图像
102
+ with gr.Column():
103
+ gr.Markdown("### 🖼️ **Generated Masks**")
104
+ img1 = gr.Image(label="Background Image", show_label=True) # 显示背景图像
105
+ img2 = gr.Image(label="Mask 1 (Blue)", show_label=True) # 显示蓝色掩码
106
+ img3 = gr.Image(label="Mask 2 (Orange)", show_label=True) # 显示橙色掩码
107
+ img4 = gr.Image(label="Mask 3 (Green)", show_label=True) # 显示绿色掩码
108
+ img5 = gr.Image(label="Mask 4 (Pink)", show_label=True) # 显示粉色掩码
109
+ img6 = gr.Image(label="Mask 5 (Purple)", show_label=True) # 显示紫色掩码
110
+ img7 = gr.Image(label="Merged Mask", show_label=True) # 显示合并后的掩码
111
+
112
+ # 按钮:触发图像处理
113
+ btn = gr.Button("Generate Masks")
114
+ btn.click(process_image, img, [img1, img2, img3, img4, img5, img6, img7])
115
+
116
+ # 添加 HTML 结尾
117
+ gr.Markdown("""
118
+ ## 📝 **How to Use**
119
+ 1. Upload an image using the **Draw Mask** section.
120
+ 2. Use the brush tool to draw masks with different colors.
121
+ 3. Click the **Generate Masks** button to create and save the masks.
122
+ 4. View the generated masks on the right side.
123
+
124
+ ## 📂 **Output**
125
+ - Each mask is saved as an RGB image in the `output_masks` directory.
126
+ - A merged mask is also generated for your convenience.
127
+
128
+ ## 🚀 **Enjoy!**
129
+ """)
130
+
131
+ # 启动应用
132
+ demo.launch(debug=True, share=True)