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

Support torch tensors #7

Merged
merged 7 commits into from
Mar 10, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
37 changes: 27 additions & 10 deletions imgcat/imgcat.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,21 @@ def to_content_buf(data):
else:
raise ValueError("Expected a 3D ndarray (RGB/RGBA image) or 2D (grayscale image), "
"but given shape: {}".format(im.shape))
return _get_bytes_from_numpy(im, mode)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit

try:
from PIL import Image
except ImportError as e:
raise ImportError(e.msg +
"\nTo draw numpy arrays, we require Pillow. " +
"(pip install Pillow)") # TODO; reraise

with io.BytesIO() as buf:
Image.fromarray(im, mode=mode).save(buf, format='png')
return buf.getvalue()
elif 'torch' in sys.modules and isinstance(data, sys.modules['torch'].Tensor):
# numpy ndarray: convert to png
im = data
if im.shape[0] == 1:
mode = 'L' # 8-bit pixels, grayscale
im = im.mul(255).byte().squeeze().numpy()
elif im.shape[0] == 3:
mode = None # RGB/RGBA
im = im.mul(255).byte().permute(1, 2, 0).numpy()
Copy link
Owner

@wookayin wookayin Feb 20, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One should not assume anything about RGB/BGR order and datatype (uint8 or float). But why don't we just do im.numpy()?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm, You are right.
fix use torchvision.

else:
raise ValueError("Expected a 3D ndarray (RGB/RGBA image) or 2D (grayscale image), "
"but given shape: {}".format(im.shape))
return _get_bytes_from_numpy(im, mode)

elif 'PIL.Image' in sys.modules and isinstance(data, sys.modules['PIL.Image'].Image):
# PIL/Pillow images
Expand Down Expand Up @@ -288,5 +292,18 @@ def main():
return 0


def _get_bytes_from_numpy(im, mode):
try:
from PIL import Image
except ImportError as e:
raise ImportError(e.msg +
"\nTo draw numpy arrays, we require Pillow. " +
"(pip install Pillow)") # TODO; reraise

with io.BytesIO() as buf:
Image.fromarray(im, mode=mode).save(buf, format='png')
return buf.getvalue()


if __name__ == '__main__':
sys.exit(main())
13 changes: 13 additions & 0 deletions imgcat/test_imgcat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import unittest
import numpy as np
import torch
import sys
import os
import io
Expand Down Expand Up @@ -41,6 +42,18 @@ def test_numpy(self):
a[:, :, 0] = 255 # (255, 0, 0): red
imgcat(a)

def test_torch(self):
# uint8, grayscale
a = torch.ones([1, 32, 32], dtype=torch.uint8)
imgcat(a)

a = torch.ones([1, 32, 32], dtype=torch.float32)
imgcat(a)

# uint8, color image
a = torch.ones([3, 32, 32], dtype=torch.uint8) * 0
imgcat(a)

def test_matplotlib(self):
# plt
import matplotlib.pyplot as plt
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def read_version():
tests_requires = [
'pytest<5.0',
'numpy',
'torch',
]
if sys.version_info >= (3, 6):
tests_requires += ['matplotlib>=3.1', 'Pillow']
Expand Down