Skip to content

Commit

Permalink
transforms/loading: support reading numpy files (.npy, .npz)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonGuti13 committed Oct 5, 2023
1 parent f2439cd commit f6865bd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
11 changes: 9 additions & 2 deletions docs/en/understand_mmcv/data_process.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

### Image

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

#### Read/Write/Show

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

```python
import mmcv
Expand All @@ -17,6 +17,13 @@ img_ = mmcv.imread(img) # nothing will happen, img_ = img
mmcv.imwrite(img, 'out.jpg')
```

```python
import numpy as np

img = np.load('test.npy')
np.save('test.npy', img)
```

To read images from bytes

```python
Expand Down
24 changes: 16 additions & 8 deletions mmcv/transforms/loading.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
from pathlib import Path
from typing import Optional

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

filename = results['img_path']

try:
if self.file_client_args is not None:
file_client = fileio.FileClient.infer_client(
self.file_client_args, filename)
img_bytes = file_client.get(filename)
if Path(filename).suffix in ['.npy', '.npz']:
img = np.load(filename)
else:
img_bytes = fileio.get(
filename, backend_args=self.backend_args)
img = mmcv.imfrombytes(
img_bytes, flag=self.color_type, backend=self.imdecode_backend)
if self.file_client_args is not None:
file_client = fileio.FileClient.infer_client(
self.file_client_args, filename)
img_bytes = file_client.get(filename)
else:
img_bytes = fileio.get(
filename, backend_args=self.backend_args)
img = mmcv.imfrombytes(
img_bytes,
flag=self.color_type,
backend=self.imdecode_backend)
except Exception as e:
if self.ignore_empty:
return None
else:
raise e

# in some cases, images are not read successfully, the img would be
# `None`, refer to https://github.com/open-mmlab/mmpretrain/issues/1427
assert img is not None, f'failed to load image: {filename}'
Expand Down

0 comments on commit f6865bd

Please sign in to comment.