pyiqa.utils

Submodules

Package Contents

Classes

FileClient

A general file client to access files in different backend.

AvgTimer

MessageLogger

Message logger for printing.

Functions

crop_border(imgs, crop_border)

Crop borders of images.

imfrombytes(content[, flag, float32])

Read an image from bytes.

img2tensor(imgs[, bgr2rgb, float32])

Numpy array to tensor.

imwrite(img, file_path[, params, auto_mkdir])

Write image to file.

tensor2img(tensor[, rgb2bgr, out_type, min_max])

Convert torch Tensors into image numpy arrays.

imread2tensor(img_source[, rgb])

Read image to tensor.

scandir_images(dir[, max_dataset_size, followlinks])

Get all image files from a directory and return a sorted list of fullpath.

get_env_info()

Get environment information.

get_root_logger([logger_name, log_level, log_file])

Get the root logger.

init_tb_logger(log_dir)

init_wandb_logger(opt)

We now only use wandb to sync tensorboard log.

check_resume(opt, resume_iter)

Check resume states and pretrain_network paths.

get_time_str()

make_exp_dirs(opt)

Make dirs for experiments.

mkdir_and_rename(path)

mkdirs. If path exists, rename it with timestamp, create a new one, and move it to archive folder.

scandir(dir_path[, suffix, recursive, full_path])

Scan a directory to find the interested files.

set_random_seed([seed])

Set random seeds.

sizeof_fmt(size[, suffix])

Get human readable file size.

download_file_from_google_drive(file_id, save_path)

Download files from google drive.

load_file_from_url(url[, model_dir, progress, file_name])

Load file form http url, will download models if necessary.

rgb2ycbcr(→ torch.Tensor)

Convert a batch of RGB images to a batch of YCbCr images

ycbcr2rgb(→ torch.Tensor)

Convert a batch of YCbCr images to a batch of RGB images

class pyiqa.utils.FileClient(backend='disk', **kwargs)[source]

Bases: object

A general file client to access files in different backend.

The client loads a file or text in a specified backend from its path and return it as a binary file. it can also register other backend accessor with a given name and backend class.

Attributes:
backend (str): The storage backend type. Options are “disk”,

“memcached” and “lmdb”.

client (BaseStorageBackend): The backend object.

get(filepath, client_key='default')[source]
get_text(filepath)[source]
pyiqa.utils.crop_border(imgs, crop_border)[source]

Crop borders of images.

Args:

imgs (list[ndarray] | ndarray): Images with shape (h, w, c). crop_border (int): Crop border for each end of height and weight.

Returns:

list[ndarray]: Cropped images.

pyiqa.utils.imfrombytes(content, flag='color', float32=False)[source]

Read an image from bytes.

Args:

content (bytes): Image bytes got from files or other streams. flag (str): Flags specifying the color type of a loaded image,

candidates are color, grayscale and unchanged.

float32 (bool): Whether to change to float32., If True, will also norm

to [0, 1]. Default: False.

Returns:

ndarray: Loaded image array.

pyiqa.utils.img2tensor(imgs, bgr2rgb=True, float32=True)[source]

Numpy array to tensor.

Args:

imgs (list[ndarray] | ndarray): Input images. bgr2rgb (bool): Whether to change bgr to rgb. float32 (bool): Whether to change to float32.

Returns:
list[tensor] | tensor: Tensor images. If returned results only have

one element, just return tensor.

pyiqa.utils.imwrite(img, file_path, params=None, auto_mkdir=True)[source]

Write image to file.

Args:

img (ndarray): Image array to be written. file_path (str): Image file path. params (None or list): Same as opencv’s imwrite() interface. auto_mkdir (bool): If the parent folder of file_path does not exist,

whether to create it automatically.

Returns:

bool: Successful or not.

pyiqa.utils.tensor2img(tensor, rgb2bgr=True, out_type=np.uint8, min_max=(0, 1))[source]

Convert torch Tensors into image numpy arrays.

After clamping to [min, max], values will be normalized to [0, 1].

Args:
tensor (Tensor or list[Tensor]): Accept shapes:
  1. 4D mini-batch Tensor of shape (B x 3/1 x H x W);

  2. 3D Tensor of shape (3/1 x H x W);

3) 2D Tensor of shape (H x W). Tensor channel should be in RGB order.

rgb2bgr (bool): Whether to change rgb to bgr. out_type (numpy type): output types. If np.uint8, transform outputs

to uint8 type with range [0, 255]; otherwise, float type with range [0, 1]. Default: np.uint8.

min_max (tuple[int]): min and max values for clamp.

Returns:

(Tensor or list): 3D ndarray of shape (H x W x C) OR 2D ndarray of shape (H x W). The channel order is BGR.

pyiqa.utils.imread2tensor(img_source, rgb=False)[source]

Read image to tensor.

Args:

img_source (str, bytes, or PIL.Image): image filepath string, image contents as a bytearray or a PIL Image instance rgb: convert input to RGB if true

pyiqa.utils.scandir_images(dir, max_dataset_size=float('inf'), followlinks=True)[source]

Get all image files from a directory and return a sorted list of fullpath.

class pyiqa.utils.AvgTimer(window=200)[source]
start()[source]
record()[source]
get_current_time()[source]
get_avg_time()[source]
class pyiqa.utils.MessageLogger(opt, start_iter=1, tb_logger=None)[source]

Message logger for printing.

Args:
opt (dict): Config. It contains the following keys:

name (str): Exp name. logger (dict): Contains ‘print_freq’ (str) for logger interval. train (dict): Contains ‘total_iter’ (int) for total iters. use_tb_logger (bool): Use tensorboard logger.

start_iter (int): Start iter. Default: 1. tb_logger (obj:tb_logger): Tensorboard logger. Default: None.

reset_start_time()[source]
pyiqa.utils.get_env_info()[source]

Get environment information.

Currently, only log the software version.

pyiqa.utils.get_root_logger(logger_name='pyiqa', log_level=logging.INFO, log_file=None)[source]

Get the root logger.

The logger will be initialized if it has not been initialized. By default a StreamHandler will be added. If log_file is specified, a FileHandler will also be added.

Args:

logger_name (str): root logger name. Default: ‘basicsr’. log_file (str | None): The log filename. If specified, a FileHandler

will be added to the root logger.

log_level (int): The root logger level. Note that only the process of

rank 0 is affected, while other processes will set the level to “Error” and be silent most of the time.

Returns:

logging.Logger: The root logger.

pyiqa.utils.init_tb_logger(log_dir)[source]
pyiqa.utils.init_wandb_logger(opt)[source]

We now only use wandb to sync tensorboard log.

pyiqa.utils.check_resume(opt, resume_iter)[source]

Check resume states and pretrain_network paths.

Args:

opt (dict): Options. resume_iter (int): Resume iteration.

pyiqa.utils.get_time_str()[source]
pyiqa.utils.make_exp_dirs(opt)[source]

Make dirs for experiments.

pyiqa.utils.mkdir_and_rename(path)[source]

mkdirs. If path exists, rename it with timestamp, create a new one, and move it to archive folder.

Args:

path (str): Folder path.

pyiqa.utils.scandir(dir_path, suffix=None, recursive=False, full_path=False)[source]

Scan a directory to find the interested files.

Args:

dir_path (str): Path of the directory. suffix (str | tuple(str), optional): File suffix that we are

interested in. Default: None.

recursive (bool, optional): If set to True, recursively scan the

directory. Default: False.

full_path (bool, optional): If set to True, include the dir_path.

Default: False.

Returns:

A generator for all the interested files with relative paths.

pyiqa.utils.set_random_seed(seed=123)[source]

Set random seeds.

pyiqa.utils.sizeof_fmt(size, suffix='B')[source]

Get human readable file size.

Args:

size (int): File size. suffix (str): Suffix. Default: ‘B’.

Return:

str: Formatted file siz.

pyiqa.utils.download_file_from_google_drive(file_id, save_path)[source]

Download files from google drive.

Ref: https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive # noqa E501

Args:

file_id (str): File id. save_path (str): Save path.

pyiqa.utils.load_file_from_url(url, model_dir=None, progress=True, file_name=None)[source]

Load file form http url, will download models if necessary.

Ref:https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py

Args:

url (str): URL to be downloaded. model_dir (str): The path to save the downloaded model. Should be a full path. If None, use pytorch hub_dir.

Default: None.

progress (bool): Whether to show the download progress. Default: True. file_name (str): The downloaded file name. If None, use the file name in the url. Default: None.

Returns:

str: The path to the downloaded file.

pyiqa.utils.rgb2ycbcr(x: torch.Tensor) torch.Tensor[source]

Convert a batch of RGB images to a batch of YCbCr images

It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.

Args:

x: Batch of images with shape (N, 3, H, W). RGB color space, range [0, 1].

Returns:

Batch of images with shape (N, 3, H, W). YCbCr color space.

pyiqa.utils.ycbcr2rgb(x: torch.Tensor) torch.Tensor[source]

Convert a batch of YCbCr images to a batch of RGB images

It implements the inversion of the above rgb2ycbcr function.

Args:

x: Batch of images with shape (N, 3, H, W). YCbCr color space, range [0, 1].

Returns:

Batch of images with shape (N, 3, H, W). RGB color space.