|
a |
|
b/utils/utils.py |
|
|
1 |
import calendar |
|
|
2 |
import csv |
|
|
3 |
import datetime |
|
|
4 |
import pickle |
|
|
5 |
import time |
|
|
6 |
|
|
|
7 |
import cv2 |
|
|
8 |
import matplotlib.pyplot |
|
|
9 |
import numpy as np |
|
|
10 |
from PIL import Image |
|
|
11 |
from matplotlib.backends.backend_pdf import PdfPages |
|
|
12 |
|
|
|
13 |
COLORS = ['b', 'r', 'g', 'c'] |
|
|
14 |
|
|
|
15 |
|
|
|
16 |
def timestamp(): |
|
|
17 |
ts = calendar.timegm(time.gmtime()) |
|
|
18 |
return datetime.datetime.fromtimestamp(ts).isoformat() |
|
|
19 |
|
|
|
20 |
|
|
|
21 |
def apply_colormap(img, colormap_handle): |
|
|
22 |
img = img - img.min() |
|
|
23 |
if img.max() != 0: |
|
|
24 |
img = img / img.max() |
|
|
25 |
img = Image.fromarray(np.uint8(colormap_handle(img) * 255)) |
|
|
26 |
return img |
|
|
27 |
|
|
|
28 |
|
|
|
29 |
def plot_histogram(data, bins, range, title, exportPDF=None): |
|
|
30 |
f = matplotlib.pyplot.figure() |
|
|
31 |
matplotlib.pyplot.hist(data.flatten(), bins=bins, range=range, density=True) # arguments are passed to np.histogram |
|
|
32 |
matplotlib.pyplot.title(title) |
|
|
33 |
matplotlib.pyplot.show(block=False) |
|
|
34 |
|
|
|
35 |
# save a pdf to disk |
|
|
36 |
if exportPDF: |
|
|
37 |
pp = PdfPages(exportPDF) |
|
|
38 |
pp.savefig(f) |
|
|
39 |
pp.close() |
|
|
40 |
|
|
|
41 |
return f |
|
|
42 |
|
|
|
43 |
|
|
|
44 |
def plot_histogram_with_labels(data, labels, bins, _range, title, exportPDF=None): |
|
|
45 |
classes = np.unique(labels) |
|
|
46 |
f = matplotlib.pyplot.figure() |
|
|
47 |
|
|
|
48 |
for i in range(classes.size): |
|
|
49 |
data_with_current_label = data[labels == classes[i]] |
|
|
50 |
n, bins, patches = matplotlib.pyplot.hist(data_with_current_label.flatten(), bins=bins, range=_range, color=COLORS[i]) |
|
|
51 |
|
|
|
52 |
with open(f'{exportPDF.split(".")[0]}.{i}.npy', 'wb') as file: |
|
|
53 |
pickle.dump({'n': n, 'bins': bins, 'mean': np.mean(data_with_current_label), 'var': np.var(data_with_current_label)}, file) |
|
|
54 |
|
|
|
55 |
with open(exportPDF + ".{}.csv".format(i), mode="w") as csv_file: |
|
|
56 |
fieldnames = ["Bin", "Count"] |
|
|
57 |
writer = csv.DictWriter(csv_file, fieldnames=fieldnames) |
|
|
58 |
writer.writeheader() |
|
|
59 |
for k in range(len(n)): |
|
|
60 |
writer.writerow({"Bin": bins[k], "Count": n[k]}) |
|
|
61 |
|
|
|
62 |
matplotlib.pyplot.title(title) |
|
|
63 |
matplotlib.pyplot.show(block=False) |
|
|
64 |
|
|
|
65 |
# save a pdf to disk |
|
|
66 |
if exportPDF: |
|
|
67 |
pp = PdfPages(exportPDF) |
|
|
68 |
pp.savefig(f) |
|
|
69 |
pp.close() |
|
|
70 |
|
|
|
71 |
return f |
|
|
72 |
|
|
|
73 |
|
|
|
74 |
def normalize(x): |
|
|
75 |
return np.expand_dims(cv2.normalize(x, None, 0, 1, cv2.NORM_MINMAX), -1) |