为什么根据我的 numpy 数组是 int64 还是 uint8 类型,按元素加法/减法的输出会有所不同? [英] Why is the output of element-wise addition/subtraction different depending on whether my numpy array is of type int64 or uint8?

查看:83
本文介绍了为什么根据我的 numpy 数组是 int64 还是 uint8 类型,按元素加法/减法的输出会有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行图像比较和计算差异,并注意到元素减法似乎仅在我将数据作为 dtype='int64' 而不是 dtype='uint8' 的 numpy 数组读取时才起作用.出于图像可视化的原因,我想切换到unit8".

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]差异=图像1-图像2

在上面的代码中,diff 只能使用 dtype int64 而不是 dtype uint8 正确计算.这是为什么?

解决方案

uint8 表示8 位无符号整数",只有 0-255 之间的有效值.这是因为 256 个不同的值是使用 8 位数据可以表示的最大数量.如果将两个 uint8 图像添加在一起,则很可能会在某处溢出 255.例如:

<预><代码>>>>np.uint8(130) + np.uint8(131)5

同样地,如果你减去两个图像,你很可能会得到负数——它们又会回到范围的高端:

<预><代码>>>>np.uint8(130) - np.uint8(131)255

如果您需要像这样添加或减去图像,您将需要使用不会下溢/溢出那么容易的 dtype(例如 int64 或 float),然后作为最后一步标准化并转换回 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?

解决方案

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.

这篇关于为什么根据我的 numpy 数组是 int64 还是 uint8 类型,按元素加法/减法的输出会有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆