乐趣区

关于图像识别:读取图片

PIL

import numpy as np
from PIL import Image

image_pil = Image.open("./test.jpg").convert('RGB')
image_pil = np.asarray(image_pil)

OpenCV

import cv2

image_cv = cv2.imread("./test.jpg")
image_cv = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)

查看是否等价

print(type(image_cv))
print(type(image_pil))
print(image_cv.any() == image_pil.any())

<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
True

转换成 TorchTensor

from torchvision import transforms

transform = transforms.Compose([transforms.Resize([224, 224]),
            transforms.ToTensor()])

image_cv = Image.fromarray(image_cv)
img_tensor_cv = transform(image_cv)
img_tensor_cv = img_tensor_cv.reshape((1, 3, 224, 224))
image_pil = Image.fromarray(image_pil)
img_tensor_pil = transform(image_pil)
img_tensor_pil = img_tensor_pil.reshape((1, 3, 224, 224))
print(torch.equal(img_tensor_cv, img_tensor_pil))

False
退出移动版