python - 为什么根据我的 numpy 数组的类型是 int64 还是 uint8,按元素加法/减法的输出会有所不同?

标签 python numpy

我正在进行图像比较并计算差异,并注意到按元素减法似乎仅在我使用 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]
diff = image1-image2

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

最佳答案

uint8 表示“8 位无符号整数”,并且仅具有 0-255 范围内的有效值。这是因为 256 个不同值是使用 8 位数据可以表示的最大数量。如果将两个 uint8 图像加在一起,很可能会在某个地方溢出 255。例如:

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

类似地,如果你减去两个图像,你很可能会得到负数 - 它再次回到范围的高端:

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

如果您需要像这样添加或减去图像,您将需要使用不会轻易下溢/溢出的数据类型(例如 int64 或 float),然后作为最后一步进行标准化并转换回 uint8 。

关于python - 为什么根据我的 numpy 数组的类型是 int64 还是 uint8,按元素加法/减法的输出会有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123792/

相关文章:

python - 在numpy下合并两个数组

python - 将numpy矩阵转换为嵌套字典的有效方法

python - Python中线性拟合约束通过第一个点

python - 我想从txt文件中提取x和y值

python - Django管理命令mysql报错

python 使用 matplotlib 绘制 json 文件数据

python - Python Tkinter OpenCV PIL图像调整大小以适合标签

python - 对称数组与 NumPy 的卷积 : why is the result shifted?

Python - 值错误 : operands could not be broadcast together with shapes

python - 读取 csv 时删除 pandas 中的索引列