模块六:image、transform模块

image模块主要用于加载和保存图片,返回一个Surface对象。而transform模块主要用于处理图像,主要包括反转、旋转、缩放、过滤图像等等。在pygame中,图片不是用Image对象来表示,而是用Surface对象来表示。image模块的方法比较简单,下面用一个例子介绍一下各个方法。

# 加载图片
# 支持基本格式 BMP
# 也支持扩展格式
# GIF(非动画)、JPEG、LBM(和PBM, PGM, PPM)、PCX、PNG、PNM、
# SVG (有限支持,使用 Nano SVG)、TGA (未压缩)、TIFF、WEBP、XPM
image_surface1 = pygame.image.load("test.png")
# 只支持基本格式
image_surface2 = pygame.image.load_basic("test.bmp")
# 只支持扩展格式
image_surface3 = pygame.image.load_extended("test.png")
# 将图像Surface转换成字符串string
image_string = pygame.image.tostring(image_surface1, "RGBA")
# 将字符串string转换成图像Surface
image_surface4 = pygame.image.fromstring(image_string, 65535)
byte_string = ""
image_surface5 = pygame.image.frombuffer(byte_string, 65535)
# 保存图片
# 基本格式和扩展格式均可
pygame.image.save(image_surface5, "test2.png")
# 只支持扩展格式
pygame.image.save_extended(image_surface5, "test3.png")
# 获取正在使用的 SDL_Image 库的版本号
pygame.image.get_sdl_image_version()
# 测试是否可以加载扩展图像格式
pygame.image.get_extended()

最常用的方法就是下面两个:

pygame.image.load(filename)

filename:文件名

pygame.image.save(surface, filename)

surface:图像对象
filename:文件名

对于一个Surface对象,有如下方法:

dest = (0, 0, 200, 200)
area = (0, 0, 100, 100)
# 将一个图像surface绘制到另外一个surface中
# 参数source表示要绘制的图像surface
# 参数dest表示要绘制到surface中哪一个rect中
# 参数area表示绘制图像surface中的哪一个rect
surface.blit(image_surface, dest, area)
# 将多个图像surface绘制到另外一个surface中
# 参数blit_sequence表示一个序列[(source1, dest1, area1),...]
# 参数doreturn如果为True则表示返回一个矩形rect序列,False则表示不返回任何
blit_sequence = [(image_surface, dest, area)]
doreturn = False
surface.blits(blit_sequence, doreturn)
# 根据另外一个surface的格式来转换当前的surface,并产生一个新的surface
surface1 = surface.convert(surface)
# 更改当前surface的像素格式,包括alpha通道
surface2 = surface.convert_alpha(surface)
# 复制surface
surface3 = surface.copy()
# 用纯色来填充surface,并返回一个rect
# 参数color表示填充的颜色
# 参数rect表示填充在surface中的某个rect中
color = (255, 0, 0)
rect = (20, 20, 40, 40)
rect1 = surface.fill(color, rect)
# 移动surface到另外一个位置
# 参数dx、dy表示在x和y方向的偏移量
dx, dy = 20, 20
surface.scroll(dx, dy)
# 设置surface的colorkey
surface.set_colorkey(color)
# 获取surface的colorkey
surface.get_colorkey()
# 设置图像surface的alpha值,0-255之间,0表示完全透明,255表示不透明
value = 255
surface.set_alpha(255)
# 获取图像的alpha值
surface.get_alpha()
# 锁定图像surface
surface.lock()
# 解锁图像surface
surface.unlock()
# 测试surface是否需要锁定
surface.mustlock()
# 测试surface是否锁定
surface.get_locked()
# 获取surface的锁
surface.get_locks()
# 获取和设置surface在点(x, y)上的像素值
x, y = 20, 20
surface.get_at((x, y))
surface.set_at((x, y), color)
# 获取surface在(x, y)上映射的像素颜色值
surface.get_at_mapped((x, y))
# 获取调色板
surface.get_palette()
# 获取调色板单个条目的颜色
index = 0
surface.get_palette_at(index)
# 设置调色板
surface.set_palette()
# 设置调色板某个条目的颜色
surface.set_palette_at(index, color)
# 将颜色转换成映射的颜色值
mapped_int = surface.map_rgb(color)
# 将映射的颜色值转换成颜色
surface.unmap_rgb(mapped_int)
# 设置surface的剪切区域
surface.set_clip(rect)
# 获取surface的剪切区域
surface.get_clip()
# 根据原来的surface以及rect区域生成一个新的surface
surface.subsurface(rect)
# 获取当前surface的父类surface
surface.get_parent()
# 获取当前surface的最顶层父类surface
surface.get_abs_parent()
# 获取surface的子类surface
surface.get_offset()
# 获取surface的最底层子类surface
surface.get_abs_offset()
# 获取surface的大小、宽度、高度、矩形
surface.get_size()
surface.get_width()
surface.get_height()
surface.get_rect()
# 获取surface像素格式的位深度
surface.get_bitsize()
# 获取surface每个像素使用的字节数
surface.get_bytesize()
# 获取surface的标志
surface.get_flags()
# 返回包含曲面中alpha值大于或等于最小alpha值的所有像素的最小矩形区域
min_alpha = 0
surface.get_bounding_rect(min_alpha)
# 返回Surface像素的缓冲区视图
# kind 参数是长度为 1 的字符串 '0'、'1'、'2'、'3'、'r'、'g'、'b' 或 'a'。
# 字母不区分大小写;'A' 也可以。参数可以是 Unicode 或字节 (char) 字符串。默认值为“2”。
# “0”返回一个连续的非结构化字节视图。没有给出表面形状信息。ValueError如果表面的像素不连续,则A会升高。
# '1' 返回一个 (surface-width * surface-height) 连续像素数组。
# ValueError如果表面像素不连续,则提高A。
# '2' 返回原始像素的(表面宽度,表面高度)数组。像素是表面字节大小 d 无符号整数。
# 像素格式是特定于表面的。24 位表面的 3 字节无符号整数不太可能被其他 pygame 函数以外的任何东西接受。
# '3' 返回一个 (surface-width, surface-height, 3)RGB颜色分量数组。
# 红色、绿色和蓝色分量中的每一个都是无符号字节。仅支持 24 位和 32 位表面。
# 颜色分量必须在像素内按顺序排列RGB。BGR
# 'r' 代表红色,'g' 代表绿色,'b' 代表蓝色,'a' 代表 alpha
# 返回表面内单个颜色分量的(表面宽度,表面高度)视图:颜色平面。
# 颜色分量是无符号字节。24 位和 32 位表面都支持“r”、“g”和“b”。
# SRCALPHA仅支持“a”的32 位表面 。
kind = 1
surface.get_view(kind)
# 获取Surface像素的缓冲区对象
surface.get_buffer()

transform模块的函数如下:

image_surface = pygame.image.load("test.png")
image_rect = image_surface.get_rect()
# 翻转图片
flip_x, flip_y = True, False
image_surface1 = pygame.transform.flip(image_surface, flip_x, flip_y)
# 缩放图片
size = (320, 240)
image_surface2 = pygame.transform.scale(image_surface, size)
# 旋转图片
angle = 15.0
image_surface3 = pygame.transform.rotate(image_surface, angle)
# 旋转缩放图片,参数scale的作用是当前分辨率与之相乘
angle = 15.0
scale = 2.0
image_surface4 = pygame.transform.rotozoom(image_surface, angle, scale)
# 图像的大小变成原来的两倍
image_surface5 = pygame.transform.scale2x(image_surface)
# 平滑缩放图片
size = (640, 480)
image_surface6 = pygame.transform.smoothscale(image_surface, size)
# 返回smoothscale方法使用的过滤器版本
backend = pygame.transform.get_smoothscale_backend()
# 设置smoothscale方法使用的过滤器版本,有三个可选值'GENERIC', 'MMX', or 'SSE'
backend = 'SSE'
pygame.transform.set_smoothscale_backend(backend)
# 裁剪图片
rect = pygame.Rect(100, 100, 100, 100)
image_surface7 = pygame.transform.chop(image_surface, rect)
# 获取图片的轮廓
image_surface8 = pygame.transform.laplacian(image_surface)
# 从多个图片中获取平均的图片
image_surface9 = pygame.transform.average_surfaces(image_surfaces)
# 获取图片的平均颜色
image_surface10 = pygame.transform.average_color(image_surface, rect)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是Swin-Transform模块的详细代码示例: ```python import torch import torch.nn as nn import torch.nn.functional as F class SwinTransformer(nn.Module): def __init__(self, image_size=224, patch_size=4, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], num_classes=1000): super(SwinTransformer, self).__init__() assert image_size % patch_size == 0, "image size must be divisible by patch size" num_patches = (image_size // patch_size) ** 2 patch_dim = 3 * patch_size ** 2 # Patch Embedding self.patch_embed = nn.Conv2d(3, embed_dim, kernel_size=patch_size, stride=patch_size) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) # Transformer Encoder self.transformer_encoder = TransformerEncoder(embed_dim, depths, num_heads) # Classification Head self.head = nn.Linear(embed_dim, num_classes) def forward(self, x): x = self.patch_embed(x) # [batch_size, embed_dim, H', W'] x = x.flatten(2).transpose(1, 2) # [batch_size, num_patches, embed_dim] batch_size, num_patches, _ = x.shape cls_tokens = self.cls_token.expand(batch_size, -1, -1) # [batch_size, 1, embed_dim] x = torch.cat((cls_tokens, x), dim=1) # [batch_size, num_patches+1, embed_dim] x = x + self.pos_embed # [batch_size, num_patches+1, embed_dim] x = self.transformer_encoder(x) x = x.mean(dim=1) # [batch_size, embed_dim] x = self.head(x) # [batch_size, num_classes] return x class TransformerEncoder(nn.Module): def __init__(self, embed_dim, depths, num_heads): super(TransformerEncoder, self).__init__() self.layers = nn.ModuleList() for i in range(len(depths)): self.layers.append(TransformerEncoderLayer(embed_dim, depths[i], num_heads[i])) def forward(self, x): for layer in self.layers: x = layer(x) return x class TransformerEncoderLayer(nn.Module): def __init__(self, embed_dim, depth, num_heads): super(TransformerEncoderLayer, self).__init__() self.attention_norm = nn.LayerNorm(embed_dim) self.ffn_norm = nn.LayerNorm(embed_dim) self.attention = Attention(embed_dim, num_heads) self.ffn = FeedForwardNetwork(embed_dim) self.depth = depth def forward(self, x): residual = x for _ in range(self.depth): x = x + self.attention_norm(self.attention(x)) x = x + self.ffn_norm(self.ffn(x)) return x class Attention(nn.Module): def __init__(self, embed_dim, num_heads): super(Attention, self).__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.head_dim = embed_dim // num_heads self.qkv = nn.Linear(embed_dim, embed_dim * 3) self.proj = nn.Linear(embed_dim, embed_dim) def forward(self, x): qkv = self.qkv(x) q, k, v = torch.split(qkv, self.embed_dim, dim=-1) q = q.reshape(*q.shape[:-1], self.num_heads, self.head_dim).transpose(-2, -3) k = k.reshape(*k.shape[:-1], self.num_heads, self.head_dim).permute(0, 2, 3, 1) v = v.reshape(*v.shape[:-1], self.num_heads, self.head_dim).transpose(-2, -3) attn_scores = torch.matmul(q, k) / (self.head_dim ** 0.5) attn_scores = F.softmax(attn_scores, dim=-1) attn_output = torch.matmul(attn_scores, v) attn_output = attn_output.transpose(-2, -3).reshape(*attn_output.shape[:-3], self.embed_dim) x = self.proj(attn_output) return x class FeedForwardNetwork(nn.Module): def __init__(self, embed_dim): super(FeedForwardNetwork, self).__init__() self.ffn = nn.Sequential( nn.Linear(embed_dim, 4 * embed_dim), nn.GELU(), nn.Linear(4 * embed_dim, embed_dim) ) def forward(self, x): return self.ffn(x) ``` 这就是Swin-Transform模块的详细代码。你可以将这段代码集成到你的FFANet模型中,并根据需要进行调整。记得根据实际情况修改输入输出尺寸、深度、头数等模块的参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不负韶华ღ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值