本文整理匯總了Python中mmcv.imread方法的典型用法代碼示例。如果您正苦於以下問題:Python mmcv.imread方法的具體用法?Python mmcv.imread怎麽用?Python mmcv.imread使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類mmcv
的用法示例。
在下文中一共展示了mmcv.imread方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __call__
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def __call__(self, results):
"""Call function to load images into results.
Args:
results (dict): A result dict contains the file name
of the image to be read.
Returns:
dict: ``results`` will be returned containing loaded image.
"""
if isinstance(results['img'], str):
results['filename'] = results['img']
results['ori_filename'] = results['img']
else:
results['filename'] = None
results['ori_filename'] = None
img = mmcv.imread(results['img'])
results['img'] = img
results['img_fields'] = ['img']
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
return results
示例2: test_flowwrite
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def test_flowwrite():
flow = np.random.rand(100, 100, 2).astype(np.float32)
# write to a .flo file
_, filename = tempfile.mkstemp()
mmcv.flowwrite(flow, filename)
flow_from_file = mmcv.flowread(filename)
assert_array_equal(flow, flow_from_file)
os.remove(filename)
# write to two .jpg files
tmp_filename = osp.join(tempfile.gettempdir(), 'mmcv_test_flow.jpg')
for concat_axis in range(2):
mmcv.flowwrite(
flow, tmp_filename, quantize=True, concat_axis=concat_axis)
shape = (200, 100) if concat_axis == 0 else (100, 200)
assert osp.isfile(tmp_filename)
assert mmcv.imread(tmp_filename, flag='unchanged').shape == shape
os.remove(tmp_filename)
# test exceptions
with pytest.raises(AssertionError):
mmcv.flowwrite(flow, tmp_filename, quantize=True, concat_axis=2)
示例3: test_flip
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def test_flip():
# test assertion for invalid flip_ratio
with pytest.raises(AssertionError):
transform = dict(type='RandomFlip', flip_ratio=1.5)
build_from_cfg(transform, PIPELINES)
# test assertion for invalid direction
with pytest.raises(AssertionError):
transform = dict(
type='RandomFlip', flip_ratio=1, direction='horizonta')
build_from_cfg(transform, PIPELINES)
transform = dict(type='RandomFlip', flip_ratio=1)
flip_module = build_from_cfg(transform, PIPELINES)
results = dict()
img = mmcv.imread(
osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
original_img = copy.deepcopy(img)
results['img'] = img
results['img2'] = copy.deepcopy(img)
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
# Set initial values for default meta_keys
results['pad_shape'] = img.shape
results['scale_factor'] = 1.0
results['img_fields'] = ['img', 'img2']
results = flip_module(results)
assert np.equal(results['img'], results['img2']).all()
flip_module = build_from_cfg(transform, PIPELINES)
results = flip_module(results)
assert np.equal(results['img'], results['img2']).all()
assert np.equal(original_img, results['img']).all()
示例4: test_pad
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def test_pad():
# test assertion if both size_divisor and size is None
with pytest.raises(AssertionError):
transform = dict(type='Pad')
build_from_cfg(transform, PIPELINES)
transform = dict(type='Pad', size_divisor=32)
transform = build_from_cfg(transform, PIPELINES)
results = dict()
img = mmcv.imread(
osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
original_img = copy.deepcopy(img)
results['img'] = img
results['img2'] = copy.deepcopy(img)
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
# Set initial values for default meta_keys
results['pad_shape'] = img.shape
results['scale_factor'] = 1.0
results['img_fields'] = ['img', 'img2']
results = transform(results)
assert np.equal(results['img'], results['img2']).all()
# original img already divisible by 32
assert np.equal(results['img'], original_img).all()
img_shape = results['img'].shape
assert img_shape[0] % 32 == 0
assert img_shape[1] % 32 == 0
resize_transform = dict(
type='Resize', img_scale=(1333, 800), keep_ratio=True)
resize_module = build_from_cfg(resize_transform, PIPELINES)
results = resize_module(results)
results = transform(results)
img_shape = results['img'].shape
assert np.equal(results['img'], results['img2']).all()
assert img_shape[0] % 32 == 0
assert img_shape[1] % 32 == 0
示例5: apredict
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def apredict(self, img):
if isinstance(img, str):
img = mmcv.imread(img)
async with concurrent(self.streamqueue):
result = await async_inference_detector(self.model, img)
return result
示例6: inference_single
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def inference_single(self, imagname, slide_size, chip_size):
img = mmcv.imread(imagname)
height, width, channel = img.shape
slide_h, slide_w = slide_size
hn, wn = chip_size
# TODO: check the corner case
# import pdb; pdb.set_trace()
total_detections = [np.zeros((0, 9)) for _ in range(len(self.classnames))]
for i in tqdm(range(int(width / slide_w + 1))):
for j in range(int(height / slide_h) + 1):
subimg = np.zeros((hn, wn, channel))
# print('i: ', i, 'j: ', j)
chip = img[j*slide_h:j*slide_h + hn, i*slide_w:i*slide_w + wn, :3]
subimg[:chip.shape[0], :chip.shape[1], :] = chip
chip_detections = inference_detector(self.model, subimg)
# print('result: ', result)
for cls_id, name in enumerate(self.classnames):
chip_detections[cls_id][:, :8][:, ::2] = chip_detections[cls_id][:, :8][:, ::2] + i * slide_w
chip_detections[cls_id][:, :8][:, 1::2] = chip_detections[cls_id][:, :8][:, 1::2] + j * slide_h
# import pdb;pdb.set_trace()
try:
total_detections[cls_id] = np.concatenate((total_detections[cls_id], chip_detections[cls_id]))
except:
import pdb; pdb.set_trace()
# nms
for i in range(len(self.classnames)):
keep = py_cpu_nms_poly_fast_np(total_detections[i], 0.1)
total_detections[i] = total_detections[i][keep]
return total_detections
示例7: _inference_single
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def _inference_single(model, img, img_transform, device):
img = mmcv.imread(img)
data = _prepare_data(img, img_transform, model.cfg, device)
with torch.no_grad():
result = model(return_loss=False, rescale=True, **data)
return result
示例8: show_result
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def show_result(img, result, class_names, score_thr=0.3, out_file=None):
"""Visualize the detection results on the image.
Args:
img (str or np.ndarray): Image filename or loaded image.
result (tuple[list] or list): The detection result, can be either
(bbox, segm) or just bbox.
class_names (list[str] or tuple[str]): A list of class names.
score_thr (float): The threshold to visualize the bboxes and masks.
out_file (str, optional): If specified, the visualization result will
be written to the out file instead of shown in a window.
"""
assert isinstance(class_names, (tuple, list))
img = mmcv.imread(img)
if isinstance(result, tuple):
bbox_result, segm_result = result
else:
bbox_result, segm_result = result, None
bboxes = np.vstack(bbox_result)
# draw segmentation masks
if segm_result is not None:
segms = mmcv.concat_list(segm_result)
inds = np.where(bboxes[:, -1] > score_thr)[0]
for i in inds:
color_mask = np.random.randint(0, 256, (1, 3), dtype=np.uint8)
mask = maskUtils.decode(segms[i]).astype(np.bool)
img[mask] = img[mask] * 0.5 + color_mask * 0.5
# draw bounding boxes
labels = [
np.full(bbox.shape[0], i, dtype=np.int32)
for i, bbox in enumerate(bbox_result)
]
labels = np.concatenate(labels)
mmcv.imshow_det_bboxes(
img.copy(),
bboxes,
labels,
class_names=class_names,
score_thr=score_thr,
show=out_file is None,
out_file=out_file)
示例9: draw_poly_detections
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def draw_poly_detections(img, detections, class_names, scale, threshold=0.2):
"""
:param img:
:param detections:
:param class_names:
:param scale:
:param cfg:
:param threshold:
:return:
"""
import pdb
import cv2
import random
assert isinstance(class_names, (tuple, list))
img = mmcv.imread(img)
color_white = (255, 255, 255)
for j, name in enumerate(class_names):
color = (random.randint(0, 256), random.randint(0, 256), random.randint(0, 256))
try:
dets = detections[j]
except:
pdb.set_trace()
for det in dets:
bbox = det[:8] * scale
score = det[-1]
if score < threshold:
continue
bbox = list(map(int, bbox))
cv2.circle(img, (bbox[0], bbox[1]), 3, (0, 0, 255), -1)
for i in range(3):
cv2.line(img, (bbox[i * 2], bbox[i * 2 + 1]), (bbox[(i+1) * 2], bbox[(i+1) * 2 + 1]), color=color, thickness=2)
cv2.line(img, (bbox[6], bbox[7]), (bbox[0], bbox[1]), color=color, thickness=2)
cv2.putText(img, '%s %.3f' % (class_names[j], score), (bbox[0], bbox[1] + 10),
color=color_white, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=0.5)
return img
示例10: __call__
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def __call__(self, results):
if isinstance(results['img'], str):
results['filename'] = results['img']
else:
results['filename'] = None
img = mmcv.imread(results['img'])
results['img'] = img
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
return results
示例11: setup_class
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def setup_class(cls):
cls.data_dir = osp.join(osp.dirname(__file__), '../data')
# the test img resolution is 400x300
cls.img_path = osp.join(cls.data_dir, 'color.jpg')
cls.img_path_obj = Path(cls.img_path)
cls.gray_img_path = osp.join(cls.data_dir, 'grayscale.jpg')
cls.gray_img_path_obj = Path(cls.gray_img_path)
cls.gray_img_dim3_path = osp.join(cls.data_dir, 'grayscale_dim3.jpg')
cls.gray_alpha_img_path = osp.join(cls.data_dir, 'gray_alpha.png')
cls.palette_img_path = osp.join(cls.data_dir, 'palette.gif')
cls.img = cv2.imread(cls.img_path)
示例12: test_imwrite
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def test_imwrite(self):
img = mmcv.imread(self.img_path)
out_file = osp.join(tempfile.gettempdir(), 'mmcv_test.jpg')
mmcv.imwrite(img, out_file)
rewrite_img = mmcv.imread(out_file)
os.remove(out_file)
self.assert_img_equal(img, rewrite_img)
ret = mmcv.imwrite(
img, './non_exist_path/mmcv_test.jpg', auto_mkdir=False)
assert ret is False
示例13: __call__
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def __call__(self, results):
filename = osp.join(results['img_prefix'],
results['img_info']['filename'])
img = mmcv.imread(filename)
if self.to_float32:
img = img.astype(np.float32)
results['filename'] = filename
results['img'] = img
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
return results
示例14: _load_semantic_seg
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def _load_semantic_seg(self, results):
results['gt_semantic_seg'] = mmcv.imread(
osp.join(results['seg_prefix'], results['ann_info']['seg_map']),
flag='unchanged').squeeze()
return results
示例15: __call__
# 需要導入模塊: import mmcv [as 別名]
# 或者: from mmcv import imread [as 別名]
def __call__(self, results):
if results['img_prefix'] is not None:
filename = osp.join(results['img_prefix'],
results['img_info']['filename'])
else:
filename = results['img_info']['filename']
img = mmcv.imread(filename)
if self.to_float32:
img = img.astype(np.float32)
results['filename'] = filename
results['img'] = img
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
return results