difference between arrays in numpy

Observe:

>>> import numpy as np
>>> a, b = np.random.randint(0, 255, (2, 10), dtype=np.uint8)
>>> a - b
array([ 62,  10, 126, 206, 157,  36, 170,  42,  54,   1], dtype=uint8)
>>> b - a
array([194, 246, 130,  50,  99, 220,  86, 214, 202, 255], dtype=uint8)

>>> a.astype(np.int) - b.astype(np.int)
array([  62, -246, -130,  -50,  -99,   36,  -86,   42,   54,    1])
>>> b.astype(np.int) - a.astype(np.int)
array([-62, 246, 130,  50,  99, -36,  86, -42, -54,  -1])

RGB images contain unsigned (nonnegative only) 8-bit integers, so all operations will return np.uint8:

>>> np.uint8(1) - np.uint8(5)
__main__:1: RuntimeWarning: overflow encountered in ubyte_scalars
252  # not -4
>>> np.int8(1) - np.int8(5)
-4

Leave a Comment