Python实现图片画质分辨率提升而保留文字和Logo细节
在提高图片分辨率的同时保留文字和Logo等细节是一个常见的图像处理需求。传统的图像放大方法可能会导致文字和Logo变得模糊,而现代的超分辨率技术可以更好地保留这些细节。以下是几种实现方法:
1. 使用超分辨率库
使用OpenCV的超分辨率模块
import cv2
import numpy as np
# 读取图片
img = cv2.imread('input.jpg')
# 创建超分辨率模型
sr = cv2.dnn_superres.DnnSuperResImpl_create()
# 加载EDSR模型 (可选择不同模型如ESPCN, FSRCNN, LapSRN)
path = "EDSR_x4.pb" # 预训练模型路径
sr.readModel(path)
sr.setModel("edsr", 4) # 放大4倍
# 进行超分辨率处理
result = sr.upsample(img)
# 保存结果
cv2.imwrite('output.jpg', result) 使用深度学习库如TensorFlow或PyTorch
# 使用PyTorch实现的示例
import torch
from PIL import Image
import torchvision.transforms as transforms
from torchvision.models import vgg19
import numpy as np
# 加载预训练的超分辨率模型
# 这里需要自定义或使用预训练的超分辨率模型
model = torch.hub.load('xinntao/ESRGAN-PyTorch', 'RRDBNet_arch')
model.eval()
if torch.cuda.is_available():
model = model.cuda()
# 读取图像
img = Image.open('input.jpg')
img_tensor = transforms.ToTensor()(img).unsqueeze(0)
if torch.cuda.is_available():
img_tensor = img_tensor.cuda()
# 进行超分辨率处理
with torch.no_grad():
output = model(img_tensor)
# 转换回PIL图像并保存
output_img = transforms.ToPILImage()(output.squeeze().cpu())
output_img.save('output.jpg') 2. 使用专门针对文字和Logo的超分辨率方法
对于包含文字和Logo的图像,可以考虑先进行图像分割,分别处理文字区域和非文字区域:
import cv2
import numpy as np
from PIL import Image
# 读取图像
img = cv2.imread('input.jpg')
# 转换为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用自适应阈值处理找出文字区域
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2)
# 寻找轮廓
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 创建文字掩码
text_mask = np.zeros_like(gray)
for cnt in contours:
# 过滤掉太小的轮廓
if cv2.contourArea(cnt) > 50:
cv2.drawContours(text_mask, [cnt], -1, 255, -1)
# 创建文字区域和非文字区域的掩码
text_mask = cv2.dilate(text_mask, np.ones((3,3), np.uint8), iterations=2)
non_text_mask = cv2.bitwise_not(text_mask)
# 分离文字区域和非文字区域
text_region = cv2.bitwise_and(img, img, mask=text_mask)
non_text_region = cv2.bitwise_and(img, img, mask=non_text_mask)
# 对非文字区域使用普通的放大方法
non_text_upscaled = cv2.resize(non_text_region, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
# 对文字区域使用更锐利的放大方法
text_upscaled = cv2.resize(text_region, None, fx=2, fy=2, interpolation=cv2.INTER_NEAREST)
# 合并两个区域
result = cv2.add(text_upscaled, non_text_upscaled)
# 保存结果
cv2.imwrite('output.jpg', result) 3. 使用专业的超分辨率工具库
使用Real-ESRGAN
Real-ESRGAN是一个专门针对真实世界图像的超分辨率工具,对文字和Logo的保留效果较好:
# 需要先安装: pip install realesrgan
from realesrgan import RealESRGANer
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
import cv2
import numpy as np
import torch
# 读取图像
img = cv2.imread('input.jpg')
# 初始化模型
model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
upsampler = RealESRGANer(
scale=4,
model_path='realesr-general-x4v3.pth', # 需要下载预训练模型
model=model,
tile=0,
tile_pad=10,
pre_pad=0,
half=True
)
# 进行超分辨率处理
output, _ = upsampler.enhance(img, outscale=4)
# 保存结果
cv2.imwrite('output.jpg', output) 4. 结合OCR技术的方法
对于文字非常重要的图像,可以考虑使用OCR先识别文字,然后在高分辨率图像上重新渲染文字:
import cv2
import pytesseract
from PIL import Image, ImageDraw, ImageFont
import numpy as np
# 读取图像
img = Image.open('input.jpg')
img_np = np.array(img)
# 使用OCR识别文字及其位置
ocr_results = pytesseract.image_to_data(img_np, output_type=pytesseract.Output.DICT)
# 放大图像
scale_factor = 2
img_upscaled = img.resize((img.width * scale_factor, img.height * scale_factor),
Image.LANCZOS)
draw = ImageDraw.Draw(img_upscaled)
# 在放大后的图像上重新绘制文字
for i in range(len(ocr_results['text'])):
if int(ocr_results['conf'][i]) > 60: # 只处理置信度高的文字
x = ocr_results['left'][i] * scale_factor
y = ocr_results['top'][i] * scale_factor
w = ocr_results['width'][i] * scale_factor
h = ocr_results['height'][i] * scale_factor
text = ocr_results['text'][i]
# 尝试匹配字体大小
font_size = h
font = ImageFont.truetype("arial.ttf", font_size)
# 绘制文字
draw.text((x, y), text, fill="black", font=font)
# 保存结果
img_upscaled.save('output.jpg') 总结与建议
对于一般用途:使用Real-ESRGAN或ESRGAN等现代超分辨率模型,它们通常能很好地保留文字和Logo细节。对于文字为主的图像:考虑使用分割方法,对文字区域和非文字区域分别处理。对于高质量要求:结合OCR技术,先识别文字,然后在高分辨率图像上重新渲染。对于Logo:如果Logo是矢量图,最好的方法是找到原始矢量文件;如果不可能,使用专门的超分辨率模型如Real-ESRGAN通常能获得较好的效果。硬件要求:深度学习方法通常需要较好的GPU支持,如果硬件条件有限,可以考虑使用基于OpenCV的方法或在线服务。
网友回复


