python - Pytorch 在变换中从左上角裁剪图像
问题描述
我正在使用 Pytorch transforms.Compose
,在我的数据集中我有 1200x1600(高度 x 宽度)图像。
我想从左上角 (0,0) 开始裁剪图像,这样我就可以拥有 800x800 的图像。
我正在查看 Pytorch 文档,但没有找到任何解决问题的方法,所以我复制了center_crop
项目中的源代码并修改如下:
def center_crop(img: Tensor, output_size: List[int]):
# .... Other stuff of Pytorch
# ....
# Original Pytorch Code (that I commented)
crop_top = int((image_height - crop_height + 1) * 0.5)
crop_left = int((image_width - crop_width + 1) * 0.5)
# ----
# My modifications:
crop_top = crop_left = 0
return crop(img, crop_top, crop_left, crop_height, crop_width)
但基本上我认为这有点矫枉过正,如果可能的话,我想避免复制他们的代码并对其进行修改。默认情况下,没有任何东西已经实现了所需的行为,是吗?
解决方案
我使用Lambda
变换来定义自定义裁剪
from torchvision.transforms.functional import crop
def crop800(image):
return crop(image, 0, 0, 800, 800)
data_transforms = {
'images': transforms.Compose([transforms.ToTensor(),
transforms.Lambda(crop800),
transforms.Resize((400, 400))])}
推荐阅读
- python - 用熊猫附加到数据框单元格?
- android - 获取 Gson MalformedJsonException:未终止的数组
- ios - 由于发送到无法识别的选择器而崩溃(仅在首次启动后)
- php - Laravel 不自动加载类
- javascript - 如何在Javascript中将字符串转换为整数和运算符?
- python - Python:将矩阵重塑为特定形式的向量
- c - select() 或 epoll() 在链接原始接口上运行时不返回
- reactjs - jss 覆盖 material-ui 非确定性类
- python - 使用 matplotlib 在 Linux Ubuntu 的 Windows 子系统上创建直方图
- c - 使用阶乘函数和余弦函数通过 Maclaurin 级数逼近计算 cos(x)