megashigger
megashigger

Reputation: 9053

Why is the output of element-wise addition/subtraction different depending on whether my numpy array is of type int64 or uint8?

I'm doing image comparisons and calculating diff's and have noticed that element-wise subtraction only seems to work when I read the data in as a numpy array with dtype='int64' and not with dtype='uint8'. I'd like to switch to 'unit8' for image visualization reasons.

image1 = np.array(plt.imread('fixed_image.jpg'), dtype='int64')[:, :, 0:3]
image2 = np.array(plt.imread('fixed_image_2.jpg'), dtype='int64')[:, :, 0:3]
diff = image1-image2

In the code above, diff is only calculated correctly with dtype int64 and not with dtype uint8. Why is that?

Upvotes: 2

Views: 705

Answers (1)

wim
wim

Reputation: 363253

uint8 means "8 bit unsigned integer" and only has valid values in 0-255. This is because 256 distinct values is the maximum amount that can be represented using 8 bits of data. If you add two uint8 images together, you'll very likely overflow 255 somewhere. For example:

>>> np.uint8(130) + np.uint8(131)
5

Similarly, if you subtract two images, you'll very likely get negative numbers - which get wrapped around to the high end of the range again:

>>> np.uint8(130) - np.uint8(131)
255

If you need to add or subtract images like this, you'll want to work with a dtype that won't underflow/overflow as easily (e.g. int64 or float), then normalize and convert back to uint8 as the last step.

Upvotes: 2

Related Questions