完整例子:
import torch
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
from PIL import Image
# Step 1: 读取一张图片
image_path = r"C:\Users\Administrator\Pictures\pinije\3.jpg" # 替换为你的图片路径
img = Image.open(image_path)
# Step 2: 转为Tensor
transform_to_tensor = transforms.ToTensor()
img_tensor = transform_to_tensor(img)
batch_size = 4
batch_img_tensor = img_tensor.unsqueeze(0).repeat(batch_size, 1, 1, 1)
# Step 4: 翻转
flipped_batch_tensor = torch.flip(batch_img_tensor, [-1])
# Step 5: 转回图片并保存(仅保存第一个批量数据)
transform_to_pil = transforms.ToPILImage()
flipped_img = transform_to_pil(flipped_batch_tensor[0])
# 保存图片
flipped_img.save("flipped_image.jpg")
import torch
import torchvision.transforms as transforms
# 假设你的图像张量是 img_tensor
# img_tensor 的尺寸是 (1, 3, 256, 448)
# 使用 transforms.RandomHorizontalFlip()
transform = transforms.RandomHorizontalFlip(p=1) # p=1 表示总是翻转
flipped_tensor = transform(img_tensor)
print(flipped_tensor.shape)
import torch
import torchvision.transforms.functional as F
# 假设你的图像张量是 img_tensor
# img_tensor 的尺寸是 (1, 3, 256, 448)
# 使用 F.hflip
flipped_tensor = F.hflip(img_tensor)
print(flipped_tensor.shape)
import torch
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
# 创建一个示例图像张量,尺寸为 (1, 3, 256, 448)
img_tensor = torch.randn(1, 3, 256, 448)
# 方法1:使用 transforms.RandomHorizontalFlip
transform = transforms.RandomHorizontalFlip(p=1) # p=1 表示总是翻转
flipped_tensor1 = transform(img_tensor)
print(f"使用 transforms.RandomHorizontalFlip 翻转后的张量尺寸: {flipped_tensor1.shape}")
# 方法2:使用 F.hflip
flipped_tensor2 = F.hflip(img_tensor)
print(f"使用 F.hflip 翻转后的张量尺寸: {flipped_tensor2.shape}")