可以建议使用
np.unique和
np.bincount获得最主要颜色的两种方法。另外,在链接的页面中,它是
bincount作为一种更快的替代方法讨论的,因此这可能是可行的方法。
方法1
def unique_count_app(a): colors, count = np.unique(a.reshape(-1,a.shape[-1]), axis=0, return_counts=True) return colors[count.argmax()]
方法#2
def bincount_app(a): a2D = a.reshape(-1,a.shape[-1]) col_range = (256, 256, 256) # generically : a2D.max(0)+1 a1D = np.ravel_multi_index(a2D.T, col_range) return np.unravel_index(np.bincount(a1D).argmax(), col_range)
1000 x 1000在宽范围内对彩色图像进行验证和计时,以
[0,9)确保可重现的结果-
In [28]: np.random.seed(0) ...: a = np.random.randint(0,9,(1000,1000,3)) ...: ...: print unique_count_app(a) ...: print bincount_app(a)[4 7 2](4, 7, 2)In [29]: %timeit unique_count_app(a)1 loop, best of 3: 820 ms per loopIn [30]: %timeit bincount_app(a)100 loops, best of 3: 11.7 ms per loop
进一步提升
在利用进一步推动
multi-core与
numexpr模块大数据-
import numexpr as nedef bincount_numexpr_app(a): a2D = a.reshape(-1,a.shape[-1]) col_range = (256, 256, 256) # generically : a2D.max(0)+1 eval_params = {'a0':a2D[:,0],'a1':a2D[:,1],'a2':a2D[:,2], 's0':col_range[0],'s1':col_range[1]} a1D = ne.evaluate('a0*s0*s1+a1*s0+a2',eval_params) return np.unravel_index(np.bincount(a1D).argmax(), col_range)
时间-
In [90]: np.random.seed(0) ...: a = np.random.randint(0,9,(1000,1000,3))In [91]: %timeit unique_count_app(a) ...: %timeit bincount_app(a) ...: %timeit bincount_numexpr_app(a)1 loop, best of 3: 843 ms per loop100 loops, best of 3: 12 ms per loop100 loops, best of 3: 8.94 ms per loop
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)