-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaverage_meter.py
74 lines (60 loc) · 1.91 KB
/
average_meter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File :L5 -> Contrastive_train
@IDE :PyCharm
@Author :DIPTE
@Date :2020/8/3 0:25
@Desc :
=================================================='''
import numpy as np
import torch
import torchvision.transforms as transforms
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
"""
reset all parameters
"""
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
"""
update parameters
"""
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
def convert_image_to_tensor(image):
"""convert an image to pytorch tensor
Parameters:
----------
image: numpy array , h * w * c
Returns:
-------
image_tensor: pytorch.FloatTensor, c * h * w
"""
return transform(image)
def convert_chwTensor_to_hwcNumpy(tensor):
"""convert a group images pytorch tensor(count * c * h * w) to numpy array images(count * h * w * c)
Parameters:
----------
tensor: numpy array , count * c * h * w
Returns:
-------
numpy array images: count * h * w * c
"""
if isinstance(tensor, torch.FloatTensor):
return np.transpose(tensor.detach().numpy(), (0, 2, 3, 1))
else:
raise Exception(
"covert b*c*h*w tensor to b*h*w*c numpy error.This tensor must have 4 dimension of float data type.")