问题出在
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]])
这可能会给你的逻辑带来有趣的副作用。它确实会影响到 matplotlib 的直方图函数,因为使用浮点数会让它对如何放置箱体边界产生不同的想法。
看看这个:
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)
给定bins和range可以解决问题。即使您缩放到很近的距离。
hist(b.ravel().astype(np.uint8), bins=255, range=(0,255))