pyailib.utils package

Submodules

pyailib.utils.colormaps module

pyailib.utils.colors module

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

Converts gray image values to rgb image

converts gray image values 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 (numpy array) – The gray image.

  • 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 pyailib as pl
import matplotlib.pyplot as plt
import numpy as np

cmap = 'jet'
# cmap = 'hsv'
# cmap = 'hot'
# cmap = 'parula'
gray = pl.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, np.min(gray), np.max(gray), gray.dtype)
print(rgb.shape, np.min(rgb), np.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()
pyailib.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 (numpy array) – Original RGB tensor.

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

pyailib.utils.const module

pyailib.utils.convert module

pyailib.utils.convert.str2list(s)

Converts string with [ and ] to list

Parameters

s (str) – The string.

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

Extracts numbers in a string.

Parameters
  • s (str) – The string.

  • tfunc (None, optional) – formating function, such as int, float.

Returns

The number list.

Return type

list

pyailib.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

pyailib.utils.file module

pyailib.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.

pyailib.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. Sometimes you need to sort the list using sorted.

Return type

list

pyailib.utils.file.pathjoin(*kwargs)

Joint strings to a path.

Parameters

*kwargs – strings.

Returns

The joined path string.

Return type

str

pyailib.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

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

Read a file and extract numbers in it.

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, 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

list

pyailib.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

pyailib.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. (default)

Returns

File content.

Return type

str

pyailib.utils.image module

pyailib.utils.image.histeq(img, nbins=256)
pyailib.utils.image.imread(imgfile)
pyailib.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 (ndarray) – Input image.

  • oshape (tulpe, 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

ndarray

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)
pyailib.utils.image.imsave(outfile, img)

pyailib.utils.ios module

pyailib.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

pyailib.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.

pyailib.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.

pyailib.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.

pyailib.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

pyailib.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

pyailib.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

pyailib.utils.plot_show module

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

Bases: object

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

pyailib.utils.typevalue module

pyailib.utils.typevalue.bin2int(b, endian='<')
pyailib.utils.typevalue.peakvalue(A)

Compute the peak value of the input.

Find peak value in matrix

Parameters

A (numpy array) – Data for finding peak value

Returns

Peak value.

Return type

number

Module contents