Dan Allan
Dan Allan

Reputation: 35255

Inverting numpy array image which might be uint8, uint16,

Is there a prettier way to do this? Specifically, are these max values available through the numpy API? I haven't been able to find them in the API, although they are easily found here in the docs.

MAX_VALUES = {np.uint8: 255, np.uint16: 65535, np.uint32: 4294967295, \
              np.uint64: 18446744073709551615}

try:
    image = MAX_VALUES[image.dtype] - image
except KeyError:
    raise ValueError, "Image must be array of unsigned integers."

Packages like PIL and cv2 provide convenient tools for inverting an image, but at this point in the code I have a numpy array -- more sophisticated analysis follows -- and I'd like to stick with numpy.

Upvotes: 2

Views: 1485

Answers (2)

unutbu
unutbu

Reputation: 879769

By the way, you do not need to define MAX_VALUES yourself. NumPy has them built-in:

import numpy as np
h, w = 100, 100
image = np.arange(h*w).reshape((h,w)).astype(np.uint8)
max_val = np.iinfo(image.dtype).max
print(max_val)
# 255
image ^= max_val

print(image)
# [[255 254 253 ..., 158 157 156]
#  [155 154 153 ...,  58  57  56]
#  [ 55  54  53 ..., 214 213 212]
#  ..., 
#  [ 27  26  25 ..., 186 185 184]
#  [183 182 181 ...,  86  85  84]
#  [ 83  82  81 ..., 242 241 240]]

Upvotes: 1

wflynny
wflynny

Reputation: 18521

Try doing

image ^= MAX_VALUES[image.dtype]

Upvotes: 4

Related Questions