nihuajian commited on
Commit
4ee3c69
·
verified ·
1 Parent(s): d64d56e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +310 -0
app.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ ClearAI - 图像增强应用
5
+ 作者: ClearAI Team
6
+ 描述: 基于Gradio的图像到图像处理应用,提供图像增强功能
7
+ """
8
+
9
+ import gradio as gr
10
+ import numpy as np
11
+ from PIL import Image, ImageEnhance, ImageFilter
12
+ import cv2
13
+ import logging
14
+
15
+ # 配置日志
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
+
19
+ class ImageProcessor:
20
+ """图像处理器类,包含各种图像增强方法"""
21
+
22
+ def __init__(self):
23
+ logger.info("初始化图像处理器")
24
+
25
+ def enhance_image(self, image, enhancement_type="auto"):
26
+ """
27
+ 图像增强主函数
28
+
29
+ 参数:
30
+ image: PIL.Image对象 - 输入图像
31
+ enhancement_type: str - 增强类型 ("auto", "sharpen", "brightness", "contrast")
32
+
33
+ 返回:
34
+ PIL.Image对象 - 增强后的图像
35
+ """
36
+ try:
37
+ if image is None:
38
+ logger.error("输入图像为空")
39
+ return None
40
+
41
+ logger.info(f"开始处理图像,增强类型: {enhancement_type}")
42
+
43
+ # 转换为RGB模式(如果不是的话)
44
+ if image.mode != 'RGB':
45
+ image = image.convert('RGB')
46
+
47
+ # 根据增强类型选择处理方法
48
+ if enhancement_type == "auto":
49
+ enhanced_image = self._auto_enhance(image)
50
+ elif enhancement_type == "sharpen":
51
+ enhanced_image = self._sharpen_image(image)
52
+ elif enhancement_type == "brightness":
53
+ enhanced_image = self._adjust_brightness(image)
54
+ elif enhancement_type == "contrast":
55
+ enhanced_image = self._adjust_contrast(image)
56
+ else:
57
+ enhanced_image = self._auto_enhance(image)
58
+
59
+ logger.info("图像处理完成")
60
+ return enhanced_image
61
+
62
+ except Exception as e:
63
+ logger.error(f"图像处理出错: {str(e)}")
64
+ return image # 出错时返回原图像
65
+
66
+ def _auto_enhance(self, image):
67
+ """
68
+ 自动图像增强
69
+ 综合应用多种增强技术
70
+ """
71
+ # 1. 轻微锐化
72
+ sharpened = image.filter(ImageFilter.UnsharpMask(radius=1.5, percent=150, threshold=3))
73
+
74
+ # 2. 调整对比度
75
+ contrast_enhancer = ImageEnhance.Contrast(sharpened)
76
+ contrasted = contrast_enhancer.enhance(1.1)
77
+
78
+ # 3. 调整亮度
79
+ brightness_enhancer = ImageEnhance.Brightness(contrasted)
80
+ brightened = brightness_enhancer.enhance(1.05)
81
+
82
+ # 4. 调整饱和度
83
+ color_enhancer = ImageEnhance.Color(brightened)
84
+ final_image = color_enhancer.enhance(1.1)
85
+
86
+ return final_image
87
+
88
+ def _sharpen_image(self, image):
89
+ """图像锐化"""
90
+ # 使用UnsharpMask滤镜进行锐化
91
+ sharpened = image.filter(ImageFilter.UnsharpMask(radius=2, percent=200, threshold=3))
92
+ return sharpened
93
+
94
+ def _adjust_brightness(self, image):
95
+ """调整亮度"""
96
+ enhancer = ImageEnhance.Brightness(image)
97
+ return enhancer.enhance(1.2) # 增加20%亮度
98
+
99
+ def _adjust_contrast(self, image):
100
+ """调整对比度"""
101
+ enhancer = ImageEnhance.Contrast(image)
102
+ return enhancer.enhance(1.3) # 增加30%对比度
103
+
104
+ def color_correction(self, image):
105
+ """
106
+ 颜色校正
107
+ 自动调整图像的色彩平衡和饱和度
108
+ """
109
+ try:
110
+ # 转换为numpy数组进行处理
111
+ img_array = np.array(image)
112
+
113
+ # 转换到LAB色彩空间进行颜色校正
114
+ lab = cv2.cvtColor(img_array, cv2.COLOR_RGB2LAB)
115
+
116
+ # 分离L、A、B通道
117
+ l, a, b = cv2.split(lab)
118
+
119
+ # 对L通道进行直方图均衡化(改善亮度分布)
120
+ l = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)).apply(l)
121
+
122
+ # 重新合并通道
123
+ lab = cv2.merge([l, a, b])
124
+
125
+ # 转换回RGB色彩空间
126
+ corrected = cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)
127
+
128
+ # 转换回PIL图像
129
+ corrected_image = Image.fromarray(corrected)
130
+
131
+ # 进一步调整饱和度
132
+ color_enhancer = ImageEnhance.Color(corrected_image)
133
+ final_image = color_enhancer.enhance(1.15) # 增加15%饱和度
134
+
135
+ return final_image
136
+
137
+ except Exception as e:
138
+ logger.error(f"颜色校正处理出错: {str(e)}")
139
+ return image
140
+
141
+ # 创建全局图像处理器实例
142
+ processor = ImageProcessor()
143
+
144
+ def process_image(input_image, apply_color_correction):
145
+ """
146
+ Gradio接口函数
147
+
148
+ 参数:
149
+ input_image: 输入图像
150
+ apply_color_correction: 是否应用颜色校正
151
+
152
+ 返回:
153
+ 处理后的图像
154
+ """
155
+ if input_image is None:
156
+ return None
157
+
158
+ try:
159
+ # 自动图像增强
160
+ enhanced_image = processor.enhance_image(input_image, "auto")
161
+
162
+ # 可选的颜色校正处理
163
+ if apply_color_correction:
164
+ enhanced_image = processor.color_correction(enhanced_image)
165
+
166
+ return enhanced_image
167
+
168
+ except Exception as e:
169
+ logger.error(f"处理图像时发生错误: {str(e)}")
170
+ return input_image
171
+
172
+ def create_gradio_interface():
173
+ """创建Gradio界面"""
174
+
175
+ # 自定义CSS样式
176
+ css = """
177
+ .gradio-container {
178
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
179
+ }
180
+ .header {
181
+ text-align: center;
182
+ margin-bottom: 30px;
183
+ }
184
+ .footer {
185
+ text-align: center;
186
+ margin-top: 30px;
187
+ color: #666;
188
+ }
189
+ """
190
+
191
+ # 创建Gradio界面
192
+ with gr.Blocks(css=css, title="ClearAI - 图像增强") as demo:
193
+
194
+ # 标题和描述
195
+ gr.HTML("""
196
+ <div class="header">
197
+ <h1>🏢 ClearAI - 图像增强应用</h1>
198
+ <p>上传您的图像,选择增强类型,获得更清晰的图像效果</p>
199
+ </div>
200
+ """)
201
+
202
+ # 主要界面布局
203
+ with gr.Row():
204
+ # 左侧:输入区域
205
+ with gr.Column(scale=1):
206
+ gr.HTML("<h3>📤 输入图像</h3>")
207
+ input_image = gr.Image(
208
+ type="pil",
209
+ label="上传图像",
210
+ height=400
211
+ )
212
+
213
+ # 控制选项
214
+ gr.HTML("<h3>⚙️ 处理选项</h3>")
215
+ gr.HTML("<p>✨ 自动增强模式:智能优化图像清晰度、对比度和亮度</p>")
216
+
217
+ apply_color_correction = gr.Checkbox(
218
+ label="应用颜色校正",
219
+ value=False,
220
+ info="自动调整图像色彩平衡和饱和度(处理时间会稍微增加)"
221
+ )
222
+
223
+ # 处理按钮
224
+ process_btn = gr.Button(
225
+ "🚀 处理图像",
226
+ variant="primary",
227
+ size="lg"
228
+ )
229
+
230
+ # 右侧:输出区域
231
+ with gr.Column(scale=1):
232
+ gr.HTML("<h3>📥 增强结果</h3>")
233
+ output_image = gr.Image(
234
+ type="pil",
235
+ label="增强后图像",
236
+ height=400
237
+ )
238
+
239
+ # 示例图像区域
240
+ gr.HTML("<h3>💡 使用示例</h3>")
241
+ gr.Examples(
242
+ examples=[
243
+ [False],
244
+ [True],
245
+ ],
246
+ inputs=[apply_color_correction],
247
+ label="预设配置"
248
+ )
249
+
250
+ # 使用说明
251
+ with gr.Accordion("📖 使用说明", open=False):
252
+ gr.Markdown("""
253
+ ### 如何使用:
254
+ 1. **上传图像**:点击上传区域或拖拽图像文件
255
+ 2. **自动增强**:应用会自动优化图像的清晰度、对比度和亮度
256
+ 3. **可选颜色校正**:勾选后会进行色彩平衡和饱和度调整
257
+ - 使用LAB色彩空间进行专业级颜色校正
258
+ - 自动改善图像的色彩分布
259
+ - 增强图像的色彩饱和度
260
+ 4. **点击处理**:点击"处理图像"按钮开始处理
261
+ 5. **查看结果**:在右侧查看增强后的图像
262
+ 6. **下载图像**:右键点击结果图像可以保存
263
+
264
+ ### 支持格式:
265
+ - PNG, JPG, JPEG, BMP, TIFF, WEBP
266
+
267
+ ### 注意事项:
268
+ - 建议图像大小不超过10MB
269
+ - 颜色校正会稍微增加处理时间
270
+ - 处理时间取决于图像大小和复杂度
271
+ - 自动增强适用于大多数图像类型
272
+ """)
273
+
274
+ # 绑定处理函数
275
+ process_btn.click(
276
+ fn=process_image,
277
+ inputs=[input_image, apply_color_correction],
278
+ outputs=output_image,
279
+ show_progress=True
280
+ )
281
+
282
+ # 页脚信息
283
+ gr.HTML("""
284
+ <div class="footer">
285
+ <p>🚀 由 <strong>ClearAI</strong> 提供技术支持 | 基于 Gradio 构建</p>
286
+ <p>💡 如有问题或建议,请在 Hugging Face Space 页面留言</p>
287
+ </div>
288
+ """)
289
+
290
+ return demo
291
+
292
+ def main():
293
+ """主函数"""
294
+ logger.info("启动ClearAI图像增强应用")
295
+
296
+ # 创建Gradio界面
297
+ demo = create_gradio_interface()
298
+
299
+ # 启动应用
300
+ demo.launch(
301
+ server_name="0.0.0.0",
302
+ server_port=7860,
303
+ share=False,
304
+ show_error=True,
305
+ show_tips=True,
306
+ enable_queue=True
307
+ )
308
+
309
+ if __name__ == "__main__":
310
+ main()