Commit ddef9a56 authored by Kai Chen's avatar Kai Chen
Browse files

fix flake8 errors

parent f9d8870f
# flake8: noqa
from .arraymisc import * from .arraymisc import *
from .utils import * from .utils import *
from .fileio import * from .fileio import *
......
from .quantization import * from .quantization import quantize, dequantize
__all__ = ['quantize', 'dequantize']
import numpy as np import numpy as np
__all__ = ['quantize', 'dequantize']
def quantize(arr, min_val, max_val, levels, dtype=np.int64): def quantize(arr, min_val, max_val, levels, dtype=np.int64):
"""Quantize an array of (-inf, inf) to [0, levels-1]. """Quantize an array of (-inf, inf) to [0, levels-1].
......
from .io import * from .io import imread, imwrite, imfrombytes
from .transforms import * from .transforms import (bgr2gray, gray2bgr, bgr2rgb, rgb2bgr, bgr2hsv,
hsv2bgr, imflip, imrotate, imcrop, impad,
impad_to_multiple, imnorm, imdenorm, scale_size,
imresize, imresize_like, imrescale, limit_size)
__all__ = [
'imread', 'imwrite', 'imfrombytes', 'bgr2gray', 'gray2bgr', 'bgr2rgb',
'rgb2bgr', 'bgr2hsv', 'hsv2bgr', 'imflip', 'imrotate', 'imcrop', 'impad',
'impad_to_multiple', 'imnorm', 'imdenorm', 'scale_size', 'imresize',
'imresize_like', 'imrescale', 'limit_size'
]
...@@ -19,8 +19,6 @@ imread_flags = { ...@@ -19,8 +19,6 @@ imread_flags = {
'unchanged': IMREAD_UNCHANGED 'unchanged': IMREAD_UNCHANGED
} }
__all__ = ['imread', 'imwrite', 'imfrombytes']
def imread(img_or_path, flag='color'): def imread(img_or_path, flag='color'):
"""Read an image. """Read an image.
......
from .colorspace import * from .colorspace import bgr2gray, gray2bgr, bgr2rgb, rgb2bgr, bgr2hsv, hsv2bgr
from .geometry import * from .geometry import imflip, imrotate, imcrop, impad, impad_to_multiple
from .normalize import * from .normalize import imnorm, imdenorm
from .resize import * from .resize import scale_size, imresize, imresize_like, imrescale, limit_size
__all__ = [
'bgr2gray', 'gray2bgr', 'bgr2rgb', 'rgb2bgr', 'bgr2hsv', 'hsv2bgr',
'imflip', 'imrotate', 'imcrop', 'impad', 'impad_to_multiple', 'imnorm',
'imdenorm', 'scale_size', 'imresize', 'imresize_like', 'imrescale',
'limit_size'
]
import cv2 import cv2
__all__ = ['bgr2gray', 'gray2bgr', 'bgr2rgb', 'rgb2bgr', 'bgr2hsv', 'hsv2bgr']
def bgr2gray(img, keepdim=False): def bgr2gray(img, keepdim=False):
"""Convert a BGR image to grayscale image. """Convert a BGR image to grayscale image.
......
...@@ -3,8 +3,6 @@ from __future__ import division ...@@ -3,8 +3,6 @@ from __future__ import division
import cv2 import cv2
import numpy as np import numpy as np
__all__ = ['imflip', 'imrotate', 'imcrop', 'impad', 'impad_to_multiple']
def imflip(img, direction='horizontal'): def imflip(img, direction='horizontal'):
"""Flip an image horizontally or vertically. """Flip an image horizontally or vertically.
......
...@@ -2,8 +2,6 @@ import numpy as np ...@@ -2,8 +2,6 @@ import numpy as np
from .colorspace import bgr2rgb, rgb2bgr from .colorspace import bgr2rgb, rgb2bgr
__all__ = ['imnorm', 'imdenorm']
def imnorm(img, mean, std, to_rgb=True): def imnorm(img, mean, std, to_rgb=True):
img = img.astype(np.float32) img = img.astype(np.float32)
......
from .hooks import * from .runner import Runner, LogBuffer
from .io import * from .hooks import (Hook, CheckpointHook, ClosureHook, LrUpdaterHook,
from .parallel import * OptimizerHook, IterTimerHook, DistSamplerSeedHook,
from .runner import * LoggerHook, TextLoggerHook, PaviLoggerHook,
from .utils import * TensorboardLoggerHook)
from .io import (load_state_dict, load_checkpoint, weights_to_cpu,
save_checkpoint)
from .parallel import parallel_test, worker_func
from .utils import (get_host_info, get_dist_info, master_only, get_time_str,
add_file_handler, obj_from_dict)
__all__ = [
'Runner', 'LogBuffer', 'Hook', 'CheckpointHook', 'ClosureHook',
'LrUpdaterHook', 'OptimizerHook', 'IterTimerHook', 'DistSamplerSeedHook',
'LoggerHook', 'TextLoggerHook', 'PaviLoggerHook', 'TensorboardLoggerHook',
'load_state_dict', 'load_checkpoint', 'weights_to_cpu', 'save_checkpoint',
'parallel_test', 'worker_func', 'get_host_info', 'get_dist_info',
'master_only', 'get_time_str', 'add_file_handler', 'obj_from_dict'
]
from .log_buffer import LogBuffer from .log_buffer import LogBuffer
from .runner import Runner from .runner import Runner
__all__ = ['LogBuffer', 'Runner']
from .config import * from .config import ConfigDict, Config
from .misc import * from .misc import (is_str, iter_cast, list_cast, tuple_cast, is_seq_of,
from .path import * is_list_of, is_tuple_of, slice_list, concat_list,
from .progressbar import * check_prerequisites, requires_package, requires_executable)
from .timer import * from .path import (is_filepath, fopen, check_file_exist, mkdir_or_exist,
symlink, scandir)
from .progressbar import ProgressBar, track_progress, track_parallel_progress
from .timer import Timer, TimerError, check_time
__all__ = [
'ConfigDict', 'Config', 'is_str', 'iter_cast', 'list_cast', 'tuple_cast',
'is_seq_of', 'is_list_of', 'is_tuple_of', 'slice_list', 'concat_list',
'check_prerequisites', 'requires_package', 'requires_executable',
'is_filepath', 'fopen', 'check_file_exist', 'mkdir_or_exist', 'symlink',
'scandir', 'ProgressBar', 'track_progress', 'track_parallel_progress',
'Timer', 'TimerError', 'check_time'
]
...@@ -37,9 +37,20 @@ def iter_cast(inputs, dst_type, return_type=None): ...@@ -37,9 +37,20 @@ def iter_cast(inputs, dst_type, return_type=None):
return return_type(out_iterable) return return_type(out_iterable)
list_cast = functools.partial(iter_cast, return_type=list) def list_cast(inputs, dst_type):
"""Cast elements of an iterable object into a list of some type.
A partial method of :func:`iter_cast`.
"""
return iter_cast(inputs, dst_type, return_type=list)
tuple_cast = functools.partial(iter_cast, return_type=tuple)
def tuple_cast(inputs, dst_type):
"""Cast elements of an iterable object into a tuple of some type.
A partial method of :func:`iter_cast`.
"""
return iter_cast(inputs, dst_type, return_type=tuple)
def is_seq_of(seq, expected_type, seq_type=None): def is_seq_of(seq, expected_type, seq_type=None):
...@@ -66,9 +77,20 @@ def is_seq_of(seq, expected_type, seq_type=None): ...@@ -66,9 +77,20 @@ def is_seq_of(seq, expected_type, seq_type=None):
return True return True
is_list_of = functools.partial(is_seq_of, seq_type=list) def is_list_of(seq, expected_type):
"""Check whether it is a list of some type.
A partial method of :func:`is_seq_of`.
"""
return is_seq_of(seq, expected_type, seq_type=list)
is_tuple_of = functools.partial(is_seq_of, seq_type=tuple)
def is_tuple_of(seq, expected_type):
"""Check whether it is a tuple of some type.
A partial method of :func:`is_seq_of`.
"""
return is_seq_of(seq, expected_type, seq_type=tuple)
def slice_list(in_list, lens): def slice_list(in_list, lens):
...@@ -161,30 +183,29 @@ def _check_executable(cmd): ...@@ -161,30 +183,29 @@ def _check_executable(cmd):
return True return True
requires_package = functools.partial( def requires_package(prerequisites):
check_prerequisites, checker=_check_py_package) """A decorator to check if some python packages are installed.
requires_package.__doc__ = """A decorator to check if some python packages are installed. Example:
>>> @requires_package('numpy')
Example: >>> func(arg1, args):
>>> @requires_package('numpy') >>> return numpy.zeros(1)
>>> func(arg1, args): array([0.])
>>> return numpy.zeros(1) >>> @requires_package(['numpy', 'non_package'])
array([0.]) >>> func(arg1, args):
>>> @requires_package(['numpy', 'non_package']) >>> return numpy.zeros(1)
>>> func(arg1, args): ImportError
>>> return numpy.zeros(1) """
ImportError return check_prerequisites(prerequisites, checker=_check_py_package)
"""
requires_executable = functools.partial(
check_prerequisites, checker=_check_executable)
requires_executable.__doc__ = """A decorator to check if some executable files are installed. def requires_executable(prerequisites):
"""A decorator to check if some executable files are installed.
Example: Example:
>>> @requires_executable('ffmpeg') >>> @requires_executable('ffmpeg')
>>> func(arg1, args): >>> func(arg1, args):
>>> print(1) >>> print(1)
1 1
""" """
return check_prerequisites(prerequisites, checker=_check_executable)
...@@ -12,6 +12,7 @@ class Timer(object): ...@@ -12,6 +12,7 @@ class Timer(object):
"""A flexible Timer class. """A flexible Timer class.
:Example: :Example:
>>> import time >>> import time
>>> import mmcv >>> import mmcv
>>> with mmcv.Timer(): >>> with mmcv.Timer():
...@@ -94,6 +95,7 @@ def check_time(timer_id): ...@@ -94,6 +95,7 @@ def check_time(timer_id):
be registered when the method is called for the first time. be registered when the method is called for the first time.
:Example: :Example:
>>> import time >>> import time
>>> import mmcv >>> import mmcv
>>> for i in range(1, 6): >>> for i in range(1, 6):
......
from mmcv.opencv_info import USE_OPENCV2 from .io import Cache, VideoReader, frames2video
from .processing import convert_video, resize_video, cut_video, concat_video
from .optflow import flowread, flowwrite, quantize_flow, dequantize_flow
if not USE_OPENCV2: __all__ = [
from cv2 import (CAP_PROP_FRAME_WIDTH, CAP_PROP_FRAME_HEIGHT, CAP_PROP_FPS, 'Cache', 'VideoReader', 'frames2video', 'convert_video', 'resize_video',
CAP_PROP_FRAME_COUNT, CAP_PROP_FOURCC, 'cut_video', 'concat_video', 'flowread', 'flowwrite', 'quantize_flow',
CAP_PROP_POS_FRAMES, VideoWriter_fourcc) 'dequantize_flow'
else: ]
from cv2.cv import CV_CAP_PROP_FRAME_WIDTH as CAP_PROP_FRAME_WIDTH
from cv2.cv import CV_CAP_PROP_FRAME_HEIGHT as CAP_PROP_FRAME_HEIGHT
from cv2.cv import CV_CAP_PROP_FPS as CAP_PROP_FPS
from cv2.cv import CV_CAP_PROP_FRAME_COUNT as CAP_PROP_FRAME_COUNT
from cv2.cv import CV_CAP_PROP_FOURCC as CAP_PROP_FOURCC
from cv2.cv import CV_CAP_PROP_POS_FRAMES as CAP_PROP_POS_FRAMES
from cv2.cv import CV_FOURCC as VideoWriter_fourcc
from .io import *
from .processing import *
from .optflow import *
from collections import OrderedDict
import os.path as osp import os.path as osp
from collections import OrderedDict
import cv2 import cv2
from mmcv.utils import (scandir, check_file_exist, mkdir_or_exist, from mmcv.utils import (scandir, check_file_exist, mkdir_or_exist,
track_progress) track_progress)
from . import (CAP_PROP_FRAME_WIDTH, CAP_PROP_FRAME_HEIGHT, CAP_PROP_FPS, from mmcv.opencv_info import USE_OPENCV2
CAP_PROP_FRAME_COUNT, CAP_PROP_FOURCC, CAP_PROP_POS_FRAMES,
VideoWriter_fourcc) if not USE_OPENCV2:
from cv2 import (CAP_PROP_FRAME_WIDTH, CAP_PROP_FRAME_HEIGHT, CAP_PROP_FPS,
CAP_PROP_FRAME_COUNT, CAP_PROP_FOURCC,
CAP_PROP_POS_FRAMES, VideoWriter_fourcc)
else:
from cv2.cv import CV_CAP_PROP_FRAME_WIDTH as CAP_PROP_FRAME_WIDTH
from cv2.cv import CV_CAP_PROP_FRAME_HEIGHT as CAP_PROP_FRAME_HEIGHT
from cv2.cv import CV_CAP_PROP_FPS as CAP_PROP_FPS
from cv2.cv import CV_CAP_PROP_FRAME_COUNT as CAP_PROP_FRAME_COUNT
from cv2.cv import CV_CAP_PROP_FOURCC as CAP_PROP_FOURCC
from cv2.cv import CV_CAP_PROP_POS_FRAMES as CAP_PROP_POS_FRAMES
from cv2.cv import CV_FOURCC as VideoWriter_fourcc
class Cache(object): class Cache(object):
...@@ -50,6 +61,7 @@ class VideoReader(object): ...@@ -50,6 +61,7 @@ class VideoReader(object):
cache. cache.
:Example: :Example:
>>> import mmcv >>> import mmcv
>>> v = mmcv.VideoReader('sample.mp4') >>> v = mmcv.VideoReader('sample.mp4')
>>> len(v) # get the total frame number with `len()` >>> len(v) # get the total frame number with `len()`
...@@ -131,7 +143,7 @@ class VideoReader(object): ...@@ -131,7 +143,7 @@ class VideoReader(object):
"""Read the next frame. """Read the next frame.
If the next frame have been decoded before and in the cache, then If the next frame have been decoded before and in the cache, then
return it directly, otherwise decode and return it, put it in the cache. return it directly, otherwise decode, cache and return it.
Returns: Returns:
ndarray or None: Return the frame if successful, otherwise None. ndarray or None: Return the frame if successful, otherwise None.
...@@ -163,8 +175,9 @@ class VideoReader(object): ...@@ -163,8 +175,9 @@ class VideoReader(object):
ndarray or None: Return the frame if successful, otherwise None. ndarray or None: Return the frame if successful, otherwise None.
""" """
if frame_id < 0 or frame_id >= self._frame_cnt: if frame_id < 0 or frame_id >= self._frame_cnt:
raise IndexError('"frame_id" must be between 0 and {}'.format( raise IndexError(
self._frame_cnt - 1)) '"frame_id" must be between 0 and {}'.format(self._frame_cnt -
1))
if frame_id == self._position: if frame_id == self._position:
return self.read() return self.read()
if self._cache: if self._cache:
...@@ -177,7 +190,7 @@ class VideoReader(object): ...@@ -177,7 +190,7 @@ class VideoReader(object):
if ret: if ret:
if self._cache: if self._cache:
self._cache.put(self._position, img) self._cache.put(self._position, img)
self._position += 1 self._position += 1
return img return img
def current_frame(self): def current_frame(self):
...@@ -203,7 +216,8 @@ class VideoReader(object): ...@@ -203,7 +216,8 @@ class VideoReader(object):
Args: Args:
frame_dir (str): Output directory to store all the frame images. frame_dir (str): Output directory to store all the frame images.
file_start (int): Filenames will start from the specified number. file_start (int): Filenames will start from the specified number.
filename_tmpl (str): Filename template with the index as the variable. filename_tmpl (str): Filename template with the index as the
placeholder.
start (int): The starting frame index. start (int): The starting frame index.
max_num (int): Maximum number of frames to be written. max_num (int): Maximum number of frames to be written.
show_progress (bool): Whether to show a progress bar. show_progress (bool): Whether to show a progress bar.
...@@ -240,7 +254,10 @@ class VideoReader(object): ...@@ -240,7 +254,10 @@ class VideoReader(object):
def __getitem__(self, index): def __getitem__(self, index):
if isinstance(index, slice): if isinstance(index, slice):
return [self.get_frame(i) for i in range(*index.indices(self.frame_cnt))] return [
self.get_frame(i)
for i in range(*index.indices(self.frame_cnt))
]
# support negative indexing # support negative indexing
if index < 0: if index < 0:
index += self.frame_cnt index += self.frame_cnt
......
...@@ -12,8 +12,11 @@ def convert_video(in_file, out_file, print_cmd=False, pre_options='', ...@@ -12,8 +12,11 @@ def convert_video(in_file, out_file, print_cmd=False, pre_options='',
"""Convert a video with ffmpeg. """Convert a video with ffmpeg.
This provides a general api to ffmpeg, the executed command is:: This provides a general api to ffmpeg, the executed command is::
ffmpeg -y <pre_options> -i <in_file> <options> <out_file>
`ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`
Options(kwargs) are mapped to ffmpeg commands with the following rules: Options(kwargs) are mapped to ffmpeg commands with the following rules:
- key=val: "-key val" - key=val: "-key val"
- key=True: "-key" - key=True: "-key"
- key=False: "" - key=False: ""
......
from .color import * from .color import Color, color_val
from .image import * from .image import imshow, imshow_bboxes
from .optflow import * from .optflow import flowshow, flow2rgb, make_color_wheel
__all__ = [
'Color', 'color_val', 'imshow', 'imshow_bboxes', 'flowshow', 'flow2rgb',
'make_color_wheel'
]
...@@ -27,7 +27,7 @@ def color_val(color): ...@@ -27,7 +27,7 @@ def color_val(color):
color (:obj:`Color`/str/tuple/int/ndarray): Color inputs color (:obj:`Color`/str/tuple/int/ndarray): Color inputs
Returns: Returns:
tuple: A tuple of 3 integers indicating BGR channels. tuple[int]: A tuple of 3 integers indicating BGR channels.
""" """
if is_str(color): if is_str(color):
return Color[color].value return Color[color].value
......
# flake8: noqa
import os import os
import os.path as osp import os.path as osp
import tempfile import tempfile
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment