torchlib.utils package

Submodules

torchlib.utils.colormaps module

torchlib.utils.colors module

torchlib.utils.colors.gray2rgb(gray, cmap, drange=[0, 255], fmtstr=False)

Converts gray images to rgb image

converts gray images to rgb image according to the specified colormap string ‘cmap’, supported are: 'parula', 'jet', 'hsv', 'hot', 'cool', 'spring', 'summer', 'autumn', 'winter', 'gray', 'bone', 'copper', 'pink', 'lines', 'colorcube', 'prism', 'flag', 'white'.

Parameters
  • gray (torch tensor) – The gray image \(N\times H\times W\), or the gray images \(N\times H\times W\), \(N\) is the number of images.

  • cmap (str or colormap) – colormap string

  • drange (list or tuple) – The low and high value, default is [0, 255]

  • fmtstr (bool or str) – Specifies the format ('int', 'uint8', 'uint16', 'uint32', 'float16', 'float32', , 'float64') for the output rgb matrix. (default is False, don’t change)

Examples

import torchlib as tl
import matplotlib.pyplot as plt
import torch as th

cmap = 'jet'
# cmap = 'hsv'
# cmap = 'hot'
# cmap = 'parula'
gray = ts.imread('../../data/images/LenaGRAY256.png')
print(gray.shape)

rgb = gray2rgb(gray, cmap, [0, 1], False)  # rgb --> double, [0, 1]
# rgb = gray2rgb(gray, cmap, [0, 255], False)  # rgb --> double, [0., 255.]
# rgb = gray2rgb(gray, cmap, [0, 255], True)  # rgb --> uint8, [0, 255]

print(gray.shape, th.min(gray), th.max(gray), gray.dtype)
print(rgb.shape, th.min(rgb), th.max(rgb), rgb.dtype)

plt.figure()
plt.subplot(121)
plt.imshow(gray, cmap=pl.parula if cmap == 'parula' else cmap)
plt.subplot(122)
plt.imshow(rgb)
plt.show()
torchlib.utils.colors.rgb2gray(rgb, fmt='chnllast')

Converts RGB image to GRAY image

Converts RGB image to GRAY image according to

\[G = 0.2989R + 0.5870G + 0.1140B \]

see matlab’s rgb2gray function for details.

Parameters
  • rgb (Tensor) – Original RGB tensor.

  • fmt (str, optional) – Specifies the position of channels in rgb tensor, surpported are: - 'chnllast' (default) - 'chnlfirst'

torchlib.utils.const module

torchlib.utils.convert module

torchlib.utils.convert.str2list(s)

Converts string with [ and ] to list

Parameters

s (str) – The string.

torchlib.utils.convert.str2num(s, tfunc=None)

Extracts numbers in a string.

Parameters
  • s (str) – The string.

  • tfunc (None, optional) – formating function.

Returns

The number list.

Return type

list

torchlib.utils.convert.str2sec(x, sep=':')

Extracts second in a time string.

hh:mm:ss –> hh*3600 + mm*60 + ss

Parameters
  • s (str) – The string or string list/tuple.

  • sep (str) – The separator between hour, minute and seconds, default is ':'.

Returns

y – The seconds.

Return type

int

torchlib.utils.file module

torchlib.utils.file.fileparts(file)

Filename parts

Returns the path, file name, and file name extension for the specified file. The file input is the name of a file or folder, and can include a path and file name extension.

Parameters

file (str) – The name string of a file or folder.

Returns

  • filepath (str) – The path string of the file or folder.

  • name (str) – The name string of the file or folder.

  • ext (str) – The extension string of the file.

torchlib.utils.file.listxfile(listdir=None, exts=None, recursive=False, filelist=[])

List the files in a directory.

Parameters
  • listdir (None, optional) – The directory for listing. The default is None, which means return filelist directly.

  • exts (str, list or None, optional) – File extension string or extension string list, such as '.png' or ['.png', 'jpg']. The default is None, which means any extension.

  • recursive (bool, optional) – Recursive search? The default is False, which means only list the root directory (listdir).

  • filelist (list, optional) – An initial list contains files’s path. The default is [].

Returns

The list of file path with extension exts.

Return type

list

torchlib.utils.file.pathjoin(*kwargs)

Joint strings to a path.

Parameters

*kwargs – strings.

Returns

The joined path string.

Return type

str

torchlib.utils.file.readcsv(filepath, sep=None, vfn=None, nlines=None)

Read a csv file and extract numbers in it.

Parameters
  • filepath (str) – The path string of the file.

  • sep (str, optional) – The separation character. Such as ',' or ' '. If None (default) or '' (empty) return a list of all the lines.

  • vfn (function or None, optional) – The function for formating the numbers. float –> convert to float number; int –> convert to integer number…, The default is None, which means won’t converted, string format.

  • nlines (None, optional) – The number of lines for reading, the default is None, which means all the lines.

Returns

The list of numbers or strings.

Return type

list

torchlib.utils.file.readnum(filepath, pmain='Train', psub='loss', vfn=<class 'float'>, nshots=None)

Read a file and extract numbers in it.

Parameters
  • filepath (str) – Description

  • pmain (str, optional) – The matching pattern string, such as ‘—>Train’.

  • psub (str, optional) – The sub-matching pattern string, such as ‘loss’.

  • vfn (function, optional) – The function for formating the numbers. float –> convert to float number; int –> convert to integer number…, The default is float.

  • nshots (None, optional) – The number of shots of sub-matching pattern.

Returns

The list of numbers.

Return type

str

torchlib.utils.file.readsec(filepath, pmain='Train', psub='time: ', vfn=<class 'int'>, nshots=None)

Read a file and extract seconds in it.

hh:mm:ss –> hh*3600 + mm*60 + ss

Parameters
  • filepath (str) – The path string of the file.

  • pmain (str, optional) – The matching pattern string, such as ‘—>Train’.

  • psub (str, optional) – The sub-matching pattern string, such as ‘loss’.

  • vfn (function or None, optional) – The function for formating the numbers. float –> convert to float number; int –> convert to integer number.

  • nshots (None, optional) – The number of shots of sub-matching pattern.

Returns

The list of seconds.

Return type

list

torchlib.utils.file.readtxt(filepath, mode=None)

Read a text file.

Parameters
  • filepath (str) – The path string of the file.

  • mode (str or None, optional) – 'line' –> reading line-by-line. 'all' –> reading all content.

Returns

File content.

Return type

str

torchlib.utils.image module

torchlib.utils.image.histeq(img, nbins=256)
torchlib.utils.image.imadjust(img, lhin, lhout)
torchlib.utils.image.imadjustlog(img, lhin=None, lhout=None)
torchlib.utils.image.imread(imgfile)
torchlib.utils.image.imresize(img, oshape=None, odtype=None, order=1, mode='constant', cval=0, clip=True, preserve_range=False)

resize image to oshape

see skimage.transform.resize().

Parameters
  • img (tensor) – Input image.

  • oshape (tuple, optional) – output shape (the default is None, which is the same as the input)

  • odtype (str, optional) – output data type, 'uint8', 'uint16', 'int8', ... (the default is None, float)

  • order (int, optional) – The order of the spline interpolation, default is 1. The order has to be in the range 0-5. See skimage.transform.warp for detail.

  • mode (str, optional) – Points outside the boundaries of the input are filled according to the given mode. {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, Modes match the behaviour of numpy.pad. The default mode is ‘constant’.

  • cval (float, optional) – Used in conjunction with mode ‘constant’, the value outside the image boundaries.

  • clip (bool, optional) – Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range.

  • preserve_range (bool, optional) – Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float.

Returns

resized – Resized version of the input.

Return type

tensor

Notes

Modes ‘reflect’ and ‘symmetric’ are similar, but differ in whether the edge pixels are duplicated during the reflection. As an example, if an array has values [0, 1, 2] and was padded to the right by four values using symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it would be [0, 1, 2, 1, 0, 1, 2].

Examples

>>> from skimage import data
>>> from skimage.transform import resize
>>> image = data.camera()
>>> resize(image, (100, 100), mode='reflect').shape
(100, 100)
torchlib.utils.image.imsave(outfile, img)

torchlib.utils.ios module

torchlib.utils.ios.loadh5(filename, keys=None)

load h5 file

load data from a h5 file. ('None' will be replaced by None)

Parameters
  • filename (str) – File’s full path string.

  • keys (list) – list of keys.

Returns

D – The loaded data in dict type.

Return type

dict

torchlib.utils.ios.loadjson(filepath, field=None)

load a json file

Parameters
  • filepath (str) – The file path string.

  • field (None, optional) – The string of field that want to be loaded.

torchlib.utils.ios.loadmat(filepath)

load data from an .mat file

load data from an .mat file ('None' will be replaced by None)

see https://stackoverflow.com/questions/7008608/scipy-io-loadmat-nested-structures-i-e-dictionaries

Parameters

filepath (str) – The file path string.

torchlib.utils.ios.loadyaml(filepath, field=None)

Load a yaml file.

Parameters
  • filepath (str) – The file path string.

  • field (None, optional) – The string of field that want to be loaded.

torchlib.utils.ios.mvkeyh5(filepath, ksf, kst, sep='.')

rename keys in .h5 file

Parameters
  • filepath (str) – The file path string

  • ksf (list) – keys from list, e.g. [‘a.x’, ‘b.y’]

  • kst (list) – keys to list, e.g. [‘a.1’, ‘b.2’]

  • sep (str, optional) – The separate pattern, default is '.'

Returns

All is ok!

Return type

0

torchlib.utils.ios.saveh5(filename, mdict, mode='w')

save data to h5 file

save data to h5 file (None will be replaced by 'None')

Parameters
  • filename (str) – filename string

  • mdict (dict) – each dict is store in group, the elements in dict are store in dataset

  • mode (str) – save mode, 'w' for write, 'a' for add.

Returns

0 –> all is well.

Return type

number

torchlib.utils.ios.savemat(filepath, mdict, fmt='5')

save data to an .mat file

save data to .mat file (None will be replaced by 'None')

Parameters
  • filepath (str) – savefile path

  • mdict (dict) – data in dict formation.

  • fmt (str, optional) – mat formation, by default ‘5’

Returns

all is ok!

Return type

0

torchlib.utils.plot_show module

class torchlib.utils.plot_show.Plots(plotdir='./', xlabel='x', ylabel='y', title='', figname=None, issave=False, isshow=True)

Bases: object

torchlib.utils.plot_show.cplot(ca, lmod=None)
torchlib.utils.plot_show.plots(x, ydict, plotdir='./', xlabel='x', ylabel='y', title='', issave=False, isshow=True)

Module contents