Merge pull request #260 from ahojnnes/convert-bool

ENH: Support for boolean dtype conversion.
This commit is contained in:
Stefan van der Walt
2012-08-24 17:56:28 -07:00
2 changed files with 49 additions and 4 deletions
+34 -3
View File
@@ -1,12 +1,15 @@
from __future__ import division
import numpy as np
__all__ = ['img_as_float', 'img_as_int', 'img_as_uint', 'img_as_ubyte']
__all__ = ['img_as_float', 'img_as_int', 'img_as_uint', 'img_as_ubyte',
'img_as_bool']
from .. import get_log
log = get_log('dtype_converter')
dtype_range = {np.uint8: (0, 255),
dtype_range = {np.bool_: (False, True),
np.bool8: (False, True),
np.uint8: (0, 255),
np.uint16: (0, 65535),
np.int8: (-128, 127),
np.int16: (-32768, 32767),
@@ -15,7 +18,8 @@ dtype_range = {np.uint8: (0, 255),
integer_types = (np.uint8, np.uint16, np.int8, np.int16)
_supported_types = (np.uint8, np.uint16, np.uint32,
_supported_types = (np.bool_, np.bool8,
np.uint8, np.uint16, np.uint32,
np.int8, np.int16, np.int32,
np.float32, np.float64)
@@ -145,6 +149,10 @@ def convert(image, dtype, force_copy=False, uniform=False):
kind_in = dtypeobj_in.kind
itemsize = dtypeobj.itemsize
itemsize_in = dtypeobj_in.itemsize
if kind == 'b' or kind_in == 'b':
return dtype(image)
if kind in 'ui':
imin = np.iinfo(dtype).min
imax = np.iinfo(dtype).max
@@ -322,3 +330,26 @@ def img_as_ubyte(image, force_copy=False):
"""
return convert(image, np.uint8, force_copy)
def img_as_bool(image, force_copy=False):
"""Convert an image to boolean format.
Parameters
----------
image : ndarray
Input image.
force_copy : bool
Force a copy of the data, irrespective of its current dtype.
Returns
-------
out : ndarray of bool (bool_)
Output image.
Notes
-----
All non-zero elements are treated as True.
"""
return convert(image, np.bool_, force_copy)
+15 -1
View File
@@ -1,7 +1,7 @@
import numpy as np
from numpy.testing import assert_equal, assert_raises
from skimage import img_as_int, img_as_float, \
img_as_uint, img_as_ubyte
img_as_uint, img_as_ubyte, img_as_bool
from skimage.util.dtype import convert
@@ -86,5 +86,19 @@ def test_copy():
assert y is x
assert z is not x
def test_bool():
img_ = np.zeros((10, 10), np.bool_)
img8 = np.zeros((10, 10), np.bool8)
img_[1, 1] = True
img8[1, 1] = True
funcs = (img_as_float, img_as_int, img_as_ubyte, img_as_uint, img_as_bool)
for func in funcs:
converted_ = func(img_)
assert np.sum(converted_) == 1
converted8 = func(img8)
assert np.sum(converted8) == 1
if __name__ == '__main__':
np.testing.run_module_suite()