详细解释: import os from flask import Flask, rendertemplate, request import cv2 import torch…
- User
详细解释: import os from flask import Flask, render_template, request import cv2 import torch from basicsr.archs.srvgg_arch import SRVGGNetCompact from gfpgan.utils import GFPGANer from realesrgan.utils import RealESRGANer
app = Flask(name)
Set the upload folder and allowed extensions
app.config['UPLOAD_FOLDER'] = 'static/uploads' app.config['ALLOWED_EXTENSIONS'] = {'jpg', 'jpeg', 'png'}
Create the uploads and ouputs folder if it does not exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) os.makedirs('static/outputs', exist_ok=True)
Download weights if not available
model_weights = { 'realesr-general-x4v3.pth': 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth', 'GFPGANv1.2.pth': 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.2.pth', 'GFPGANv1.3.pth': 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth', 'GFPGANv1.4.pth': 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth', 'RestoreFormer.pth': 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth', 'CodeFormer.pth': 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/CodeFormer.pth' }
for weight_file, weight_url in model_weights.items(): if not os.path.exists(weight_file): os.system(f"wget {weight_url} -P .")
Create the background enhancer with RealESRGAN
model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu') model_path = 'realesr-general-x4v3.pth' half = True if torch.cuda.is_available() else False upsampler = RealESRGANer(scale=4, model_path=model_path, model=model, tile=0, tile_pad=10, pre_pad=0, half=half)
def allowed_file(filename): """Check if the file extension is allowed.""" return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
- Assistant
这段代码创建了一个基于Flask框架的Web应用程序,主要用于图像增强。它利用opencv、torch、GFPGAN、RealESRGAN等开源库和深度学习模型自动进行图片的超分辨率放大和面部修复。以下是各部分的详细解释:
-
初始化Flask应用和设置:
- 创建Flask应用实例。设置上传文件夹
'static/uploads'和允许的文件扩展名(jpg, jpeg, png)。 - 检查上传目录是否存在,如果不存在则创建它以及输出文件夹
'static/outputs'。
- 创建Flask应用实例。设置上传文件夹
-
下载权重文件:
- 定义模型权重文件和对应的下载链接,如果这些文件不存在于当前目录下,则会下载它们。这里使用了
os.system调用wget命令进行下载,涉及到的模型主要是RealESRGAN和GFPGAN(包括不同版本)以及RestoreFormer和CodeFormer两种面部修复模型。
- 定义模型权重文件和对应的下载链接,如果这些文件不存在于当前目录下,则会下载它们。这里使用了
-
图片增强部分:
- 初始化RealESRGAN模型,准备用于背景图片的超分辨。
- 定义
enhance_image函数,该函数接受图片路径、GFPGAN版本和缩放比例作为输入,根据提供的参数选择GFPGAN版本进行人脸增强处理,并可选地对图片尺寸进行调整。函数处理流程包括读取图片、选择模型、图片增强、缩放和保存结果等。
-
文件上传和处理路由:
- 定义
allowed_file函数,帮助确认上传的文件类型是否被允许。 /路由支持GET和POST请求:GET请求直接返回首页,POST请求处理上传的文件。在接收到POST请求后,首先检查是否包含文件,然后验证文件类型,保存文件,并调用enhance_image函数处理图片,最后以渲染的模板返回处理结果。
- 定义
-
:
-