import torch
import torchvision
def mean_std(image_data):
'''
计算数据集图像的mean和std
image_data: 自定义类Dataset(或ImageFolder即可)
'''
print('Number of images are', len(image_data))
data_loader = torch.utils.data.DataLoader(
image_data, batch_size=1, shuffle=False, num_workers=0, pin_memory=True)
mean = torch.zeros(3)
std = torch.zeros(3)
for X, _ in data_loader:
for i in range(3):
mean[i] += X[:, i, :, :].mean()
std[i] += X[:, i, :, :].std()
mean.div_(len(image_data))
std.div_(len(image_data))
return list(mean.numpy()), list(std.numpy())
if __name__ == '__main__':
image_dataset = torchvision.datasets.ImageFolder(root=r'数据集地址', transform=torchvision.transforms.ToTensor())
print(mean_std(image_dataset))
其他:
1、for d in range(3),RGB图像3通道;若是灰度图,则只需要一次
2、数据集地址里需要建立子文件夹
3、transform=torchvision.transforms.ToTensor(),数据转为tensor格式
参考文章
https://blog.csdn.net/Carpe_Diemly/article/details/115031131
https://blog.csdn.net/weixin_44579633/article/details/123128976
https://blog.csdn.net/PanYHHH/article/details/107896526
https://www.bilibili.com/read/cv14137505/