Skip to content

Commit f216eab

Browse files
committed
transforms/loading: support reading numpy files (.npy, .npz)
1 parent c7c02a7 commit f216eab

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

docs/en/understand_mmcv/data_process.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22

33
### Image
44

5-
This module provides some image processing methods, which requires `opencv` to be installed first.
5+
This module provides some image processing methods, which requires `opencv` and `numpy` to be installed first.
66

77
#### Read/Write/Show
88

9-
To read or write images files, use `imread` or `imwrite`.
9+
To read or write images files, use `imread` or `imwrite` with `opencv` and `load` or `save` with `numpy`.
1010

1111
```python
1212
import mmcv
@@ -17,6 +17,13 @@ img_ = mmcv.imread(img) # nothing will happen, img_ = img
1717
mmcv.imwrite(img, 'out.jpg')
1818
```
1919

20+
```python
21+
import numpy as np
22+
23+
img = np.load('test.npy')
24+
np.save('test.npy', img)
25+
```
26+
2027
To read images from bytes
2128

2229
```python

mmcv/transforms/loading.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Copyright (c) OpenMMLab. All rights reserved.
22
import warnings
3+
from pathlib import Path
34
from typing import Optional
45

56
import mmengine.fileio as fileio
@@ -90,21 +91,28 @@ def transform(self, results: dict) -> Optional[dict]:
9091
"""
9192

9293
filename = results['img_path']
94+
9395
try:
94-
if self.file_client_args is not None:
95-
file_client = fileio.FileClient.infer_client(
96-
self.file_client_args, filename)
97-
img_bytes = file_client.get(filename)
96+
if Path(filename).suffix in ['.npy', '.npz']:
97+
img = np.load(filename)
9898
else:
99-
img_bytes = fileio.get(
100-
filename, backend_args=self.backend_args)
101-
img = mmcv.imfrombytes(
102-
img_bytes, flag=self.color_type, backend=self.imdecode_backend)
99+
if self.file_client_args is not None:
100+
file_client = fileio.FileClient.infer_client(
101+
self.file_client_args, filename)
102+
img_bytes = file_client.get(filename)
103+
else:
104+
img_bytes = fileio.get(
105+
filename, backend_args=self.backend_args)
106+
img = mmcv.imfrombytes(
107+
img_bytes,
108+
flag=self.color_type,
109+
backend=self.imdecode_backend)
103110
except Exception as e:
104111
if self.ignore_empty:
105112
return None
106113
else:
107114
raise e
115+
108116
# in some cases, images are not read successfully, the img would be
109117
# `None`, refer to https://github.com/open-mmlab/mmpretrain/issues/1427
110118
assert img is not None, f'failed to load image: {filename}'

0 commit comments

Comments
 (0)