io.py 2.35 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os.path as osp

import cv2
import numpy as np

from mmcv.utils import is_str, check_file_exist, mkdir_or_exist
from mmcv.opencv_info import USE_OPENCV2

if not USE_OPENCV2:
    from cv2 import IMREAD_COLOR, IMREAD_GRAYSCALE, IMREAD_UNCHANGED
else:
    from cv2 import CV_LOAD_IMAGE_COLOR as IMREAD_COLOR
    from cv2 import CV_LOAD_IMAGE_GRAYSCALE as IMREAD_GRAYSCALE
    from cv2 import CV_LOAD_IMAGE_UNCHANGED as IMREAD_UNCHANGED

imread_flags = {
    'color': IMREAD_COLOR,
    'grayscale': IMREAD_GRAYSCALE,
    'unchanged': IMREAD_UNCHANGED
}

22
23

def imread(img_or_path, flag='color'):
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    """Read an image.

    Args:
        img_or_path (ndarray or str): Either a numpy array or image path.
            If it is a numpy array (loaded image), then it will be returned
            as is.
        flag (str): Flags specifying the color type of a loaded image,
            candidates are `color`, `grayscale` and `unchanged`.

    Returns:
        ndarray: Loaded image array.
    """
    if isinstance(img_or_path, np.ndarray):
        return img_or_path
    elif is_str(img_or_path):
        flag = imread_flags[flag] if is_str(flag) else flag
        check_file_exist(img_or_path,
                         'img file does not exist: {}'.format(img_or_path))
        return cv2.imread(img_or_path, flag)
    else:
        raise TypeError('"img" must be a numpy array or a filename')


47
def imfrombytes(content, flag='color'):
48
49
50
51
    """Read an image from bytes.

    Args:
        content (bytes): Image bytes got from files or other streams.
52
        flag (str): Same as :func:`imread`.
53
54
55
56

    Returns:
        ndarray: Loaded image array.
    """
Kai Chen's avatar
Kai Chen committed
57
    img_np = np.frombuffer(content, np.uint8)
58
59
60
61
62
    flag = imread_flags[flag] if is_str(flag) else flag
    img = cv2.imdecode(img_np, flag)
    return img


63
def imwrite(img, file_path, params=None, auto_mkdir=True):
64
65
66
    """Write image to file

    Args:
67
        img (ndarray): Image array to be written.
68
69
        file_path (str): Image file path.
        params (None or list): Same as opencv's :func:`imwrite` interface.
tjsongzw's avatar
tjsongzw committed
70
        auto_mkdir (bool): If the parent folder of `file_path` does not exist,
71
72
73
74
75
76
77
78
79
            whether to create it automatically.

    Returns:
        bool: Successful or not.
    """
    if auto_mkdir:
        dir_name = osp.abspath(osp.dirname(file_path))
        mkdir_or_exist(dir_name)
    return cv2.imwrite(file_path, img, params)