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

后端 未结 1 643
独厮守ぢ
独厮守ぢ 2021-01-21 21:42

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=\'int6

相关标签:
1条回答
  • 2021-01-21 22:13

    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.

    0 讨论(0)
提交回复
热议问题