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

Fixup numpy #21

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
8 changes: 3 additions & 5 deletions imgcat/imgcat.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,23 +98,21 @@ def to_content_buf(data: Any) -> bytes:
# numpy ndarray: convert to png
import numpy
im: 'numpy.ndarray' = data
if im.dtype.kind == 'f':
# https://stackoverflow.com/a/66862750
im = (im * 256).clip(0, 255).astype('uint8')
if len(im.shape) == 2:
mode = 'L' # 8-bit pixels, grayscale
im = im.astype(sys.modules['numpy'].uint8)
elif len(im.shape) == 3 and im.shape[2] in (1, 3, 4):
# (H, W, C) format
mode = None # RGB/RGBA
if im.dtype.kind == 'f':
im = (im * 255).astype('uint8')
if im.shape[2] == 1:
mode = 'L' # 8-bit grayscale
im = numpy.squeeze(im, axis=2)
elif len(im.shape) == 3 and im.shape[0] in (1, 3, 4):
# (C, H, W) format
mode = None # RGB/RGBA
im = numpy.rollaxis(im, 0, 3) # CHW -> HWC
if im.dtype.kind == 'f':
im = (im * 255).astype('uint8')
if im.shape[2] == 1:
mode = 'L' # 8-bit grayscale
im = numpy.squeeze(im, axis=2)
Expand Down