【问题标题】:torch transform.resize() vs cv2.resize()火炬 transform.resize() 与 cv2.resize()
【发布时间】:2020-08-21 18:15:06
【问题描述】:

CNN 模型将大小为(112x112) 的图像张量作为输入,并给出(1x512) 大小的张量作为输出。

使用 Opencv 函数 cv2.resize() 或在 pytorch 中使用 Transform.resize 将输入调整为 (112x112) 会得到不同的输出。

这是什么原因? (我知道opencv调整大小与torch调整大小的底层实现的差异可能是造成这种情况的原因,但我想详细了解一下)

import cv2
import numpy as np 
from PIL import image
import torch
import torchvision
from torchvision import transforms as trans


# device for pytorch
device = torch.device('cuda:0')

torch.set_default_tensor_type('torch.cuda.FloatTensor')

model = torch.jit.load("traced_facelearner_model_new.pt")
model.eval()

# read the example image used for tracing
image=cv2.imread("videos/example.jpg")

test_transform = trans.Compose([
            trans.ToTensor(),
            trans.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
        ])   
test_transform2 = trans.Compose([
            trans.Resize([int(112), int(112)]),
            trans.ToTensor(),
            trans.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
        ])      

resized_image = cv2.resize(image, (112, 112))

tensor1 = test_transform(resized_image).to(device).unsqueeze(0)
tensor2 = test_transform2(Image.fromarray(image)).to(device).unsqueeze(0)
output1 = model(tensor1)
output2 = model(tensor2)

output1 和 output2 张量具有不同的值。

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    基本上torchvision.transforms.Resize()默认使用PIL.Image.BILINEAR插值。

    在您的代码中,您只需使用不使用任何插值的cv2.resize

    例如

    import cv2
    from PIL import Image
    import numpy as np
    
    a = cv2.imread('videos/example.jpg')
    b = cv2.resize(a, (112, 112))
    c = np.array(Image.fromarray(a).resize((112, 112), Image.BILINEAR))
    

    您会看到bc 略有不同。

    编辑:

    实际上 opencv 文档说

    INTER_LINEAR - 双线性插值(默认使用)

    但是,它给出的结果与PIL 不同。

    编辑 2:

    这也在文档中

    要缩小图像,通常使用 INTER_AREA 插值效果最好

    显然

    d = cv2.resize(a, (112, 112), interpolation=cv2.INTER_AREA)
    

    给出与c 几乎相同的结果。但不幸的是,这些并没有回答这个问题。

    【讨论】:

    • OpenCV 默认不使用插值
    • 它在 Python 中使用 None,但默认情况下 cv::resize 使用 INTER_LINEAR
    • @Natthaphon Hongcharoen。 PIL 在调整大小之前应用了一些 抗锯齿 过滤器。但不是 cv2 这也会导致一些差异
    • @NatthaphonHongcharoen 我们在这里讨论的是 Python 而不是 C++
    猜你喜欢
    • 2020-03-10
    • 2018-09-02
    • 2017-02-23
    • 2021-02-08
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多