initial commit

This commit is contained in:
Sen Liang committed 2022-01-21 17:42:41 +08:00
commit c7175dd7ff
127 files changed
+13949

No files matched your search

+149
View File
@@ -0,0 +1,149 @@
import dominate
import ntpath
from dominate.tags import meta, h3, table, tr, td, p, a, img, br
import os
from subprocess import Popen, PIPE
from skimage.transform import resize
from pathlib import Path
import math
from common import utils
from common.image import save_image
class HTML():
"""This HTML class allows us to save images and write texts into a single HTML file.
It consists of functions such as <add_header> (add a text header to the HTML file),
<add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk).
It is based on Python library 'dominate', a Python library for creating and manipulating HTML documents using a DOM API.
"""
def __init__(self, web_dir, title, opt, refresh=0):
"""Initialize the HTML classes
Parameters:
web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/
title (str) -- the webpage name
refresh (int) -- how often the website refresh itself; if 0; no refreshing
"""
self.opt = opt
self.title = title
self.web_dir = Path(web_dir)
self.img_dir = self.web_dir.joinpath("images")
self.img_dir.mkdir(parents=True, exist_ok=True)
self.doc = dominate.document(title=title)
if refresh > 0:
with self.doc.head:
meta(http_equiv="refresh", content=str(refresh))
def get_image_dir(self):
"""Return the directory that stores images"""
return self.img_dir
def add_header(self, text):
"""Insert a header to the HTML file
Parameters:
text (str) -- the header text
"""
with self.doc:
h3(text)
def add_images(self, ims, txts, links, width=400):
"""add images to the HTML file
Parameters:
ims (str list) -- a list of image paths
txts (str list) -- a list of image names shown on the website
links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page
"""
ncol = 6
nrow = math.ceil( len(ims) / ncol )
for irow in range(nrow):
itable = table(border=1, style="table-layout: fixed;") # Insert a table
self.doc.add(itable)
with itable:
with tr():
# for im, txt, link in zip(ims, txts, links):
for icol in range(ncol):
idx = ncol * irow + icol
if idx >= len(ims): break
with td(style="word-wrap: break-word;", halign="center", valign="top"):
with p():
with a(href=links[idx]):
img(style="width:%dpx" % width, src=ims[idx])
br()
p(txts[idx])
def save(self):
"""save the current content to the HMTL file"""
path_html = self.web_dir.joinpath("index.html")
with open(str(path_html), 'wt') as f:
f.write(self.doc.render())
def save_images(self, visuals, image_path, aspect_ratio=1.0, width=256):
"""Save images to the disk.
Parameters:
webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details)
visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs
image_path (str) -- the string is used to create image paths
aspect_ratio (float) -- the aspect ratio of saved images
width (int) -- the images will be resized to width x width
This function will save images stored in 'visuals' to the HTML file specified by 'webpage'.
"""
image_dir = self.get_image_dir()
short_path = ntpath.basename(image_path[0])
short_path1 = ntpath.basename(ntpath.dirname(image_path[0]))
short_path = short_path1 + '-' + short_path
name = os.path.splitext(short_path)[0]
print(f"image_dir={image_dir}, short_path={short_path}, name={name}")
self.add_header(name)
ims, txts, links = [], [], []
for label, im_data in visuals.items():
im = utils.tensor2im(im_data)
image_name = '%s_%s.png' % (name, label)
save_path = os.path.join(image_dir, image_name)
h, w, _ = im.shape
if aspect_ratio > 1.0:
#im = imresize(im, (h, int(w * aspect_ratio)), interp='bicubic')
im = resize(im, (h, int(w * aspect_ratio)))
if aspect_ratio < 1.0:
#im = imresize(im, (int(h / aspect_ratio), w), interp='bicubic')
im = resize(im, (int(h / aspect_ratio), w))
save_image(im, save_path)
ims.append(image_name)
txts.append(label)
links.append(image_name)
self.add_images(ims, txts, links, width=width)
if __name__ == '__main__': # we show an example usage here.
html = HTML('web/', 'test_html', opt=None)
html.add_header('hello world')
ims, txts, links = [], [], []
for n in range(4):
ims.append('image_%d.png' % n)
txts.append('text_%d' % n)
links.append('image_%d.png' % n)
html.add_images(ims, txts, links)
html.save()
+413
View File
@@ -0,0 +1,413 @@
import cv2
from matplotlib import pyplot as plt
import numpy as np
import seaborn as sns
from csl_common.utils.nn import to_numpy
def denormalize(tensor):
if tensor.shape[1] == 3:
tensor[:, 0] += 0.518
tensor[:, 1] += 0.418
tensor[:, 2] += 0.361
elif tensor.shape[-1] == 3:
tensor[..., 0] += 0.518
tensor[..., 1] += 0.418
tensor[..., 2] += 0.361
def denormalized(tensor):
if isinstance(tensor, np.ndarray):
t = tensor.copy()
else:
t = tensor.clone()
denormalize(t)
return t
def color_map(data, vmin=None, vmax=None, cmap=plt.cm.viridis):
if vmin is None:
vmin = data.min()
if vmax is None:
vmax = data.max()
val = np.maximum(vmin, np.minimum(vmax, data))
norm = (val-vmin)/(vmax-vmin)
cm = cmap(norm)
if isinstance(cm, tuple):
return cm[:3]
if len(cm.shape) > 2:
cm = cm[:,:,:3]
return cm
# take an array of shape (n, height, width) or (n, height, width, channels)
# and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)
def make_grid(data, padsize=2, padval=255, nCols=10, dsize=None, fx=None, fy=None, normalize=False):
# if not isinstance(data, np.ndarray):
data = np.array(data)
if data.shape[0] == 0:
return
if data.shape[1] == 3:
data = data.transpose((0,2,3,1))
if data.dtype == np.float64:
data = data.astype(np.float32)
if normalize:
data -= data.min()
data /= data.max()
else:
data[data < 0] = 0
# data[data > 1] = 1
# force the number of filters to be square
# n = int(np.ceil(np.sqrt(data.shape[0])))
c = nCols
r = int(np.ceil(data.shape[0]/float(c)))
padding = ((0, r*c - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
# tile the filters into an image
data = data.reshape((r, c) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
data = data.reshape((r * data.shape[1], c * data.shape[3]) + data.shape[4:])
if dsize is not None or fx is not None or fy is not None:
data = cv2.resize(data, dsize=dsize, fx=fx, fy=fy, interpolation=cv2.INTER_LANCZOS4)
return data
def vis_square(data, padsize=1, padval=0, wait=0, nCols=10, title='results', dsize=None, fx=None, fy=None, normalize=False):
img = make_grid(data, padsize=padsize, padval=padval, nCols=nCols, dsize=dsize, fx=fx, fy=fy, normalize=normalize)
cv2.imshow(title, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
cv2.waitKey(wait)
def cvt32FtoU8(img):
return (img * 255.0).astype(np.uint8)
def to_disp_image(img, denorm=False, output_dtype=np.uint8):
if not isinstance(img, np.ndarray):
img = img.detach().cpu().numpy()
img = img.astype(np.float32).copy()
if img.shape[0] == 3:
img = img.transpose((1, 2, 0)).copy()
if denorm:
img = denormalized(img)
if img.max() > 2.00:
if isinstance(img, np.ndarray):
img /= 255.0
else:
raise ValueError("Image data in wrong value range (min/max={:.2f}/{:.2f}).".format(img.min(), img.max()))
img = np.clip(img, a_min=0, a_max=1)
if output_dtype == np.uint8:
img = cvt32FtoU8(img)
return img
def to_disp_images(images, denorm=False):
return [to_disp_image(i, denorm) for i in images]
def add_frames_to_images(images, labels, label_colors, gt_labels=None):
import collections
if not isinstance(labels, (collections.Sequence, np.ndarray)):
labels = [labels] * len(images)
new_images = to_disp_images(images)
for idx, (disp, label) in enumerate(zip(new_images, labels)):
frame_width = 3
bgr = label_colors[label]
cv2.rectangle(disp,
(frame_width // 2, frame_width // 2),
(disp.shape[1] - frame_width // 2, disp.shape[0] - frame_width // 2),
color=bgr,
thickness=frame_width)
if gt_labels is not None:
radius = 8
color = (0, 1, 0) if gt_labels[idx] == label else (1, 0, 0)
cv2.circle(disp, (disp.shape[1] - 2*radius, 2*radius), radius, color, -1)
return new_images
def add_cirle_to_images(images, intensities, cmap=plt.cm.viridis, radius=10):
new_images = to_disp_images(images)
for idx, (disp, val) in enumerate(zip(new_images, intensities)):
# color = (0, 1, 0) if gt_labels[idx] == label else (1, 0, 0)
# color = plt_colors.to_rgb(val)
if isinstance(val, float):
color = cmap(val).ravel()
else:
color = val
cv2.circle(disp, (2*radius, 2*radius), radius, color, -1)
# new_images.append(disp)
return new_images
def get_pos_in_image(loc, text_size, image_shape):
bottom_offset = int(6*text_size)
right_offset = int(95*text_size)
line_height = int(35*text_size)
mid_offset = right_offset
top_offset = line_height + int(0.05*line_height)
if loc == 'tl':
pos = (2, top_offset)
elif loc == 'tr':
pos = (image_shape[1]-right_offset, top_offset)
elif loc == 'tr+1':
pos = (image_shape[1]-right_offset, top_offset + line_height)
elif loc == 'tr+2':
pos = (image_shape[1]-right_offset, top_offset + line_height*2)
elif loc == 'bl':
pos = (2, image_shape[0]-bottom_offset)
elif loc == 'bl-1':
pos = (2, image_shape[0]-bottom_offset-line_height)
elif loc == 'bl-2':
pos = (2, image_shape[0]-bottom_offset-2*line_height)
# elif loc == 'bm':
# pos = (mid_offset, image_shape[0]-bottom_offset)
# elif loc == 'bm-1':
# pos = (mid_offset, image_shape[0]-bottom_offset-line_height)
elif loc == 'br':
pos = (image_shape[1]-right_offset, image_shape[0]-bottom_offset)
elif loc == 'br-1':
pos = (image_shape[1]-right_offset, image_shape[0]-bottom_offset-line_height)
elif loc == 'br-2':
pos = (image_shape[1]-right_offset, image_shape[0]-bottom_offset-2*line_height)
elif loc == 'bm':
pos = (image_shape[1]-right_offset*2, image_shape[0]-bottom_offset)
elif loc == 'bm-1':
pos = (image_shape[1]-right_offset*2, image_shape[0]-bottom_offset-line_height)
elif loc == 'bm-2':
pos = (image_shape[1]-right_offset*2, image_shape[0]-bottom_offset-2*line_height)
else:
raise ValueError("Unknown location {}".format(loc))
return pos
def add_id_to_images(images, ids, gt_ids=None, loc='tl', color=(1,1,1), size=0.7, thickness=1):
new_images = to_disp_images(images)
for idx, (disp, val) in enumerate(zip(new_images, ids)):
if gt_ids is not None:
color = (0,1,0) if ids[idx] == gt_ids[idx] else (1,0,0)
# if val != 0:
pos = get_pos_in_image(loc, size, disp.shape)
cv2.putText(disp, str(val), pos, cv2.FONT_HERSHEY_DUPLEX, size, color, thickness, cv2.LINE_AA)
return new_images
def add_error_to_images(images, errors, loc='bl', size=0.65, vmin=0., vmax=30.0, thickness=1,
format_string='{:.1f}', colors=None):
new_images = to_disp_images(images)
if colors is None:
colors = color_map(to_numpy(errors), cmap=plt.cm.jet, vmin=vmin, vmax=vmax)
if images[0].dtype == np.uint8:
colors *= 255
for disp, err, color in zip(new_images, errors, colors):
pos = get_pos_in_image(loc, size, disp.shape)
cv2.putText(disp, format_string.format(err), pos, cv2.FONT_HERSHEY_DUPLEX, size, color, thickness, cv2.LINE_AA)
return new_images
def add_landmarks_to_images(images, landmarks, color=None, radius=2, gt_landmarks=None,
lm_errs=None, lm_confs=None, lm_rec_errs=None,
draw_dots=True, draw_wireframe=False, draw_gt_offsets=False, landmarks_to_draw=None,
offset_line_color=None):
def draw_wireframe_lines(img, lms):
pts = lms.reshape((-1,1,2)).astype(np.int32)
cv2.polylines(img, [pts[:17]], isClosed=False, color=color, lineType=cv2.LINE_AA) # head outline
cv2.polylines(img, [pts[17:22]], isClosed=False, color=color, lineType=cv2.LINE_AA) # left eyebrow
cv2.polylines(img, [pts[22:27]], isClosed=False, color=color, lineType=cv2.LINE_AA) # right eyebrow
cv2.polylines(img, [pts[27:31]], isClosed=False, color=color, lineType=cv2.LINE_AA) # nose vert
cv2.polylines(img, [pts[31:36]], isClosed=False, color=color, lineType=cv2.LINE_AA) # nose hor
cv2.polylines(img, [pts[36:42]], isClosed=True, color=color, lineType=cv2.LINE_AA) # left eye
cv2.polylines(img, [pts[42:48]], isClosed=True, color=color, lineType=cv2.LINE_AA) # right eye
cv2.polylines(img, [pts[48:60]], isClosed=True, color=color, lineType=cv2.LINE_AA) # outer mouth
cv2.polylines(img, [pts[60:68]], isClosed=True, color=color, lineType=cv2.LINE_AA) # inner mouth
def draw_wireframe_lines_98(img, lms):
pts = lms.reshape((-1,1,2)).astype(np.int32)
cv2.polylines(img, [pts[:33]], isClosed=False, color=color, lineType=cv2.LINE_AA) # head outline
cv2.polylines(img, [pts[33:42]], isClosed=True, color=color, lineType=cv2.LINE_AA) # left eyebrow
# cv2.polylines(img, [pts[38:42]], isClosed=False, color=color, lineType=cv2.LINE_AA) # right eyebrow
cv2.polylines(img, [pts[42:51]], isClosed=True, color=color, lineType=cv2.LINE_AA) # nose vert
cv2.polylines(img, [pts[51:55]], isClosed=False, color=color, lineType=cv2.LINE_AA) # nose hor
cv2.polylines(img, [pts[55:60]], isClosed=False, color=color, lineType=cv2.LINE_AA) # left eye
cv2.polylines(img, [pts[60:68]], isClosed=True, color=color, lineType=cv2.LINE_AA) # right eye
cv2.polylines(img, [pts[68:76]], isClosed=True, color=color, lineType=cv2.LINE_AA) # outer mouth
cv2.polylines(img, [pts[76:88]], isClosed=True, color=color, lineType=cv2.LINE_AA) # inner mouth
cv2.polylines(img, [pts[88:96]], isClosed=True, color=color, lineType=cv2.LINE_AA) # inner mouth
def draw_offset_lines(img, lms, gt_lms, errs):
if gt_lms.sum() == 0:
return
if lm_errs is None:
# if offset_line_color is None:
offset_line_color = (1,1,1)
colors = [offset_line_color] * len(lms)
else:
colors = color_map(errs, cmap=plt.cm.jet, vmin=0, vmax=15.0)
if img.dtype == np.uint8:
colors *= 255
for i, (p1, p2) in enumerate(zip(lms, gt_lms)):
if landmarks_to_draw is None or i in landmarks_to_draw:
if p1.min() > 0:
cv2.line(img, tuple(p1.astype(int)), tuple(p2.astype(int)), colors[i], thickness=1, lineType=cv2.LINE_AA)
new_images = to_disp_images(images)
landmarks = to_numpy(landmarks)
gt_landmarks = to_numpy(gt_landmarks)
lm_errs = to_numpy(lm_errs)
img_size = new_images[0].shape[0]
default_color = (255,255,255)
if gt_landmarks is not None and draw_gt_offsets:
for img_id in range(len(new_images)):
if gt_landmarks[img_id].sum() == 0:
continue
dists = None
if lm_errs is not None:
dists = lm_errs[img_id]
draw_offset_lines(new_images[img_id], landmarks[img_id], gt_landmarks[img_id], dists)
for img_id, (disp, lm) in enumerate(zip(new_images, landmarks)):
if len(lm) in [68, 21, 19, 98, 8, 5, 38]:
if draw_dots:
for lm_id in range(0,len(lm)):
if landmarks_to_draw is None or lm_id in landmarks_to_draw or len(lm) != 68:
lm_color = color
if lm_color is None:
if lm_errs is not None:
lm_color = color_map(lm_errs[img_id, lm_id], cmap=plt.cm.jet, vmin=0, vmax=1.0)
else:
lm_color = default_color
# if lm_errs is not None and lm_errs[img_id, lm_id] > 40.0:
# lm_color = (1,0,0)
cv2.circle(disp, tuple(lm[lm_id].astype(int).clip(0, disp.shape[0]-1)), radius=radius, color=lm_color, thickness=-1, lineType=cv2.LINE_AA)
if lm_confs is not None:
max_radius = img_size * 0.05
try:
conf_radius = max(2, int((1-lm_confs[img_id, lm_id]) * max_radius))
except ValueError:
conf_radius = 2
# if lm_confs[img_id, lm_id] > 0.4:
cirle_color = (0,0,255)
# if lm_confs[img_id, lm_id] < is_good_landmark(lm_confs, lm_rec_errs):
# if not is_good_landmark(lm_confs[img_id, lm_id], lm_rec_errs[img_id, lm_id]):
if lm_errs[img_id, lm_id] > 10.0:
cirle_color = (255,0,0)
cv2.circle(disp, tuple(lm[lm_id].astype(int)), conf_radius, cirle_color, 1, lineType=cv2.LINE_AA)
# Draw outline if we actually have 68 valid landmarks.
# Landmarks can be zeros for UMD landmark format (21 points).
if draw_wireframe:
nlms = (np.count_nonzero(lm.sum(axis=1)))
if nlms == 68:
draw_wireframe_lines(disp, lm)
elif nlms == 98:
draw_wireframe_lines_98(disp, lm)
else:
# colors = ['tab:gray', 'tab:orange', 'tab:brown', 'tab:pink', 'tab:cyan', 'tab:olive', 'tab:red', 'tab:blue']
# colors_rgb = list(map(plt_colors.to_rgb, colors))
colors = sns.color_palette("Set1", n_colors=14)
for i in range(0,len(lm)):
cv2.circle(disp, tuple(lm[i].astype(int)), radius=radius, color=colors[i], thickness=2, lineType=cv2.LINE_AA)
return new_images
def draw_z(z_vecs):
fy = 1
width = 10
z_zoomed = []
for lvl, _ft in enumerate(to_numpy(z_vecs)):
# _ft = (_ft-_ft.min())/(_ft.max()-_ft.min())
vmin = 0 if lvl == 0 else -1
canvas = np.zeros((int(fy*len(_ft)), width, 3))
canvas[:int(fy*len(_ft)), :] = color_map(cv2.resize(_ft.reshape(-1,1), dsize=(width, int(fy*len(_ft))),
interpolation=cv2.INTER_NEAREST), vmin=-1.0, vmax=1.0)
z_zoomed.append(canvas)
return make_grid(z_zoomed, nCols=len(z_vecs), padsize=1, padval=0).transpose((1,0,2))
def overlay_heatmap(img, hm, heatmap_opacity=0.45):
img_dtype = img.dtype
img_new = img.copy()
if img_new.dtype == np.uint8:
img_new = img_new.astype(np.float32) / 255.0
# hm = np.clip(hm, a_min=0, a_max=1.0)
hm_colored = color_map(hm**3, vmin=0, vmax=1.0, cmap=plt.cm.inferno)
if len(hm.shape) > 2:
mask = cv2.blur(hm, ksize=(3, 3))
print('mask', mask.dtype)
mask = mask.mean(axis=2)
mask = mask > 0.05
for c in range(3):
# img_new[...,c] = img[...,c] + hm[...,c]
img_new[..., c][mask] = img[..., c][mask] * 0.7 + hm[..., c][mask] * 0.3
else:
# mask = mask > 0.05
# img_new[mask] = img[mask] * 0.7 + hm_col[mask] * 0.3
# heatmap_opacity = 0.7
if hm_colored.shape != img.shape:
hm_colored = cv2.resize(hm_colored, (img.shape[1], img.shape[0]), interpolation=cv2.INTER_CUBIC)
img_new = img_new + hm_colored * heatmap_opacity
img_new = img_new.clip(0, 1)
if img_dtype == np.uint8:
img_new = cvt32FtoU8(img_new)
assert img_new.dtype == img.dtype
assert img_new.shape == img.shape
return img_new
def draw_z_vecs(levels_z, ncols, size, vmin=-1, vmax=1, vertical=False):
z_fy = 1.0
width, height = [int(x) for x in size[:2]]
def draw_z(z):
z_zoomed = []
for lvl, ft in enumerate(z):
_ft = ft[:]
# _ft = (_ft-_ft.min())/(_ft.max()-_ft.min())
# canvas = np.zeros((height, width, 3))
if vertical:
_ft_reshaped = _ft.reshape(-1, 1)
else:
_ft_reshaped = _ft.reshape(1, -1)
canvas = color_map(
cv2.resize(_ft_reshaped, dsize=(width, height), interpolation=cv2.INTER_NEAREST),
vmin=vmin,
vmax=vmax
)
z_zoomed.append(canvas)
return z_zoomed
# pivots not used anymore FIXME: remove
def draw_pivot(z_imgs, pivot):
z_imgs_new = to_disp_images(z_imgs)
for new_img in z_imgs_new:
y = int(pivot*z_fy)
cv2.line(new_img, (0, y), (new_img.shape[1], y), (1, 1, 1), thickness=1)
return z_imgs_new
# pivots = [z.shape[1] for z in levels_z if z is not None]
# z_vis_list_per_level = [draw_pivot(draw_z(z), p) for z,p in zip(levels_z, pivots) if z is not None]
z_vis_list_per_level = [draw_z(z) for z in levels_z if z is not None]
z_grid_per_sample = [make_grid(all_vis_sample, nCols=len(levels_z)) for all_vis_sample in zip(*z_vis_list_per_level)]
return make_grid(z_grid_per_sample, nCols=ncols, normalize=False)
def draw_status_bar(text, status_bar_width, status_bar_height, dtype=np.float32, text_size=-1, text_color=(255,255,255)):
img_status_bar = np.zeros((status_bar_height, status_bar_width, 3), dtype=dtype)
if text_size <= 0:
text_size = status_bar_height * 0.025
cv2.putText(img_status_bar, text, (4,img_status_bar.shape[0]-5), cv2.FONT_HERSHEY_SIMPLEX, text_size, text_color, 1, cv2.LINE_AA)
return img_status_bar
+220
View File
@@ -0,0 +1,220 @@
import numpy as np
import os
import sys
import ntpath
import time
from subprocess import Popen, PIPE
from pathlib import Path
from common import utils
# from common.vis.html import HTML
from common.image import tensor2im, save_image
from common.landmark import landmark_to_image
class Visualizer():
"""This class includes several functions that can display/save images
and print/save logging information.
It uses a Python library 'visdom' for display,
and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images.
"""
def __init__(self, opt, logger):
"""Initialize the Visualizer class
Parameters:
opt -- stores all the experiment flags; needs to be a subclass of BaseOptions
Step 1: Cache the training/test options
Step 2: connect to a visdom server
Step 3: create an HTML object for saveing HTML filters
Step 4: create a logging file to store training losses
"""
self.opt = opt # cache the option
self.logger = logger # logger info
self.name = opt.MODEL.name
self.path_output = Path(opt.OUTPUT_DIR) # the output path for debug image
if self.opt.VISUAL.use_visdom: # connect to a visdom server given <vsdm_port> and <vsdm_server>
import visdom
self.ncols = opt.VISUAL.vsdm_ncol
self.vis = visdom.Visdom(server=opt.VISUAL.vsdm_server, port=opt.VISUAL.vsdm_port, env=opt.VISUAL.vsdm_env)
if not self.vis.check_connection():
self.create_visdom_connections()
if self.opt.VISUAL.use_HTML:
# create an HTML object at <checkpoints_dir>/web/;
# images will be saved under <checkpoints_dir>/web/images/
self.web_dir = self.path_output.joinpath('web')
self.img_dir = self.path_output.joinpath('web', 'images')
print(f'create web directory {self.web_dir} ...')
self.img_dir.mkdir(parents=True, exist_ok=True)
# create a logging file to store training losses
self.logger.info(f'================ Training Loss ({time.strftime("%c")}) ================\n')
def reset(self):
"""Reset the self.saved status"""
pass
def create_visdom_connections(self):
"""If the program could not connect to Visdom server,
this function will start a new server at port < self.opt.VISUAL.vsdm_port > """
cmd = sys.executable + ' -m visdom.server -p %d &>/dev/null &' % self.opt.VISUAL.vsdm_port
self.logger.info('\n\nCould not connect to Visdom server. \n Trying to start a server....')
self.logger.info('Command: %s' % cmd)
Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
def display_current_results(self, visuals, epoch=0, batch=0):
"""Display current results on visdom; save current results to an HTML file.
Parameters:
visuals (OrderedDict) - - dictionary of images to display or save
epoch (int) - - the current epoch
save_result (bool) - - if save the current results to an HTML file
"""
if self.opt.VISUAL.use_visdom: # show images in the browser using visdom
ncols = self.ncols
if ncols > 0: # show all the images in one visdom panel
ncols = min(ncols, len(visuals))
h, w = next(iter(visuals.values())).shape[:2]
table_css = """<style>
table {border-collapse: separate; border-spacing: 4px; white-space: nowrap; text-align: center}
table td {width: % dpx; height: % dpx; padding: 4px; outline: 4px solid black}
</style>""" % (w, h) # create a table css
# create a table of images.
title = self.name
label_html = ''
label_html_row = ''
images = []
idx = 0
for label, image in visuals.items():
image_numpy = tensor2im(image)
label_html_row += '<td>%s</td>' % label
images.append(image_numpy.transpose([2, 0, 1]))
idx += 1
if idx % ncols == 0:
label_html += '<tr>%s</tr>' % label_html_row
label_html_row = ''
white_image = np.ones_like(image_numpy.transpose([2, 0, 1])) * 255
while idx % ncols != 0:
images.append(white_image)
label_html_row += '<td></td>'
idx += 1
if label_html_row != '':
label_html += '<tr>%s</tr>' % label_html_row
try:
self.vis.images(images, nrow=ncols, win=self.opt.VISUAL.vsdm_id + 1, padding=2, opts=dict(title=title + ' images'))
label_html = '<table>%s</table>' % label_html
self.vis.text(table_css + label_html, win=self.opt.VISUAL.vsdm_id + 2, opts=dict(title=title + ' labels'))
except Exception:
print("CANNOT vis image, text")
self.create_visdom_connections()
else: # show each image in a separate visdom panel;
idx = 1
try:
for label, image in visuals.items():
image_numpy = tensor2im(image)
self.vis.image(image_numpy.transpose([2, 0, 1]), opts=dict(title=label), win=self.opt.VISUAL.vsdm_id + idx)
idx += 1
except Exception:
print("CANNOT vis image")
self.create_visdom_connections()
if self.opt.VISUAL.use_HTML: # save images to an HTML file
# create a webpage
webpage = HTML(str(self.web_dir), 'Experiment name = %s' % self.name, opt=self.opt, refresh=-1)
# save images to the disk
for ilabel, data in visuals.items():
image_numpy = tensor2im(data)
img_path = self.img_dir.joinpath(f'epoch_{epoch:04d}_{batch:04d}_{ilabel}.png')
save_image(image_numpy, img_path)
# for epoch and batch
for iepoch in range(epoch, 0, -1):
# print(f"DEBUG: iepoch={iepoch}, batch={batch}")
if iepoch % self.opt.FREQ.epoch_display != 0 : continue
for ibatch in range(batch, -1, -1):
# print(f"DEBUG: ibatch={ibatch}")
if ibatch % self.opt.FREQ.batch_display != 0: continue
# print(f"DEBUG add page: iepoch={iepoch} ibatch={ibatch}")
webpage.add_header(f'epoch [{iepoch:04d}] - Batch [{ibatch:04d}]')
ims, txts, links = [], [], []
for ilabel in visuals.keys():
img_path = f'images/epoch_{iepoch:04d}_{ibatch:04d}_{ilabel}.png'
ims.append(img_path)
txts.append(ilabel)
links.append(img_path)
webpage.add_images(ims, txts, links, width=self.opt.VISUAL.vsdm_wsize)
webpage.save()
def plot_current_losses(self, epoch, counter_ratio, losses):
"""display the current losses on visdom display: dictionary of error labels and values
Parameters:
epoch (int) -- current epoch
counter_ratio (float) -- progress (percentage) in the current epoch, between 0 to 1
losses (OrderedDict) -- training losses stored in the format of (name, float) pairs
"""
if not self.opt.VISUAL.use_visdom: return
if not hasattr(self, 'plot_data'):
self.plot_data = {'X': [], 'Y': [], 'legend': list(losses.keys())}
self.plot_data['X'].append(epoch + counter_ratio)
self.plot_data['Y'].append([losses[k] for k in self.plot_data['legend']])
try:
# print("np.array(self.plot_data['X'])=", np.array(self.plot_data['X']))
# print("np.array(self.plot_data['Y'])=", np.array(self.plot_data['Y']))
# print("self.plot_data['legend']", self.plot_data['legend'])
self.vis.line(
X=np.stack([np.array(self.plot_data['X'])] * len(self.plot_data['legend']), 1),
Y=np.array(self.plot_data['Y']),
opts={
'title': self.name + ' loss over time',
'legend': self.plot_data['legend'],
'xlabel': 'epoch',
'ylabel': 'loss'},
win=self.opt.VISUAL.vsdm_id)
except Exception:
raise("CANNOT vis line")
self.create_visdom_connections()
# losses: same format as |losses| of plot_current_losses
def print_current_losses(self, epoch, iters, losses, t_comp=None, t_data=None):
"""print current losses on console; also save the losses to the disk
Parameters:
epoch (int) -- current epoch
iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch)
losses (OrderedDict) -- training losses stored in the format of (name, float) pairs
t_comp (float) -- computational time per data point (normalized by batch_size)
t_data (float) -- data loading time per data point (normalized by batch_size)
"""
msg = f"[Epoch:{epoch:03d}-{iters:03d}]"
for k,v in losses.items():
msg += f" {k}= {v:0.5f} "
self.logger.info(f'{msg}') # save the message