arrays - np.diff() 在图像中的数组上使用时给出不正确的输出
问题描述
我有一个通过读取图像创建的 np.array 。我对创建交替像素值之间的差异感兴趣。因此我做了如下切片。
roi_pixels = np.array(cropped_image[-250:, -1280:])
roi_pixels_even = roi_pixels[::,::2]
roi_pixels_odd = roi_pixels[::,1::2]
但是,当我在这些数组上执行 np.diff 时,我没有正确理解差异。每当差异 i 为负时,差异就会被计算为一个巨大的数字(如下所示差异的图片)。我只强调了 3 个值,但还有更多(所有值都超过 60K)。
但是,当我使用以下这些值创建一个全新的数组并使用 np.diff() 方法时,一切都很好!!!谁能帮助我在从图像创建的数组中正确获取它?
x = np.array([1545, 1661, 1782, 1992, 1899, 1981, 1980, 1974, 2049, 2033, 2059,
2049, 2009, 1925, 1710, 1725, 1715, 1643, 1454, 1289, 979, 676,
649, 637, 715, 763, 787, 769, 788, 822])
If I use abs(np.diff(x)), output is as below
array([116, 121, 210, 93, 82, 1, 6, 75, 16, 26, 10, 40, 84,
215, 15, 10, 72, 189, 165, 310, 303, 27, 12, 78, 48, 24,
18, 19, 34]
If I use np.diff(x), output is as below
array([ 116, 121, 210, -93, 82, -1, -6, 75, -16, 26, -10,
-40, -84, -215, 15, -10, -72, -189, -165, -310, -303, -27,
-12, 78, 48, 24, -18, 19, 34])
解决方案
np.diff
返回与输入数组具有相同 dtype 的数组。如果这是一个无符号 dtype 负整数,则它们的位模式将转换为 uint dtype,从而产生高整数。
import numpy as np
np.random.seed(100)
arr = np.random.randint( 2000, size = 10, dtype = np.uint16)
arr
# array([1544, 796, 792, 976, 1859, 1859, 1895, 379, 1879, 1197], dtype=uint16)
np.diff(arr) # arr has dtype uint16
# array([64788, 65532, 184, 883, 0, 36, 64020, 1500, 64854], dtype=uint16)
# The result has dtype uint16
signed = arr.astype( np.int16 ) # signed has dtype int16 ( a signed type )
np.diff( signed )
# array([ -748, -4, 184, 883, 0, 36, -1516, 1500, -682], dtype=int16)
# The result has dtype int16
int16 的有符号和无符号版本之间的关系如下所示。
# Take dif as int32 of np.diff( signed )
dif = np.diff( signed ).astype( np.int32 )
dif[ dif < 0 ] += 0x10000 # 2 ** 16 in hex
# Add 2 ** 16 to any negative results
dif
# array([64788, 65532, 184, 883, 0, 36, 64020, 1500, 64854])
# dif == np.diff( arr )
( dif == np.diff(arr) ).all()
# True
推荐阅读
- c - 如何在 C 中的 switch 中使用格式说明符
- php - 重定向到特定的 URL?
- c++ - static_cast 复合体
复杂的 在 C++ 中 - flutter - 如何在颤动中使用拇指创建一个范围滑块作为png图像
- javascript - 如何从科尔多瓦项目中调用图书馆的主要活动
- php - 交货报价 404 Not Found
- html - 如何从 textarea 元素中删除调整大小的角?
- ajax - 属性“ScriptServiceAttribute”无法应用于“MethodName”,因为该属性在此声明类型上无效
- c# - 如何从类中添加另一个输入
- php - 如何按最小值计算产品总价。Woocommerce中的数量订单?