ClearAI / app.py
nihuajian
Update app.py
ea373d1 verified
#!/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()