Pytorch torchvision.transforms的crop方法裁剪尺寸超原图未自动补零
问题原因
你遇到的问题是接口功能理解偏差导致的:torchvision.transforms.functional.crop(即你调用的TF.crop)本身仅支持截取输入图像的实际存在区域,当指定的裁剪宽高超出原图边界时,接口会自动将裁剪边界截断到原图边缘,不会主动执行填充操作。
你看到的「裁剪尺寸大于原图时自动补零」的描述,实际是torchvision.transforms.RandomCrop类的特性:该类在pad_if_needed参数开启的前提下,若指定的裁剪尺寸大于输入图像尺寸,会先对原图做零填充,再执行裁剪操作。
解决方案
方案1:固定裁剪位置(从左上角裁剪)
如果你需要严格从左上角开始裁剪、超出部分补零,手动先做填充再裁剪即可,参考代码:
import torch import torchvision.transforms.functional as TF x = torch.rand(1,3,256,256) target_h, target_w = 300, 300 # 计算需要填充的右、下侧像素数(从左上角裁剪只需补右边和下边) pad_right = max(0, target_w - x.shape[3]) pad_bottom = max(0, target_h - x.shape[2]) # 填充参数顺序为左、上、右、下,填充值设为0 x_padded = TF.pad(x, padding=[0, 0, pad_right, pad_bottom], fill=0) y = TF.crop(img=x_padded, top=0, left=0, height=target_h, width=target_w) print(y.shape) # 输出 torch.Size([1, 3, 300, 300])
方案2:无需固定裁剪位置
如果你没有固定裁剪位置的要求,直接使用RandomCrop接口即可自动处理填充逻辑,参考代码:
import torch from torchvision.transforms import RandomCrop x = torch.rand(1,3,256,256) transform = RandomCrop(size=(300,300), pad_if_needed=True, fill=0) y = transform(x) print(y.shape) # 输出 torch.Size([1, 3, 300, 300])
内容的提问来源于stack exchange,提问作者TPaul
相关产品推荐
相关产品推荐

