首页 > 解决方案 > 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)

但基本上我认为这有点矫枉过正,如果可能的话,我想避免复制他们的代码并对其进行修改。默认情况下,没有任何东西已经实现了所需的行为,是吗?

标签: pythonpytorchconv-neural-network

解决方案


我使用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))])}

推荐阅读