From 0b7df2626a8bdec47013d40c5f91088b8b391313 Mon Sep 17 00:00:00 2001 From: Stefan van der Walt Date: Tue, 27 Sep 2011 01:16:35 -0700 Subject: [PATCH] ENH: Add img_as_ubyte. --- scikits/image/util/__init__.py | 2 ++ scikits/image/util/dtype.py | 24 +++++++++++++++++++++++- scikits/image/util/tests/test_dtype.py | 6 ++++-- 3 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 scikits/image/util/__init__.py diff --git a/scikits/image/util/__init__.py b/scikits/image/util/__init__.py new file mode 100644 index 00000000..6eb4da1c --- /dev/null +++ b/scikits/image/util/__init__.py @@ -0,0 +1,2 @@ +from dtype import * + diff --git a/scikits/image/util/dtype.py b/scikits/image/util/dtype.py index 8a690689..7e86892a 100644 --- a/scikits/image/util/dtype.py +++ b/scikits/image/util/dtype.py @@ -1,7 +1,7 @@ from __future__ import division import numpy as np -__all__ = ['img_as_float', 'img_as_int', 'img_as_uint'] +__all__ = ['img_as_float', 'img_as_int', 'img_as_uint', 'img_as_ubyte'] from .. import get_log log = get_log('dtype_converter') @@ -146,3 +146,25 @@ def img_as_int(image): """ prec_loss = (np.float32, np.float64, np.uint16) return _convert(image, np.int16, prec_loss) + +def img_as_ubyte(image): + """Convert an image to 8-bit unsigned integer format. + + Parameters + ---------- + image : ndarray + Input image. + + Returns + ------- + out : ndarray of ubyte (uint8) + Output image. + + Notes + ----- + If the input data-type is positive-only (e.g., uint16), then + the output image will still only have positive values. + + """ + prec_loss = (np.float32, np.float64, np.uint16, np.int16, np.int8) + return _convert(image, np.ubyte, prec_loss) diff --git a/scikits/image/util/tests/test_dtype.py b/scikits/image/util/tests/test_dtype.py index a3ef2377..d7cc3259 100644 --- a/scikits/image/util/tests/test_dtype.py +++ b/scikits/image/util/tests/test_dtype.py @@ -1,6 +1,7 @@ import numpy as np from numpy.testing import assert_equal -from scikits.image import img_as_int, img_as_float, img_as_uint +from scikits.image import img_as_int, img_as_float, \ + img_as_uint, img_as_ubyte dtype_range = {np.uint8: (0, 255), np.uint16: (0, 65535), @@ -20,7 +21,8 @@ def test_range(): for (f, dt) in [(img_as_int, np.int16), (img_as_float, np.float64), - (img_as_uint, np.uint16)]: + (img_as_uint, np.uint16), + (img_as_ubyte, np.ubyte)]: y = f(x) omin, omax = dtype_range[dt]