Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Post a Comment for "Why Is The Output Of Element-wise Addition/subtraction Different Depending On Whether My Numpy Array Is Of Type Int64 Or Uint8?"