Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

transforms/loading: support reading numpy files (.npy, .npz) #2950

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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