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

port from cvbase and do some refactoring

parent b3a84c7f
import os
import os.path as osp
import tempfile
import mmcv
import numpy as np
import pytest
from numpy.testing import assert_array_equal, assert_array_almost_equal
class TestImage(object):
@classmethod
def setup_class(cls):
# the test img resolution is 400x300
cls.img_path = osp.join(osp.dirname(__file__), 'data/color.jpg')
cls.gray_img_path = osp.join(
osp.dirname(__file__), 'data/grayscale.jpg')
def assert_img_equal(self, img, ref_img, ratio_thr=0.999):
assert img.shape == ref_img.shape
assert img.dtype == ref_img.dtype
area = ref_img.shape[0] * ref_img.shape[1]
diff = np.abs(img.astype('int32') - ref_img.astype('int32'))
assert np.sum(diff <= 1) / float(area) > ratio_thr
def test_read_img(self):
img = mmcv.read_img(self.img_path)
assert img.shape == (300, 400, 3)
img = mmcv.read_img(self.img_path, 'grayscale')
assert img.shape == (300, 400)
img = mmcv.read_img(self.gray_img_path)
assert img.shape == (300, 400, 3)
img = mmcv.read_img(self.gray_img_path, 'unchanged')
assert img.shape == (300, 400)
img = mmcv.read_img(img)
assert_array_equal(img, mmcv.read_img(img))
with pytest.raises(TypeError):
mmcv.read_img(1)
def test_img_from_bytes(self):
with open(self.img_path, 'rb') as f:
img_bytes = f.read()
img = mmcv.img_from_bytes(img_bytes)
assert img.shape == (300, 400, 3)
def test_write_img(self):
img = mmcv.read_img(self.img_path)
out_file = osp.join(tempfile.gettempdir(), 'mmcv_test.jpg')
mmcv.write_img(img, out_file)
rewrite_img = mmcv.read_img(out_file)
os.remove(out_file)
self.assert_img_equal(img, rewrite_img)
def test_bgr2gray(self):
in_img = np.random.rand(10, 10, 3).astype(np.float32)
out_img = mmcv.bgr2gray(in_img)
computed_gray = (in_img[:, :, 0] * 0.114 + in_img[:, :, 1] * 0.587 +
in_img[:, :, 2] * 0.299)
assert_array_almost_equal(out_img, computed_gray, decimal=4)
out_img_3d = mmcv.bgr2gray(in_img, True)
assert out_img_3d.shape == (10, 10, 1)
assert_array_almost_equal(out_img_3d[..., 0], out_img, decimal=4)
def test_gray2bgr(self):
in_img = np.random.rand(10, 10).astype(np.float32)
out_img = mmcv.gray2bgr(in_img)
assert out_img.shape == (10, 10, 3)
for i in range(3):
assert_array_almost_equal(out_img[..., i], in_img, decimal=4)
def test_bgr2rgb(self):
in_img = np.random.rand(10, 10, 3).astype(np.float32)
out_img = mmcv.bgr2rgb(in_img)
assert out_img.shape == in_img.shape
assert_array_equal(out_img[..., 0], in_img[..., 2])
assert_array_equal(out_img[..., 1], in_img[..., 1])
assert_array_equal(out_img[..., 2], in_img[..., 0])
def test_rgb2bgr(self):
in_img = np.random.rand(10, 10, 3).astype(np.float32)
out_img = mmcv.rgb2bgr(in_img)
assert out_img.shape == in_img.shape
assert_array_equal(out_img[..., 0], in_img[..., 2])
assert_array_equal(out_img[..., 1], in_img[..., 1])
assert_array_equal(out_img[..., 2], in_img[..., 0])
def test_bgr2hsv(self):
in_img = np.random.rand(10, 10, 3).astype(np.float32)
out_img = mmcv.bgr2hsv(in_img)
argmax = in_img.argmax(axis=2)
computed_hsv = np.empty_like(in_img, dtype=in_img.dtype)
for i in range(in_img.shape[0]):
for j in range(in_img.shape[1]):
b = in_img[i, j, 0]
g = in_img[i, j, 1]
r = in_img[i, j, 2]
v = max(r, g, b)
s = (v - min(r, g, b)) / v if v != 0 else 0
if argmax[i, j] == 0:
h = 240 + 60 * (r - g) / (v - min(r, g, b))
elif argmax[i, j] == 1:
h = 120 + 60 * (b - r) / (v - min(r, g, b))
else:
h = 60 * (g - b) / (v - min(r, g, b))
if h < 0:
h += 360
computed_hsv[i, j, :] = [h, s, v]
assert_array_almost_equal(out_img, computed_hsv, decimal=2)
def test_scale_size(self):
assert mmcv.scale_size((300, 200), 0.5) == (150, 100)
assert mmcv.scale_size((11, 22), 0.7) == (8, 15)
def test_resize(self):
resized_img = mmcv.resize(self.img_path, (1000, 600))
assert resized_img.shape == (600, 1000, 3)
resized_img, w_scale, h_scale = mmcv.resize(self.img_path, (1000, 600),
True)
assert (resized_img.shape == (600, 1000, 3) and w_scale == 2.5
and h_scale == 2.0)
for mode in ['nearest', 'bilinear', 'bicubic', 'area', 'lanczos']:
resized_img = mmcv.resize(
self.img_path, (1000, 600), interpolation=mode)
assert resized_img.shape == (600, 1000, 3)
def test_resize_like(self):
a = np.zeros((100, 200, 3))
resized_img = mmcv.resize_like(self.img_path, a)
assert resized_img.shape == (100, 200, 3)
def test_resize_by_ratio(self):
resized_img = mmcv.resize_by_ratio(self.img_path, 1.5)
assert resized_img.shape == (450, 600, 3)
resized_img = mmcv.resize_by_ratio(self.img_path, 0.934)
assert resized_img.shape == (280, 374, 3)
def test_resize_keep_ar(self):
# resize (400, 300) to (max_1000, max_600)
resized_img = mmcv.resize_keep_ar(self.img_path, 1000, 600)
assert resized_img.shape == (600, 800, 3)
resized_img, scale = mmcv.resize_keep_ar(self.img_path, 1000, 600,
True)
assert resized_img.shape == (600, 800, 3) and scale == 2.0
# resize (400, 300) to (max_200, max_180)
img = mmcv.read_img(self.img_path)
resized_img = mmcv.resize_keep_ar(img, 200, 180)
assert resized_img.shape == (150, 200, 3)
resized_img, scale = mmcv.resize_keep_ar(self.img_path, 200, 180, True)
assert resized_img.shape == (150, 200, 3) and scale == 0.5
# max_long_edge cannot be less than max_short_edge
with pytest.raises(ValueError):
mmcv.resize_keep_ar(self.img_path, 500, 600)
def test_limit_size(self):
# limit to 800
resized_img = mmcv.limit_size(self.img_path, 800)
assert resized_img.shape == (300, 400, 3)
resized_img, scale = mmcv.limit_size(self.img_path, 800, True)
assert resized_img.shape == (300, 400, 3) and scale == 1
# limit to 200
resized_img = mmcv.limit_size(self.img_path, 200)
assert resized_img.shape == (150, 200, 3)
resized_img, scale = mmcv.limit_size(self.img_path, 200, True)
assert resized_img.shape == (150, 200, 3) and scale == 0.5
# test with img rather than img path
img = mmcv.read_img(self.img_path)
resized_img = mmcv.limit_size(img, 200)
assert resized_img.shape == (150, 200, 3)
resized_img, scale = mmcv.limit_size(img, 200, True)
assert resized_img.shape == (150, 200, 3) and scale == 0.5
def test_crop_img(self):
img = mmcv.read_img(self.img_path)
# yapf: disable
bboxes = np.array([[100, 100, 199, 199], # center
[0, 0, 150, 100], # left-top corner
[250, 200, 399, 299], # right-bottom corner
[0, 100, 399, 199], # wide
[150, 0, 299, 299]]) # tall
# yapf: enable
# crop one bbox
patch = mmcv.crop_img(img, bboxes[0, :])
patches = mmcv.crop_img(img, bboxes[[0], :])
assert patch.shape == (100, 100, 3)
patch_path = osp.join(osp.dirname(__file__), 'data/patches')
ref_patch = np.load(patch_path + '/0.npy')
self.assert_img_equal(patch, ref_patch)
assert isinstance(patches, list) and len(patches) == 1
self.assert_img_equal(patches[0], ref_patch)
# crop with no scaling and padding
patches = mmcv.crop_img(img, bboxes)
assert len(patches) == bboxes.shape[0]
for i in range(len(patches)):
ref_patch = np.load(patch_path + '/{}.npy'.format(i))
self.assert_img_equal(patches[i], ref_patch)
# crop with scaling and no padding
patches = mmcv.crop_img(img, bboxes, 1.2)
for i in range(len(patches)):
ref_patch = np.load(patch_path + '/scale_{}.npy'.format(i))
self.assert_img_equal(patches[i], ref_patch)
# crop with scaling and padding
patches = mmcv.crop_img(img, bboxes, 1.2, pad_fill=[255, 255, 0])
for i in range(len(patches)):
ref_patch = np.load(patch_path + '/pad_{}.npy'.format(i))
self.assert_img_equal(patches[i], ref_patch)
patches = mmcv.crop_img(img, bboxes, 1.2, pad_fill=0)
for i in range(len(patches)):
ref_patch = np.load(patch_path + '/pad0_{}.npy'.format(i))
self.assert_img_equal(patches[i], ref_patch)
def test_pad_img(self):
img = np.random.rand(10, 10, 3).astype(np.float32)
padded_img = mmcv.pad_img(img, (15, 12), 0)
assert_array_equal(img, padded_img[:10, :10, :])
assert_array_equal(
np.zeros((5, 12, 3), dtype='float32'), padded_img[10:, :, :])
assert_array_equal(
np.zeros((15, 2, 3), dtype='float32'), padded_img[:, 10:, :])
img = np.random.randint(256, size=(10, 10, 3)).astype('uint8')
padded_img = mmcv.pad_img(img, (15, 12, 3), [100, 110, 120])
assert_array_equal(img, padded_img[:10, :10, :])
assert_array_equal(
np.array([100, 110, 120], dtype='uint8') * np.ones(
(5, 12, 3), dtype='uint8'), padded_img[10:, :, :])
assert_array_equal(
np.array([100, 110, 120], dtype='uint8') * np.ones(
(15, 2, 3), dtype='uint8'), padded_img[:, 10:, :])
with pytest.raises(AssertionError):
mmcv.pad_img(img, (15, ), 0)
with pytest.raises(AssertionError):
mmcv.pad_img(img, (5, 5), 0)
with pytest.raises(AssertionError):
mmcv.pad_img(img, (5, 5), [0, 1])
def test_rotate_img(self):
img = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).astype(np.uint8)
assert_array_equal(mmcv.rotate_img(img, 0), img)
img_r = np.array([[7, 4, 1], [8, 5, 2], [9, 6, 3]])
assert_array_equal(mmcv.rotate_img(img, 90), img_r)
img_r = np.array([[3, 6, 9], [2, 5, 8], [1, 4, 7]])
assert_array_equal(mmcv.rotate_img(img, -90), img_r)
img = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]).astype(np.uint8)
img_r = np.array([[0, 6, 2, 0], [0, 7, 3, 0]])
assert_array_equal(mmcv.rotate_img(img, 90), img_r)
img_r = np.array([[1, 0, 0, 0], [2, 0, 0, 0]])
assert_array_equal(mmcv.rotate_img(img, 90, center=(0, 0)), img_r)
img_r = np.array([[255, 6, 2, 255], [255, 7, 3, 255]])
assert_array_equal(mmcv.rotate_img(img, 90, border_value=255), img_r)
img_r = np.array([[5, 1], [6, 2], [7, 3], [8, 4]])
assert_array_equal(mmcv.rotate_img(img, 90, auto_bound=True), img_r)
import os
import os.path as osp
import tempfile
import mmcv
import pytest
def _test_processor(file_format, test_obj, str_checker, mode='r+'):
# dump to a string
dump_str = mmcv.dump(test_obj, file_format=file_format)
str_checker(dump_str)
# load/dump with filenames
tmp_filename = osp.join(tempfile.gettempdir(), 'mmcv_test_dump')
mmcv.dump(test_obj, tmp_filename, file_format=file_format)
assert osp.isfile(tmp_filename)
load_obj = mmcv.load(tmp_filename, file_format=file_format)
assert load_obj == test_obj
os.remove(tmp_filename)
# json load/dump with a file-like object
with tempfile.NamedTemporaryFile(mode, delete=False) as f:
tmp_filename = f.name
mmcv.dump(test_obj, f, file_format=file_format)
assert osp.isfile(tmp_filename)
with open(tmp_filename, mode) as f:
load_obj = mmcv.load(f, file_format=file_format)
assert load_obj == test_obj
os.remove(tmp_filename)
# automatically inference the file format from the given filename
tmp_filename = osp.join(tempfile.gettempdir(),
'mmcv_test_dump.' + file_format)
mmcv.dump(test_obj, tmp_filename)
assert osp.isfile(tmp_filename)
load_obj = mmcv.load(tmp_filename)
assert load_obj == test_obj
os.remove(tmp_filename)
obj_for_test = [{'a': 'abc', 'b': 1}, 2, 'c']
def test_json():
def json_checker(dump_str):
assert dump_str in [
'[{"a": "abc", "b": 1}, 2, "c"]', '[{"b": 1, "a": "abc"}, 2, "c"]'
]
_test_processor('json', obj_for_test, json_checker)
def test_yaml():
def yaml_checker(dump_str):
assert dump_str in [
'- {a: abc, b: 1}\n- 2\n- c\n', '- {b: 1, a: abc}\n- 2\n- c\n'
]
_test_processor('yaml', obj_for_test, yaml_checker)
def test_pickle():
def pickle_checker(dump_str):
import pickle
assert pickle.loads(dump_str) == obj_for_test
_test_processor('pickle', obj_for_test, pickle_checker, mode='rb+')
def test_exception():
test_obj = [{'a': 'abc', 'b': 1}, 2, 'c']
with pytest.raises(ValueError):
mmcv.dump(test_obj)
with pytest.raises(TypeError):
mmcv.dump(test_obj, 'tmp.txt')
import mmcv
import pytest
def test_iter_cast():
assert mmcv.list_cast([1, 2, 3], int) == [1, 2, 3]
assert mmcv.list_cast(['1.1', 2, '3'], float) == [1.1, 2.0, 3.0]
assert mmcv.list_cast([1, 2, 3], str) == ['1', '2', '3']
assert mmcv.tuple_cast((1, 2, 3), str) == ('1', '2', '3')
assert next(mmcv.iter_cast([1, 2, 3], str)) == '1'
with pytest.raises(TypeError):
mmcv.iter_cast([1, 2, 3], '')
with pytest.raises(TypeError):
mmcv.iter_cast(1, str)
def test_is_seq_of():
assert mmcv.is_seq_of([1.0, 2.0, 3.0], float)
assert mmcv.is_seq_of([(1, ), (2, ), (3, )], tuple)
assert mmcv.is_seq_of((1.0, 2.0, 3.0), float)
assert mmcv.is_list_of([1.0, 2.0, 3.0], float)
assert not mmcv.is_seq_of((1.0, 2.0, 3.0), float, seq_type=list)
assert not mmcv.is_tuple_of([1.0, 2.0, 3.0], float)
assert not mmcv.is_seq_of([1.0, 2, 3], int)
assert not mmcv.is_seq_of((1.0, 2, 3), int)
def test_slice_list():
in_list = [1, 2, 3, 4, 5, 6]
assert mmcv.slice_list(in_list, [1, 2, 3]) == [[1], [2, 3], [4, 5, 6]]
assert mmcv.slice_list(in_list, [len(in_list)]) == [in_list]
with pytest.raises(TypeError):
mmcv.slice_list(in_list, 2.0)
with pytest.raises(ValueError):
mmcv.slice_list(in_list, [1, 2])
def test_concat_list():
assert mmcv.concat_list([[1, 2]]) == [1, 2]
assert mmcv.concat_list([[1, 2], [3, 4, 5], [6]]) == [1, 2, 3, 4, 5, 6]
def test_requires_package(capsys):
@mmcv.requires_package('nnn')
def func_a():
pass
@mmcv.requires_package(['numpy', 'n1', 'n2'])
def func_b():
pass
@mmcv.requires_package('six')
def func_c():
return 1
with pytest.raises(RuntimeError):
func_a()
out, _ = capsys.readouterr()
assert out == ('Prerequisites "nnn" are required in method "func_a" but '
'not found, please install them first.\n')
with pytest.raises(RuntimeError):
func_b()
out, _ = capsys.readouterr()
assert out == (
'Prerequisites "n1, n2" are required in method "func_b" but not found,'
' please install them first.\n')
assert func_c() == 1
def test_requires_executable(capsys):
@mmcv.requires_executable('nnn')
def func_a():
pass
@mmcv.requires_executable(['ls', 'n1', 'n2'])
def func_b():
pass
@mmcv.requires_executable('mv')
def func_c():
return 1
with pytest.raises(RuntimeError):
func_a()
out, _ = capsys.readouterr()
assert out == ('Prerequisites "nnn" are required in method "func_a" but '
'not found, please install them first.\n')
with pytest.raises(RuntimeError):
func_b()
out, _ = capsys.readouterr()
assert out == (
'Prerequisites "n1, n2" are required in method "func_b" but not found,'
' please install them first.\n')
assert func_c() == 1
import os.path as osp
import sys
import mmcv
import pytest
def test_list_from_file():
filename = osp.join(osp.dirname(__file__), 'data/filelist.txt')
filelist = mmcv.list_from_file(filename)
assert filelist == ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg']
filelist = mmcv.list_from_file(filename, prefix='a/')
assert filelist == ['a/1.jpg', 'a/2.jpg', 'a/3.jpg', 'a/4.jpg', 'a/5.jpg']
filelist = mmcv.list_from_file(filename, offset=2)
assert filelist == ['3.jpg', '4.jpg', '5.jpg']
filelist = mmcv.list_from_file(filename, max_num=2)
assert filelist == ['1.jpg', '2.jpg']
filelist = mmcv.list_from_file(filename, offset=3, max_num=3)
assert filelist == ['4.jpg', '5.jpg']
def test_dict_from_file():
filename = osp.join(osp.dirname(__file__), 'data/mapping.txt')
mapping = mmcv.dict_from_file(filename)
assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
mapping = mmcv.dict_from_file(filename, key_type=int)
assert mapping == {1: 'cat', 2: ['dog', 'cow'], 3: 'panda'}
def test_check_file_exist():
mmcv.check_file_exist(__file__)
if sys.version_info > (3, 3):
with pytest.raises(FileNotFoundError):
mmcv.check_file_exist('no_such_file.txt')
else:
with pytest.raises(IOError):
mmcv.check_file_exist('no_such_file.txt')
def test_scandir():
folder = osp.join(osp.dirname(__file__), 'data/for_scan')
filenames = ['a.bin', '1.txt', '2.txt', '1.json', '2.json']
assert set(mmcv.scandir(folder)) == set(filenames)
assert set(mmcv.scandir(folder, '.txt')) == set(
[filename for filename in filenames if filename.endswith('.txt')])
assert set(mmcv.scandir(folder, ('.json', '.txt'))) == set([
filename for filename in filenames
if filename.endswith(('.txt', '.json'))
])
assert set(mmcv.scandir(folder, '.png')) == set()
with pytest.raises(TypeError):
mmcv.scandir(folder, 111)
import time
import mmcv
class TestProgressBar(object):
def test_start(self, capsys):
bar_width = 20
# without total task num
prog_bar = mmcv.ProgressBar(bar_width=bar_width)
out, _ = capsys.readouterr()
assert out == 'completed: 0, elapsed: 0s'
prog_bar = mmcv.ProgressBar(bar_width=bar_width, start=False)
out, _ = capsys.readouterr()
assert out == ''
prog_bar.start()
out, _ = capsys.readouterr()
assert out == 'completed: 0, elapsed: 0s'
# with total task num
prog_bar = mmcv.ProgressBar(10, bar_width=bar_width)
out, _ = capsys.readouterr()
assert out == '[{}] 0/10, elapsed: 0s, ETA:'.format(' ' * bar_width)
prog_bar = mmcv.ProgressBar(10, bar_width=bar_width, start=False)
out, _ = capsys.readouterr()
assert out == ''
prog_bar.start()
out, _ = capsys.readouterr()
assert out == '[{}] 0/10, elapsed: 0s, ETA:'.format(' ' * bar_width)
def test_update(self, capsys):
bar_width = 20
# without total task num
prog_bar = mmcv.ProgressBar(bar_width=bar_width)
capsys.readouterr()
time.sleep(1)
prog_bar.update()
out, _ = capsys.readouterr()
assert out == 'completed: 1, elapsed: 1s, 1.0 tasks/s'
# with total task num
prog_bar = mmcv.ProgressBar(10, bar_width=bar_width)
capsys.readouterr()
time.sleep(1)
prog_bar.update()
out, _ = capsys.readouterr()
assert out == ('\r[{}] 1/10, 1.0 task/s, elapsed: 1s, ETA: 9s'.
format('>' * 2 + ' ' * 18))
def sleep_1s(num):
time.sleep(1)
return num
def test_track_progress_list(capsys):
ret = mmcv.track_progress(sleep_1s, [1, 2, 3], bar_width=3)
out, _ = capsys.readouterr()
assert out == ('[ ] 0/3, elapsed: 0s, ETA:'
'\r[> ] 1/3, 1.0 task/s, elapsed: 1s, ETA: 2s'
'\r[>> ] 2/3, 1.0 task/s, elapsed: 2s, ETA: 1s'
'\r[>>>] 3/3, 1.0 task/s, elapsed: 3s, ETA: 0s\n')
assert ret == [1, 2, 3]
def test_track_progress_iterator(capsys):
ret = mmcv.track_progress(
sleep_1s, ((i for i in [1, 2, 3]), 3), bar_width=3)
out, _ = capsys.readouterr()
assert out == ('[ ] 0/3, elapsed: 0s, ETA:'
'\r[> ] 1/3, 1.0 task/s, elapsed: 1s, ETA: 2s'
'\r[>> ] 2/3, 1.0 task/s, elapsed: 2s, ETA: 1s'
'\r[>>>] 3/3, 1.0 task/s, elapsed: 3s, ETA: 0s\n')
assert ret == [1, 2, 3]
def test_track_parallel_progress_list(capsys):
results = mmcv.track_parallel_progress(
sleep_1s, [1, 2, 3, 4], 2, bar_width=4)
out, _ = capsys.readouterr()
assert out == ('[ ] 0/4, elapsed: 0s, ETA:'
'\r[> ] 1/4, 1.0 task/s, elapsed: 1s, ETA: 3s'
'\r[>> ] 2/4, 2.0 task/s, elapsed: 1s, ETA: 1s'
'\r[>>> ] 3/4, 1.5 task/s, elapsed: 2s, ETA: 1s'
'\r[>>>>] 4/4, 2.0 task/s, elapsed: 2s, ETA: 0s\n')
assert results == [1, 2, 3, 4]
def test_track_parallel_progress_iterator(capsys):
results = mmcv.track_parallel_progress(
sleep_1s, ((i for i in [1, 2, 3, 4]), 4), 2, bar_width=4)
out, _ = capsys.readouterr()
assert out == ('[ ] 0/4, elapsed: 0s, ETA:'
'\r[> ] 1/4, 1.0 task/s, elapsed: 1s, ETA: 3s'
'\r[>> ] 2/4, 2.0 task/s, elapsed: 1s, ETA: 1s'
'\r[>>> ] 3/4, 1.5 task/s, elapsed: 2s, ETA: 1s'
'\r[>>>>] 4/4, 2.0 task/s, elapsed: 2s, ETA: 0s\n')
assert results == [1, 2, 3, 4]
import time
import mmcv
import pytest
def test_timer_init():
timer = mmcv.Timer(start=False)
assert not timer.is_running
timer.start()
assert timer.is_running
timer = mmcv.Timer()
assert timer.is_running
def test_timer_run():
timer = mmcv.Timer()
time.sleep(1)
assert abs(timer.since_start() - 1) < 1e-2
time.sleep(1)
assert abs(timer.since_last_check() - 1) < 1e-2
assert abs(timer.since_start() - 2) < 1e-2
timer = mmcv.Timer(False)
with pytest.raises(mmcv.TimerError):
timer.since_start()
with pytest.raises(mmcv.TimerError):
timer.since_last_check()
def test_timer_context(capsys):
with mmcv.Timer():
time.sleep(1)
out, _ = capsys.readouterr()
assert abs(float(out) - 1) < 1e-2
with mmcv.Timer(print_tmpl='time: {:.1f}s'):
time.sleep(1)
out, _ = capsys.readouterr()
assert out == 'time: 1.0s\n'
import os
import os.path as osp
import tempfile
from collections import OrderedDict
import mmcv
import pytest
class TestCache(object):
def test_init(self):
with pytest.raises(ValueError):
mmcv.Cache(0)
cache = mmcv.Cache(100)
assert cache.capacity == 100
assert cache.size == 0
def test_put(self):
cache = mmcv.Cache(3)
for i in range(1, 4):
cache.put('k{}'.format(i), i)
assert cache.size == i
assert cache._cache == OrderedDict([('k1', 1), ('k2', 2), ('k3', 3)])
cache.put('k4', 4)
assert cache.size == 3
assert cache._cache == OrderedDict([('k2', 2), ('k3', 3), ('k4', 4)])
cache.put('k2', 2)
assert cache._cache == OrderedDict([('k2', 2), ('k3', 3), ('k4', 4)])
def test_get(self):
cache = mmcv.Cache(3)
assert cache.get('key_none') is None
assert cache.get('key_none', 0) == 0
cache.put('k1', 1)
assert cache.get('k1') == 1
class TestVideo(object):
@classmethod
def setup_class(cls):
cls.video_path = osp.join(osp.dirname(__file__), 'data/test.mp4')
cls.num_frames = 168
def test_load(self):
v = mmcv.VideoReader(self.video_path)
assert v.width == 294
assert v.height == 240
assert v.fps == 25
assert v.frame_cnt == self.num_frames
assert len(v) == self.num_frames
assert v.opened
import cv2
assert isinstance(v.vcap, type(cv2.VideoCapture()))
def test_read(self):
v = mmcv.VideoReader(self.video_path)
img = v.read()
assert int(round(img.mean())) == 94
img = v.get_frame(64)
assert int(round(img.mean())) == 94
img = v[65]
assert int(round(img.mean())) == 205
img = v[64]
assert int(round(img.mean())) == 94
img = v.read()
assert int(round(img.mean())) == 205
with pytest.raises(ValueError):
v.get_frame(self.num_frames + 1)
def test_current_frame(self):
v = mmcv.VideoReader(self.video_path)
assert v.current_frame() is None
v.read()
img = v.current_frame()
assert int(round(img.mean())) == 94
def test_position(self):
v = mmcv.VideoReader(self.video_path)
assert v.position == 0
for _ in range(10):
v.read()
assert v.position == 10
v.get_frame(100)
assert v.position == 100
def test_iterator(self):
cnt = 0
for img in mmcv.VideoReader(self.video_path):
cnt += 1
assert img.shape == (240, 294, 3)
assert cnt == self.num_frames
def test_with(self):
with mmcv.VideoReader(self.video_path) as v:
assert v.opened
assert not v.opened
def test_cvt2frames(self):
v = mmcv.VideoReader(self.video_path)
frame_dir = tempfile.mkdtemp()
v.cvt2frames(frame_dir)
assert osp.isdir(frame_dir)
for i in range(self.num_frames):
filename = '{}/{:06d}.jpg'.format(frame_dir, i)
assert osp.isfile(filename)
os.remove(filename)
v = mmcv.VideoReader(self.video_path)
v.cvt2frames(frame_dir, show_progress=False)
assert osp.isdir(frame_dir)
for i in range(self.num_frames):
filename = '{}/{:06d}.jpg'.format(frame_dir, i)
assert osp.isfile(filename)
os.remove(filename)
v = mmcv.VideoReader(self.video_path)
v.cvt2frames(
frame_dir,
file_start=100,
filename_tmpl='{:03d}.JPEG',
start=100,
max_num=20)
assert osp.isdir(frame_dir)
for i in range(100, 120):
filename = '{}/{:03d}.JPEG'.format(frame_dir, i)
assert osp.isfile(filename)
os.remove(filename)
os.removedirs(frame_dir)
def test_frames2video(self):
v = mmcv.VideoReader(self.video_path)
frame_dir = tempfile.mkdtemp()
v.cvt2frames(frame_dir)
assert osp.isdir(frame_dir)
for i in range(self.num_frames):
filename = '{}/{:06d}.jpg'.format(frame_dir, i)
assert osp.isfile(filename)
out_filename = osp.join(tempfile.gettempdir(), 'mmcv_test.avi')
mmcv.frames2video(frame_dir, out_filename)
v = mmcv.VideoReader(out_filename)
assert v.fps == 30
assert len(v) == self.num_frames
mmcv.frames2video(
frame_dir,
out_filename,
fps=25,
start=10,
end=50,
show_progress=False)
v = mmcv.VideoReader(out_filename)
assert v.fps == 25
assert len(v) == 40
for i in range(self.num_frames):
filename = '{}/{:06d}.jpg'.format(frame_dir, i)
os.remove(filename)
os.removedirs(frame_dir)
os.remove(out_filename)
def test_cut_concat_video(self):
part1_file = osp.join(tempfile.gettempdir(), '.mmcv_test1.mp4')
part2_file = osp.join(tempfile.gettempdir(), '.mmcv_test2.mp4')
mmcv.cut_video(self.video_path, part1_file, end=3, vcodec='h264')
mmcv.cut_video(self.video_path, part2_file, start=3, vcodec='h264')
v1 = mmcv.VideoReader(part1_file)
v2 = mmcv.VideoReader(part2_file)
assert len(v1) == 75
assert len(v2) == self.num_frames - 75
out_file = osp.join(tempfile.gettempdir(), '.mmcv_test.mp4')
mmcv.concat_video([part1_file, part2_file], out_file)
v = mmcv.VideoReader(out_file)
assert len(v) == self.num_frames
os.remove(part1_file)
os.remove(part2_file)
os.remove(out_file)
def test_resize_video(self):
out_file = osp.join(tempfile.gettempdir(), '.mmcv_test.mp4')
mmcv.resize_video(self.video_path, out_file, (200, 100), quiet=True)
v = mmcv.VideoReader(out_file)
assert v.resolution == (200, 100)
os.remove(out_file)
mmcv.resize_video(self.video_path, out_file, ratio=2)
v = mmcv.VideoReader(out_file)
assert v.resolution == (294 * 2, 240 * 2)
os.remove(out_file)
mmcv.resize_video(self.video_path, out_file, (1000, 480), keep_ar=True)
v = mmcv.VideoReader(out_file)
assert v.resolution == (294 * 2, 240 * 2)
os.remove(out_file)
mmcv.resize_video(
self.video_path, out_file, ratio=(2, 1.5), keep_ar=True)
v = mmcv.VideoReader(out_file)
assert v.resolution == (294 * 2, 360)
os.remove(out_file)
import mmcv
import numpy as np
import pytest
def test_color():
assert mmcv.color_val(mmcv.Color.blue) == (255, 0, 0)
assert mmcv.color_val('green') == (0, 255, 0)
assert mmcv.color_val((1, 2, 3)) == (1, 2, 3)
assert mmcv.color_val(100) == (100, 100, 100)
assert mmcv.color_val(np.zeros(3, dtype=np.int)) == (0, 0, 0)
with pytest.raises(TypeError):
mmcv.color_val([255, 255, 255])
with pytest.raises(TypeError):
mmcv.color_val(1.0)
with pytest.raises(AssertionError):
mmcv.color_val((0, 0, 500))
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