问题描述
如何在 Python 中正确地获取单个 RGB 像素的熵,或如下图所示。
试过这个:
def entropy(*X):
return np.sum(-p * np.log2(p) if p > 0 else 0 for p in
(np.mean(functools.reduce(np.logical_and,(predictions == c for predictions,c in zip(X,classes))))
for classes in itertools.product(*[set(x) for x in X])))
print('Entropy:',entropy(np.array([255,2,2]),np.array([255,1]),0]),1,0])))
print('Entropy:',2])))
print('Entropy:',entropy(np.array([0,255,100,200])))
结果:
Entropy: 1.584962500721156
Entropy: 0.9182958340544896
Entropy: 0.9182958340544896
Entropy: 0.9182958340544896
Entropy: 1.584962500721156
但是红色和绿色像素的熵相同,似乎无法区分,并且看起来与下表不同。我做错了什么以及如何正确地做到这一点?
解决方法
如果有帮助,试试这个
def entropy(labels,base=None):
value,counts = np.unique(labels,return_counts=True)
norm_counts = counts / counts.sum()
print(norm_counts)
e = 2.718281828
base = e if base is None else base
return -(norm_counts * np.log(norm_counts)/np.log(base)).sum()
f = np.array([[[[255,10,2],[255,1],0],1,2,0]]]])
h = entropy(f,2)
print('h=',h)