深度学习图像处理——数据加载

1 数据迭代器

1.1 enumerate()

for n, (x, _) in enumerate(train_loader):
	x = x.to(device)

这个函数可以在遍历train_loader数组的同时,返回下标。举例:

data = [(1, 3), (2, 1), (3, 3)]
1. 直接遍历数组,返回数组里的值。
for x, y in data:
    print(x,y)
# 1 3
# 2 1
# 3 3

2. 使用迭代器,同时返回下标。(这里data是一个多元数组,所以在迭代的时候,我们需要注意要将index和value区分开。)
for i, (x, y) in enumerate(data):
    print(i, x, y)

# 0 1 3
# 1 2 1
# 2 3 3

1.2 zip()

    for (x, _), (y, _) in zip(train1_loader, train2_loader):
        x, y = x.to(device), y.to(device)

多对象迭代,同时遍历两个数组。举例:

names = ['xiaoming', 'xiaohua', 'xiaohei', 'xiaoli']
jobs = ['coach', 'student', 'student', 'student', 'professor']

for name, job in zip(names, jobs):
  print(name, job)

# xiaoming coach
# xiaohua student
# xiaohei student
# xiaoli student

注意,上面例子中的names和jobs的长度其实是不一致的,在使用了zip的情况下,会自动替我们按照其中较短的那个进行截断。如果我们不希望截断,我们也可以使用itertools下的zip_longest来代替zip:

2 数据读取

2.1 路径-opencv-Tensor

img_path = './Images/1.jpg'
img = cv2.imread(img_path)

print(img.shape)  # (H,W,3)
print(img.size)  # (H,W,3)
tran = transforms.ToTensor()  # 将numpy数组或PIL.Image读的图片转换成(C,H, W)的Tensor格式且/255归一化到[0,1.0]之间
img_tensor = tran(img)
print(img_tensor.size())  # (C,H, W), 通道顺序(B,G,R)


'''
(256, 256, 3)
196608
torch.Size([3, 256, 256])
'''

2.2 Tensor加一维batch_size


image = torch.unsqueeze(img_tensor, 0)
print(image.size())		# torch.Size([1, 3, 256, 256])

猜你喜欢

转载自blog.csdn.net/everyxing1007/article/details/126867931