我正在从PyTorch创建一个CUB_200数据集和数据中心。当以pill的形式读取图像时,我需要将BGR通道更改为RGB,并使用以下代码:
def _read_images_from_list(imagefile_list):
imgs = []
mean=[0.485, 0.456, 0.406]
std= [0.229, 0.224, 0.225]
Transformations = transforms.Compose([transforms.Resize([224, 224]), transforms.ToTensor(), transforms.Normalize(mean, std)])
for imagefile in imagefile_list:
# read images as PIL instead of NUMPY
img = Image.open(imagefile)
b, g, r = img.split()
img = Image.merge("RGB", (r, g, b))
img = Transformations(img) # ToTensor and between [0,1], then normalized using image net mean and std, then transposed into shape (C,H,W)
imgs += [img]
return imgs在经历了许多类之后,我得到了以下错误。
ValueError: not enough values to unpack (expected 3, got 1)我想知道我现在该怎么办?这意味着其中一个图像只有一个通道,而不是一个通道。这是真的吗?还是我的代码有问题?我以前有过不同的实现,但它起了作用。我之所以更改这个实现,是因为我无法规范我的图像。这是旧的实现:
def _read_images_from_list(imagefile_list):
imgs = []
for imagefile in imagefile_list:
img = cv2.imread(imagefile).astype(np.float32)
img = cv2.resize(img, (224, 224))
# Convert RGB to BGR
img_r, img_g, img_b = np.split(img, 3, axis=2)
img = np.concatenate((img_b, img_g, img_r), axis=2)
# Extract mean
img -= np.array((103.94,116.78,123.68), dtype=np.float32) # BGR mean
# HWC -> CHW, compatible with pytorch
img = np.transpose(img, [2, 0, 1])
imgs += [img]
return imgs发布于 2022-12-04 19:20:21
我强烈建议您使用skimage.io加载您的图像,而不是opencv。默认情况下,它以RGB格式打开图像,从而消除了您的洗牌开销,但是如果要将BGR转换为RGB,则可以使用以下方法:
import numpy as np
img = np.arange(27).reshape(3,3,3)
b = img[:,:,0]
g = img[:,:,1]
r = img[:,:,2]
rgb = np.dstack([r,g,b])
print(img)
print("#"*20)
print(rgb)https://stackoverflow.com/questions/74679922
复制相似问题