该模型以大小为(112x112)的图像张量作为输入,以(1x512)尺寸张量作为输出。
使用Opencv函数cv2.resize()或使用Transform.resize在移相器中调整输入到(112x112)的大小会产生不同的输出。
原因是什么?(我知道opencv调整大小与火炬调整的根本实现上的差异可能是造成这种情况的原因之一,但我想对此有一个详细的了解)
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张量具有不同的值。
发布于 2020-08-21 09:43:33
基本上,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))您将看到b和c略有不同。
编辑:
实际上opencv文档上写着
INTER_LINEAR -双线性插值(默认情况下使用)
但是是的,它的结果和PIL不一样。
编辑2:
这也在文档里
为了缩小图像,通常使用INTER_AREA内插看起来最好。
而且很明显
d = cv2.resize(a, (112, 112), interpolation=cv2.INTER_AREA)给出的结果与c几乎相同。但不幸的是,这些并没有回答这个问题。
https://stackoverflow.com/questions/63519965
复制相似问题