问题在于np.mean 函数,因为它不舍入为整数并返回浮点数。
import numpy as np
import skimage.measure
a = (10 * np.random.randn(10,10) + 127).astype(np.uint8)
a
Out[4]:
array([[121, 124, 139, 129, 130, 114, 127, 96, 114, 135],
[127, 132, 102, 142, 119, 107, 138, 130, 141, 132],
[113, 132, 132, 118, 121, 120, 142, 115, 124, 128],
[127, 121, 129, 129, 121, 119, 126, 113, 128, 116],
[144, 131, 123, 131, 130, 137, 140, 142, 127, 128],
[127, 126, 124, 115, 127, 125, 122, 126, 147, 132],
[118, 119, 117, 117, 133, 149, 122, 120, 116, 138],
[147, 147, 127, 117, 123, 123, 136, 121, 139, 129],
[142, 129, 113, 111, 130, 116, 137, 127, 106, 148],
[132, 141, 141, 142, 119, 132, 126, 115, 131, 122]], dtype=uint8)
b = skimage.measure.block_reduce(a, block_size = (2,2), func=np.mean)
b
Out[6]:
array([[ 126. , 128. , 117.5 , 122.75, 130.5 ],
[ 123.25, 127. , 120.25, 124. , 124. ],
[ 132. , 123.25, 129.75, 132.5 , 133.5 ],
[ 132.75, 119.5 , 132. , 124.75, 130.5 ],
[ 136. , 126.75, 124.25, 126.25, 126.75]])
这可能会给您自己的逻辑带来有趣的副作用。它肯定会与 matplotlibs 直方图函数配合使用,因为具有浮点数会使它对如何放置 bin 边界有不同的看法。
看看这个:
a = (10 * np.random.randn(200,200) + 127).astype(np.uint8)
b = skimage.measure.block_reduce(a, block_size = (2,2), func=np.mean)
hist(b.ravel(), bins=255)
hist 函数返回的数组中的白色位实际上为零。如果你在我的玩具示例中强制四舍五入,情况会变得更糟:
hist(b.ravel().astype(np.uint8), bins=255)
给它分箱和范围可以解决问题。即使你拉近了
hist(b.ravel().astype(np.uint8), bins=255, range=(0,255))