File size: 9,951 Bytes
4ee3c69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea373d1
4ee3c69
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ClearAI - 图像增强应用
作者: ClearAI Team
描述: 基于Gradio的图像到图像处理应用,提供图像增强功能
"""

import gradio as gr
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter
import cv2
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ImageProcessor:
    """图像处理器类,包含各种图像增强方法"""
    
    def __init__(self):
        logger.info("初始化图像处理器")
    
    def enhance_image(self, image, enhancement_type="auto"):
        """
        图像增强主函数
        
        参数:
            image: PIL.Image对象 - 输入图像
            enhancement_type: str - 增强类型 ("auto", "sharpen", "brightness", "contrast")
        
        返回:
            PIL.Image对象 - 增强后的图像
        """
        try:
            if image is None:
                logger.error("输入图像为空")
                return None
            
            logger.info(f"开始处理图像,增强类型: {enhancement_type}")
            
            # 转换为RGB模式(如果不是的话)
            if image.mode != 'RGB':
                image = image.convert('RGB')
            
            # 根据增强类型选择处理方法
            if enhancement_type == "auto":
                enhanced_image = self._auto_enhance(image)
            elif enhancement_type == "sharpen":
                enhanced_image = self._sharpen_image(image)
            elif enhancement_type == "brightness":
                enhanced_image = self._adjust_brightness(image)
            elif enhancement_type == "contrast":
                enhanced_image = self._adjust_contrast(image)
            else:
                enhanced_image = self._auto_enhance(image)
            
            logger.info("图像处理完成")
            return enhanced_image
            
        except Exception as e:
            logger.error(f"图像处理出错: {str(e)}")
            return image  # 出错时返回原图像
    
    def _auto_enhance(self, image):
        """
        自动图像增强
        综合应用多种增强技术
        """
        # 1. 轻微锐化
        sharpened = image.filter(ImageFilter.UnsharpMask(radius=1.5, percent=150, threshold=3))
        
        # 2. 调整对比度
        contrast_enhancer = ImageEnhance.Contrast(sharpened)
        contrasted = contrast_enhancer.enhance(1.1)
        
        # 3. 调整亮度
        brightness_enhancer = ImageEnhance.Brightness(contrasted)
        brightened = brightness_enhancer.enhance(1.05)
        
        # 4. 调整饱和度
        color_enhancer = ImageEnhance.Color(brightened)
        final_image = color_enhancer.enhance(1.1)
        
        return final_image
    
    def _sharpen_image(self, image):
        """图像锐化"""
        # 使用UnsharpMask滤镜进行锐化
        sharpened = image.filter(ImageFilter.UnsharpMask(radius=2, percent=200, threshold=3))
        return sharpened
    
    def _adjust_brightness(self, image):
        """调整亮度"""
        enhancer = ImageEnhance.Brightness(image)
        return enhancer.enhance(1.2)  # 增加20%亮度
    
    def _adjust_contrast(self, image):
        """调整对比度"""
        enhancer = ImageEnhance.Contrast(image)
        return enhancer.enhance(1.3)  # 增加30%对比度
    
    def color_correction(self, image):
        """
        颜色校正
        自动调整图像的色彩平衡和饱和度
        """
        try:
            # 转换为numpy数组进行处理
            img_array = np.array(image)
            
            # 转换到LAB色彩空间进行颜色校正
            lab = cv2.cvtColor(img_array, cv2.COLOR_RGB2LAB)
            
            # 分离L、A、B通道
            l, a, b = cv2.split(lab)
            
            # 对L通道进行直方图均衡化(改善亮度分布)
            l = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)).apply(l)
            
            # 重新合并通道
            lab = cv2.merge([l, a, b])
            
            # 转换回RGB色彩空间
            corrected = cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)
            
            # 转换回PIL图像
            corrected_image = Image.fromarray(corrected)
            
            # 进一步调整饱和度
            color_enhancer = ImageEnhance.Color(corrected_image)
            final_image = color_enhancer.enhance(1.15)  # 增加15%饱和度
            
            return final_image
            
        except Exception as e:
            logger.error(f"颜色校正处理出错: {str(e)}")
            return image

# 创建全局图像处理器实例
processor = ImageProcessor()

def process_image(input_image, apply_color_correction):
    """
    Gradio接口函数
    
    参数:
        input_image: 输入图像
        apply_color_correction: 是否应用颜色校正
    
    返回:
        处理后的图像
    """
    if input_image is None:
        return None
    
    try:
        # 自动图像增强
        enhanced_image = processor.enhance_image(input_image, "auto")
        
        # 可选的颜色校正处理
        if apply_color_correction:
            enhanced_image = processor.color_correction(enhanced_image)
        
        return enhanced_image
        
    except Exception as e:
        logger.error(f"处理图像时发生错误: {str(e)}")
        return input_image

def create_gradio_interface():
    """创建Gradio界面"""
    
    # 自定义CSS样式
    css = """
    .gradio-container {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    .header {
        text-align: center;
        margin-bottom: 30px;
    }
    .footer {
        text-align: center;
        margin-top: 30px;
        color: #666;
    }
    """
    
    # 创建Gradio界面
    with gr.Blocks(css=css, title="ClearAI - 图像增强") as demo:
        
        # 标题和描述
        gr.HTML("""
        <div class="header">
            <h1>🏢 ClearAI - 图像增强应用</h1>
            <p>上传您的图像,选择增强类型,获得更清晰的图像效果</p>
        </div>
        """)
        
        # 主要界面布局
        with gr.Row():
            # 左侧:输入区域
            with gr.Column(scale=1):
                gr.HTML("<h3>📤 输入图像</h3>")
                input_image = gr.Image(
                    type="pil",
                    label="上传图像",
                    height=400
                )
                
                # 控制选项
                gr.HTML("<h3>⚙️ 处理选项</h3>")
                gr.HTML("<p>✨ 自动增强模式:智能优化图像清晰度、对比度和亮度</p>")
                
                apply_color_correction = gr.Checkbox(
                    label="应用颜色校正",
                    value=False,
                    info="自动调整图像色彩平衡和饱和度(处理时间会稍微增加)"
                )
                
                # 处理按钮
                process_btn = gr.Button(
                    "🚀 处理图像",
                    variant="primary",
                    size="lg"
                )
            
            # 右侧:输出区域
            with gr.Column(scale=1):
                gr.HTML("<h3>📥 增强结果</h3>")
                output_image = gr.Image(
                    type="pil",
                    label="增强后图像",
                    height=400
                )
        
        # 示例图像区域
        gr.HTML("<h3>💡 使用示例</h3>")
        gr.Examples(
            examples=[
                [False],
                [True],
            ],
            inputs=[apply_color_correction],
            label="预设配置"
        )
        
        # 使用说明
        with gr.Accordion("📖 使用说明", open=False):
            gr.Markdown("""
            ### 如何使用:
            1. **上传图像**:点击上传区域或拖拽图像文件
            2. **自动增强**:应用会自动优化图像的清晰度、对比度和亮度
            3. **可选颜色校正**:勾选后会进行色彩平衡和饱和度调整
               - 使用LAB色彩空间进行专业级颜色校正
               - 自动改善图像的色彩分布
               - 增强图像的色彩饱和度
            4. **点击处理**:点击"处理图像"按钮开始处理
            5. **查看结果**:在右侧查看增强后的图像
            6. **下载图像**:右键点击结果图像可以保存
            
            ### 支持格式:
            - PNG, JPG, JPEG, BMP, TIFF, WEBP
            
            ### 注意事项:
            - 建议图像大小不超过10MB
            - 颜色校正会稍微增加处理时间
            - 处理时间取决于图像大小和复杂度
            - 自动增强适用于大多数图像类型
            """)
        
        # 绑定处理函数
        process_btn.click(
            fn=process_image,
            inputs=[input_image, apply_color_correction],
            outputs=output_image,
            show_progress=True
        )
        
        # 页脚信息
        gr.HTML("""
        <div class="footer">
            <p>🚀 由 <strong>ClearAI</strong> 提供技术支持 | 基于 Gradio 构建</p>
            <p>💡 如有问题或建议,请在 Hugging Face Space 页面留言</p>
        </div>
        """)
    
    return demo

def main():
    """主函数"""
    logger.info("启动ClearAI图像增强应用")
    
    # 创建Gradio界面
    demo = create_gradio_interface()
    
    # 启动应用
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )

if __name__ == "__main__":
    main()