基于python的超分结果图的处理

本文详细介绍使用Python的PIL库进行图像裁剪的方法,包括指定坐标和尺寸裁剪特定区域,以及如何在图像上绘制矩形框进行视觉标注。此外,还介绍了如何批量处理图像集,适用于图像处理和计算机视觉任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做SR任务时,需要截取一些图的效果,写下本博文~

import matplotlib.pyplot as plt
from PIL import Image
import os 


fin='/home/guanwp/zhangwenlong/paperresult/ESRGAN/Set5_ESRGAN/'
fout=fin+'result'+'/'

def is_image_file(filename):
    '''
    Check wheather the file is a image file.
    :param filename: name of the file
    :return: bool value shows that whether it is a image
    '''
    return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg", ".bmp"])


for file in os.listdir(fin):
	if is_image_file(file):
		file_fullname=fin+'/'+file
		img=Image.open(file_fullname)

		a=[201,112,503,188]
		box=(a)
		ROI=img.crop(box)

		out_path=fout+'/'+file
		ROI.save(out_path)

 

import matplotlib.pyplot as plt
from PIL import Image,ImageDraw
import cv2
import os 


fin='/home/guanwp/zhangwenlong/paperresult/SRGANx4_RANK_3style_V1_esrgan_pre_46d7/val_set14/'
fout='result'+'/'

def is_image_file(filename):
    '''
    Check wheather the file is a image file.
    :param filename: name of the file
    :return: bool value shows that whether it is a image
    '''
    return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg", ".bmp"])


for file in os.listdir(fin):
	if is_image_file(file):
		if file=='baboon.png':

			file_fullname=fin+'/'+file
			img=Image.open(file_fullname)

			x=216
			y=266
			w=206
			a=[x,y,x+w,y+w]
			box=(a)
			ROI=img.crop(box)
			#upscale
			
			out_path=fout+file
			ROI.save(out_path)

			im=cv2.imread(file_fullname)
			cv2.rectangle(im,(x,y),(x+w,y+w),(0,255,0),3)
			cv2.imshow("image",im)
			cv2.waitKey (0)
			cv2.destroyAllWindows() 
			out_draw=fout+'abc/'+file
			cv2.imwrite(out_draw,im)

 

from PIL import Image, ImageDraw
import glob, os

dir = 'D:\Documents\截图/'  # 图片所在目录

# 选框左上角坐标(x, y),宽度width,高度自动计算得出
x = 0
y = 0
width = 100

# 获取图像
pyFile = glob.glob(os.path.join(dir, "*.png"))
pyFile += glob.glob(os.path.join(dir, "*.jpg"))
pyFile += glob.glob(os.path.join(dir, "*.bmp"))
result_path = os.path.join(dir,"result")

# 判断是否存在result子目录,若不存在则创建
if not os.path.exists(result_path) :
        os.mkdir(result_path)

# 遍历图片
for img_path in pyFile:
    im = Image.open(img_path)
    draw = ImageDraw.Draw(im)

    aspect_ratio = im.size[0]/im.size[1] # 长宽比
    # 截取选区图像
    im_ = im.crop((x, y, x+width, (x+width)//aspect_ratio))
    # 框出选区
    draw.rectangle((x, y, x+width, (x+width)//aspect_ratio), outline='red', width=3) # width是线条的宽度

    im_ = im_.resize(im.size) # 调用resize函数将子图放大到原图大小

    # 获取文件名
    _, img_name = os.path.split(img_path)
    img_name, _ = os.path.splitext(img_name)

    # 保存子图与含有选框的原图
    im_.save(os.path.join(result_path , img_name + '_sub_image.png'))
    im.save(os.path.join(result_path , img_name + '_ori_image.png'))

 

from PIL import Image, ImageDraw
import glob, os

dir = '*******************'  # the direction of the result

# the(x, y), and the width
x = 80
y = 100
width = 200
scale=4

# capture an image
pyFile = glob.glob(os.path.join(dir, "*.png"))
pyFile += glob.glob(os.path.join(dir, "*.jpg"))
pyFile += glob.glob(os.path.join(dir, "*.bmp"))
result_path = os.path.join(dir,"result")

# if the in result
if not os.path.exists(result_path) :
        os.mkdir(result_path)

# Traverse the picture
for img_path in pyFile:
    im = Image.open(img_path)
    draw = ImageDraw.Draw(im)

    aspect_ratio = im.size[0]/im.size[1] # Aspect ratio
    # Intercepting a selection image
    im_ = im.crop((x, y, x+width, (x+width)//aspect_ratio))
    # Box out of the selection
    draw.rectangle((x, y, x+width, (x+width)//aspect_ratio), outline='red', width=3) # width是线条的宽度

    #im_ = im_.resize(im.size) # Call the resize function to enlarge the submap to the original image size
    width1=int(im_.size[0]*scale)
    height1=int(im_.size[1]*scale)
    im_=im_.resize((width1, height1), Image.ANTIALIAS)

    # Get the file name
    _, img_name = os.path.split(img_path)
    img_name, _ = os.path.splitext(img_name)

    # Save submap and original image with marquee
    im_.save(os.path.join(result_path , img_name + '_sub_image.png'))
    im.save(os.path.join(result_path , img_name + '_ori_image.png'))

 

<think>好的,我需要帮助用户了解或实现基于Transformer的辨率像重建方法。首先,我应该回顾一下相关的知识,确保信息准确。 用户提到了TTSR和Swin2SR,这两个模型都是基于Transformer的。我需要先解释这些模型的基本原理和结构。例如,TTSR是CVPR2020的论文,它利用纹理转换网络,可能涉及到如何利用参考像来提升辨率的效果。而Swin2SR基于Swin Transformer,可能采用了层的窗口注意力机制,这样可以在不同尺度上捕捉像特征,提升重建细节。 接下来,我需要考虑实现的步骤。用户可能想知道具体的实现方法,包括数据准备、模型搭建、训练技巧等。可能需要提到使用PyTorch或TensorFlow框架,以及如何处理数据集,比如DIV2K或Flickr2K。同时,数据预处理如随机裁剪、翻转等增强技术也很重要。 然后,代码示例部需要给出一个简化的模型结构,比如一个基本的Transformer模块,或者参考Swin Transformer的结构。这里要注意代码的正确性,可能需要导入必要的库,定义模型层,并说明各部的用途。 此外,用户可能关心如何评估模型性能,比如使用PSNR、SSIM等指标,以及如何在实际中应用模型进行像重建。可能还需要提到一些优化技巧,比如学习率调整、损失函数的选择(如L1/L2损失,感知损失等)。 在相关问题部,需要生成几个相关的问题,帮助用户进一步探索。例如,比较不同Transformer结构的优劣,探讨如何提升模型效率,或者如何处理不同退化类型的像。 需要确保回答结构清晰,点说明,并且引用提供的参考文献。同时,语言要简洁明了,避免使用过于专业的术语,但又要准确。最后检查是否符合格式要求,比如数学表达式用$...$,独立公式用$$...$$,避免使用Markdown,保持自然的中文表达。</think>### 基于Transformer的辨率像重建技术 基于Transformer的辨率方法通过自注意力机制捕捉像长程依赖关系,提升细节恢复能力。以下是典型模型与技术实现要点: --- #### 一、核心模型解析 1. **TTSR(Texture Transformer Network)** - 使用可学习的纹理提取器从参考像中迁移高频细节,结合LR像与参考像的跨尺度注意力实现纹理增强[^1]。 - 关键公式:注意力权重计算 $$ \text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V $$ 其中$Q,K,V$别对应查询、键、值矩阵。 2. **Swin2SR** - 基于**Swin Transformer Block**构建,通过局部窗口注意力减少计算复杂度,支持多尺度特征融合[^2]。 - 采用移位窗口(Shifted Window)策略增强全局建模能力。 --- #### 二、实现步骤 1. **数据准备** - 数据集:DIV2K、Flickr2K等HR-LR配对数据集 - 预处理:随机裁剪(如$48\times48$块)、翻转、归一化至$[0,1]$。 2. **模型搭建(以Swin2SR简化版为例)** ```python import torch from swin_transformer import SwinTransformerBlock class Swin2SR(torch.nn.Module): def __init__(self): super().__init__() self.initial_conv = torch.nn.Conv2d(3, 64, 3, padding=1) self.swin_blocks = torch.nn.Sequential( SwinTransformerBlock(dim=64, num_heads=4, window_size=8), SwinTransformerBlock(dim=64, num_heads=4, window_size=8) ) self.reconstruction = torch.nn.Sequential( torch.nn.Conv2d(64, 256, 3, padding=1), torch.nn.PixelShuffle(2), # 2x上采样 torch.nn.Conv2d(64, 3, 3, padding=1) ) def forward(self, x): x = self.initial_conv(x) x = self.swin_blocks(x) return self.reconstruction(x) ``` 3. **训练配置** - 损失函数:L1损失 + 感知损失(VGG特征匹配) - 优化器:Adam ($\beta_1=0.9, \beta_2=0.999$) - 学习率:初始$1\times10^{-4}$,每50 epoch衰减0.5 --- #### 三、性能评估 - **指标**:PSNR(峰值信噪比)、SSIM(结构相似性) - **典型结果**:Swin2SR在Set5数据集上4x辨率可达32.1 dB PSNR[^2] ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值